import { Head, router, useForm } from '@inertiajs/react';
import { Plus, Trash2, Edit, Award, Search, ArrowUpDown, FileDown, FileUp } from 'lucide-react';
import { useState, useMemo } from 'react';
import { toast } from 'sonner';
import { store as storeLicence, update as updateLicence, destroy as destroyLicence } from '@/routes/settings/licence-master';
import { BulkImportModal } from '@/components/bulk-import-modal';
import { Pagination } from '@/components/pagination';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import AppLayout from '@/layouts/app-layout';

interface Licence {
    id: number;
    name: string;
    required_for: string | null;
}

interface Props {
    licences: Licence[];
}

type SortField = 'name' | 'required_for';
type SortOrder = 'asc' | 'desc';

export default function LicenceMasterPage({ licences }: Props) {
    const [isCreateOpen, setIsCreateOpen] = useState(false);
    const [editingLicence, setEditingLicence] = useState<Licence | null>(null);

    // Filters and Sorting State
    const [searchQuery, setSearchQuery] = useState('');
    const [sortField, setSortField] = useState<SortField>('name');
    const [sortOrder, setSortOrder] = useState<SortOrder>('asc');

    // Pagination & Bulk Import/Export State
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [isImportOpen, setIsImportOpen] = useState(false);

    const createForm = useForm({
        name: '',
        required_for: '',
    });

    const editForm = useForm({
        name: '',
        required_for: '',
    });

    const handleCreate = (e: React.FormEvent) => {
        e.preventDefault();
        createForm.post(storeLicence.url(), {
            onSuccess: () => {
                setIsCreateOpen(false);
                createForm.reset();
                toast.success('Licence created successfully.');
            },
            onError: (errors) => {
                toast.error(errors.name || 'Failed to create licence.');
            },
        });
    };

    const handleEditClick = (licence: Licence) => {
        setEditingLicence(licence);
        editForm.setData({
            name: licence.name,
            required_for: licence.required_for || '',
        });
    };

    const handleUpdate = (e: React.FormEvent) => {
        e.preventDefault();

        if (!editingLicence) {
            return;
        }

        editForm.put(
            updateLicence.url(editingLicence.id),
            {
                onSuccess: () => {
                    setEditingLicence(null);
                    toast.success('Licence updated successfully.');
                },
                onError: (errors) => {
                    toast.error(errors.name || 'Failed to update licence.');
                },
            },
        );
    };

    const handleDelete = (id: number) => {
        if (confirm('Are you sure you want to delete this licence?')) {
            router.delete(destroyLicence.url(id), {
                onSuccess: () => {
                    toast.success('Licence deleted successfully.');
                },
            });
        }
    };

    const handleSort = (field: SortField) => {
        if (sortField === field) {
            setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
        } else {
            setSortField(field);
            setSortOrder('asc');
        }
    };

    // Filtered and Sorted list
    const processedLicences = useMemo(() => {
        let list = [...licences];

        // Search filter
        if (searchQuery.trim() !== '') {
            const query = searchQuery.toLowerCase();
            list = list.filter(
                (l) =>
                    l.name.toLowerCase().includes(query) ||
                    (l.required_for &&
                        l.required_for.toLowerCase().includes(query)),
            );
        }

        // Sorting
        list.sort((a, b) => {
            let valA: string = '';
            let valB: string = '';

            if (sortField === 'name') {
                valA = a.name.toLowerCase();
                valB = b.name.toLowerCase();
            } else if (sortField === 'required_for') {
                valA = (a.required_for || '').toLowerCase();
                valB = (b.required_for || '').toLowerCase();
            }

            if (valA < valB) {
                return sortOrder === 'asc' ? -1 : 1;
            }

            if (valA > valB) {
                return sortOrder === 'asc' ? 1 : -1;
            }

            return 0;
        });

        return list;
    }, [licences, searchQuery, sortField, sortOrder]);

    const paginatedLicences = useMemo(() => {
        const start = (currentPage - 1) * pageSize;

        return processedLicences.slice(start, start + pageSize);
    }, [processedLicences, currentPage, pageSize]);

    const handleSearchChange = (val: string) => {
        setSearchQuery(val);
        setCurrentPage(1);
    };

    const handleExportCSV = () => {
        const headers = ['Name', 'Required For'];
        const rows = processedLicences.map(lic => [
            lic.name,
            lic.required_for ?? ''
        ]);
        const csvContent = "data:text/csv;charset=utf-8," 
            + [headers.join(','), ...rows.map(e => e.map(val => `"${val.replace(/"/g, '""')}"`).join(','))].join('\n');
        const encodedUri = encodeURI(csvContent);
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", "licence_master_export.csv");
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        toast.success('Licences exported successfully.');
    };

    return (
        <>
            <Head title="Licence Master Compliance Registry" />
            <div className="from-zinc-550/20 min-h-screen w-full space-y-8 bg-gradient-to-b via-transparent to-transparent p-6 md:p-10">
                {/* Premium Gradient Header Banner */}
                <div className="from-emerald-600 relative flex flex-col items-start justify-between gap-6 overflow-hidden rounded-3xl border border-white/10 bg-gradient-to-r via-teal-600 to-indigo-500 p-8 text-white shadow-2xl md:flex-row md:items-center md:p-10">
                    <div className="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(255,255,255,0.15),transparent_50%)]" />
                    <div className="relative max-w-2xl space-y-2">
                        <span className="rounded-full border border-white/20 bg-white/20 px-3 py-1 text-[10px] font-extrabold tracking-widest text-white/90 uppercase backdrop-blur-md">
                            Compliance & Licensing
                        </span>
                        <h3 className="text-2xl font-extrabold tracking-tight md:text-3xl">
                            Licence Master Compliance Registry
                        </h3>
                        <p className="text-sm font-medium text-emerald-100">
                            Register platform certificates, software licenses,
                            regulatory clearances, and audit-ready compliance
                            scopes.
                        </p>
                    </div>
                    <div className="flex flex-wrap gap-2.5 shrink-0">
                        <Button
                            variant="outline"
                            onClick={handleExportCSV}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 hover:bg-white/20 px-4 py-6 font-bold text-white shadow-lg transition-all duration-300 hover:-translate-y-0.5"
                        >
                            <FileDown className="size-4" /> Export CSV
                        </Button>
                        <Button
                            variant="outline"
                            onClick={() => setIsImportOpen(true)}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white/10 hover:bg-white/20 px-4 py-6 font-bold text-white shadow-lg transition-all duration-300 hover:-translate-y-0.5"
                        >
                            <FileUp className="size-4" /> Bulk Import
                        </Button>
                        <Button
                            onClick={() => setIsCreateOpen(true)}
                            className="relative flex items-center gap-2 rounded-xl border border-white/20 bg-white px-5 py-6 font-bold text-emerald-950 shadow-lg transition-all duration-300 hover:-translate-y-0.5 hover:bg-zinc-100 hover:shadow-emerald-500/20"
                        >
                            <Plus className="size-4 stroke-[3px]" /> Add Compliance Certificate
                        </Button>
                    </div>
                </div>

                {/* Filters and Search Toolbar */}
                <div className="flex flex-col items-center gap-4 rounded-2xl border border-zinc-200/80 bg-white/60 p-5 shadow-sm backdrop-blur-2xl sm:flex-row dark:border-zinc-800/80 dark:bg-zinc-900/60">
                    <div className="relative w-full">
                        <Search className="absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-zinc-400" />
                        <Input
                            className="h-11 rounded-xl border-zinc-200 bg-white/80 pl-10 text-xs shadow-inner focus-visible:ring-emerald-500/50 dark:border-zinc-800 dark:bg-zinc-950/80"
                            placeholder="Search compliance certificates by name, requirements, or scope..."
                            value={searchQuery}
                            onChange={(e) => handleSearchChange(e.target.value)}
                        />
                    </div>
                </div>

                {processedLicences.length === 0 ? (
                    <Card className="flex flex-col items-center justify-center rounded-3xl border-2 border-dashed border-zinc-200 bg-white/30 p-16 text-center backdrop-blur-sm dark:border-zinc-800 dark:bg-zinc-950/10">
                        <div className="mb-4 animate-pulse rounded-full border border-emerald-100 bg-emerald-50 p-4 dark:border-emerald-900 dark:bg-emerald-950/50">
                            <Award className="size-8 text-emerald-500" />
                        </div>
                        <p className="text-base font-bold text-zinc-800 dark:text-zinc-200">
                            No matching certificates found
                        </p>
                        <p className="mt-1 text-xs text-zinc-400">
                            Register corporate compliance frameworks to keep
                            track of renewal terms and audits.
                        </p>
                    </Card>
                ) : (
                    <div className="overflow-hidden rounded-3xl border border-zinc-200/80 bg-white/60 shadow-xl backdrop-blur-2xl transition-all duration-500 dark:border-zinc-800/80 dark:bg-zinc-900/60">
                        <table className="w-full border-collapse text-left text-xs">
                            <thead>
                                <tr className="border-b border-zinc-200 bg-zinc-50/80 text-[10px] font-bold tracking-wider text-zinc-500 uppercase select-none dark:border-zinc-800 dark:bg-zinc-900/50">
                                    <th
                                        className="hover:text-emerald-600 w-[40%] cursor-pointer p-5 pl-8 transition-colors dark:hover:text-emerald-400"
                                        onClick={() => handleSort('name')}
                                    >
                                        <div className="flex items-center gap-1.5">
                                            Certificate Name{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th
                                        className="hover:text-emerald-600 cursor-pointer p-5 transition-colors dark:hover:text-emerald-400"
                                        onClick={() =>
                                            handleSort('required_for')
                                        }
                                    >
                                        <div className="flex items-center gap-1.5">
                                            Required Scope / Specifications{' '}
                                            <ArrowUpDown className="size-3.5 text-zinc-400" />
                                        </div>
                                    </th>
                                    <th className="w-[150px] p-5 pr-8 text-right">
                                        Actions
                                    </th>
                                </tr>
                            </thead>
                             <tbody className="divide-y divide-zinc-100 dark:divide-zinc-800/80">
                                {paginatedLicences.map((licence) => (
                                    <tr
                                        key={licence.id}
                                        className="group transition-all duration-300 hover:bg-emerald-50/10 dark:hover:bg-emerald-950/5"
                                    >
                                        <td className="p-5 pl-8 text-sm font-extrabold text-zinc-900 dark:text-zinc-100">
                                            <div className="flex items-center gap-2.5">
                                                <div className="flex size-8 shrink-0 items-center justify-center rounded-xl border border-emerald-100 bg-emerald-50 font-bold text-emerald-600 shadow-sm dark:border-emerald-950/50 dark:bg-emerald-950/50 dark:text-emerald-400">
                                                    <Award className="size-4" />
                                                </div>
                                                <span className="text-sm">
                                                    {licence.name}
                                                </span>
                                            </div>
                                        </td>
                                        <td className="text-zinc-650 dark:text-zinc-350 p-5 text-xs leading-relaxed font-semibold">
                                            {licence.required_for || (
                                                <span className="text-zinc-450 dark:text-zinc-550 font-medium italic">
                                                    Global infrastructure scope
                                                </span>
                                            )}
                                        </td>
                                        <td className="p-5 pr-8 text-right">
                                            <div className="flex items-center justify-end gap-1.5 opacity-0 transition-opacity duration-300 group-hover:opacity-100">
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="size-8 rounded-lg text-zinc-500 hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800"
                                                    onClick={() =>
                                                        handleEditClick(licence)
                                                    }
                                                >
                                                    <Edit className="size-3.5" />
                                                </Button>
                                                <Button
                                                    variant="ghost"
                                                    size="icon"
                                                    className="size-8 rounded-lg text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-950/20"
                                                    onClick={() =>
                                                        handleDelete(licence.id)
                                                    }
                                                >
                                                    <Trash2 className="size-3.5" />
                                                </Button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                        <Pagination
                            currentPage={currentPage}
                            pageSize={pageSize}
                            totalItems={processedLicences.length}
                            onPageChange={setCurrentPage}
                            onPageSizeChange={setPageSize}
                        />
                    </div>
                )}

                {/* Create Dialog */}
                <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Register Licence</DialogTitle>
                            <DialogDescription>
                                Add a new compliance licence configuration.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            onSubmit={handleCreate}
                            className="space-y-4 pt-2"
                        >
                            <div className="space-y-1">
                                <Label htmlFor="create-name">
                                    Licence Name
                                </Label>
                                <Input
                                    id="create-name"
                                    value={createForm.data.name}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'name',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="e.g. SOC 2 Type II Compliance"
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="create-required-for">
                                    Required For
                                </Label>
                                <Input
                                    id="create-required-for"
                                    value={createForm.data.required_for}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'required_for',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="e.g. AWS Production Infrastructure"
                                />
                            </div>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setIsCreateOpen(false)}
                                    className="rounded-xl"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={createForm.processing}
                                    className="rounded-xl"
                                >
                                    Create
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Edit Dialog */}
                <Dialog
                    open={!!editingLicence}
                    onOpenChange={(open) => !open && setEditingLicence(null)}
                >
                    <DialogContent className="max-w-sm rounded-2xl">
                        <DialogHeader>
                            <DialogTitle>Edit Licence</DialogTitle>
                            <DialogDescription>
                                Update compliance licence settings.
                            </DialogDescription>
                        </DialogHeader>
                        <form
                            onSubmit={handleUpdate}
                            className="space-y-4 pt-2"
                        >
                            <div className="space-y-1">
                                <Label htmlFor="edit-name">Licence Name</Label>
                                <Input
                                    id="edit-name"
                                    value={editForm.data.name}
                                    onChange={(e) =>
                                        editForm.setData('name', e.target.value)
                                    }
                                    required
                                />
                            </div>
                            <div className="space-y-1">
                                <Label htmlFor="edit-required-for">
                                    Required For
                                </Label>
                                <Input
                                    id="edit-required-for"
                                    value={editForm.data.required_for}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'required_for',
                                            e.target.value,
                                        )
                                    }
                                />
                            </div>
                            <DialogFooter className="pt-2">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setEditingLicence(null)}
                                    className="rounded-xl"
                                >
                                    Cancel
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={editForm.processing}
                                    className="rounded-xl"
                                >
                                    Save Changes
                                </Button>
                            </DialogFooter>
                        </form>
                    </DialogContent>
                </Dialog>

                {/* Bulk Import Modal */}
                <BulkImportModal
                    isOpen={isImportOpen}
                    onClose={() => setIsImportOpen(false)}
                    importUrl="/settings/licence-master/bulk-import"
                    sampleHeaders={['name', 'required_for']}
                    sampleRows={[
                        ['Form 29 (Test Licence)', 'FRD'],
                        ['Form 11 (Import Licence)', 'Plant'],
                        ['Manufacturing license', 'Plant']
                    ]}
                    title="Import Licences"
                />
            </div>
        </>
    );
}

LicenceMasterPage.layout = (page: React.ReactNode) => (
    <AppLayout>{page}</AppLayout>
);
