import { adminToast } from '@admin/components/ui/admin-toast';
import { CrudCreateLink } from '@admin/components/ui/crud-create-link';
import { DataTable, type DataTableColumn } from '@admin/components/ui/data-table';
import { useCrudPermissions } from '@admin/hooks/use-crud-permissions';
import { DeleteConfirmationModal } from '@admin/components/ui/delete-confirmation-modal';
import { formHelpClassName } from '@admin/components/ui/field-styles';
import { dashboardPersistentLayout } from '@admin/layouts/dashboard-page-layout';
import EditPricingPlan from '@admin/pages/pricing-plans/edit-pricing-plan';
import { cn } from '@admin/lib/utils';
import { Head } from '@inertiajs/react';
import { useState } from 'react';

type UnitOption = {
    id: number;
    name: string;
};

type PlanRow = {
    id: number;
    name: string;
    description: string;
    price: string;
    billing_period: string;
    pricing_unit_id: number | null;
    unit_name: string | null;
    unit_suffix: string | null;
    is_most_popular: boolean;
    is_featured: boolean;
    sort_order: number;
    status: boolean;
    created_at: string;
};

type PricingPlansIndexProps = {
    plans: PlanRow[];
    units: UnitOption[];
};

function formatPrice(row: PlanRow): string {
    if (row.unit_suffix) {
        return `${row.price}${row.unit_suffix}`;
    }

    if (row.billing_period === 'none') {
        return row.price;
    }

    if (row.billing_period === 'year') {
        return `${row.price}/year`;
    }

    if (row.billing_period === 'month') {
        return `${row.price}/month`;
    }

    return row.price;
}

function PricingPlansIndex({ plans, units }: PricingPlansIndexProps) {
    const { canEdit, canDelete } = useCrudPermissions('pricing-plan');
    const [isEditModalOpen, setIsEditModalOpen] = useState(false);
    const [initialData, setInitialData] = useState<PlanRow | null>(null);
    const [deleteModal, setDeleteModal] = useState<{ show: boolean; plan: PlanRow | null }>({
        show: false,
        plan: null,
    });

    const columns: DataTableColumn<PlanRow>[] = [
        { header: 'Order', key: 'sort_order', className: 'w-20' },
        { header: 'Name', key: 'name', truncate: true },
        { header: 'Description', key: 'description', truncate: true },
        {
            header: 'Price',
            key: 'price',
            render: (row) => formatPrice(row),
        },
        {
            header: 'Unit',
            key: 'unit_name',
            render: (row) => row.unit_name ?? '—',
        },
        {
            header: 'Popular',
            key: 'is_most_popular',
            render: (row) => (row.is_most_popular ? 'Yes' : '—'),
        },
        {
            header: 'Featured',
            key: 'is_featured',
            render: (row) => (row.is_featured ? 'Yes' : '—'),
        },
        { header: 'Status', key: 'status' },
    ];

    const handleEdit = async (row: PlanRow) => {
        try {
            const response = await fetch(`/admin/edit_pricing_plan/${row.id}`);
            if (!response.ok) {
                throw new Error('Failed to fetch pricing plan');
            }

            const planData = (await response.json()) as PlanRow;
            setInitialData(planData);
            setIsEditModalOpen(true);
        } catch {
            adminToast.error('Could not load pricing plan details');
        }
    };

    return (
        <>
            <Head title="Pricing plans" />

            <div className="grid grid-cols-12 gap-6">
                <div className="col-span-12">
                    <CrudCreateLink href={route('admin.pricing-plans.create')} label="Create pricing plan" resource="pricing-plan" />
                    <p className={cn('mb-4', formHelpClassName)}>
                        Featured plans appear on the homepage pricing section. All published plans appear on the Our Pricing page.
                    </p>
                    <DataTable
                        data={plans}
                        columns={columns}
                        title="Pricing plans"
                        itemsPerPage={10}
                        onEdit={canEdit ? handleEdit : undefined}
                        onDelete={canDelete ? (row) => setDeleteModal({ show: true, plan: row }) : undefined}
                        showEdit={canEdit}
                        showDelete={canDelete}
                        noDataText="No pricing plans found"
                    />
                </div>
            </div>

            <DeleteConfirmationModal
                isOpen={deleteModal.show}
                onClose={() => setDeleteModal({ show: false, plan: null })}
                itemName={deleteModal.plan?.name ?? 'this pricing plan'}
                itemType="pricing plan"
                deleteEndpoint={`/admin/api/delete_pricing_plan/${deleteModal.plan?.id ?? ''}`}
                loadingMessage="Deleting pricing plan..."
            />

            <EditPricingPlan
                isOpen={isEditModalOpen}
                onClose={() => setIsEditModalOpen(false)}
                initialData={initialData}
                units={units}
            />
        </>
    );
}

export default Object.assign(PricingPlansIndex, {
    layout: dashboardPersistentLayout('Pricing plans', 'Manage service pricing tiers'),
});
