import { useState } from 'react';
import { useForm } from '@inertiajs/react';
import { 
    Dialog, 
    DialogContent, 
    DialogDescription, 
    DialogFooter, 
    DialogHeader, 
    DialogTitle 
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { UploadCloud, FileSpreadsheet, AlertTriangle, CheckCircle, Download } from 'lucide-react';
import { toast } from 'sonner';

interface BulkImportModalProps {
    isOpen: boolean;
    onClose: () => void;
    importUrl: string;
    sampleHeaders: string[];
    sampleRows: string[][];
    title: string;
}

export function BulkImportModal({
    isOpen,
    onClose,
    importUrl,
    sampleHeaders,
    sampleRows,
    title
}: BulkImportModalProps) {
    const [file, setFile] = useState<File | null>(null);
    const { setData, post, processing, errors, reset, clearErrors } = useForm({
        file: null as File | null
    });

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            const selectedFile = e.target.files[0];
            setFile(selectedFile);
            setData('file', selectedFile);
            clearErrors();
        }
    };

    const handleDownloadTemplate = () => {
        const headerRow = sampleHeaders.join(',');
        const contentRows = sampleRows.map(row => row.map(cell => `"${cell.replace(/"/g, '""')}"`).join(','));
        const csvContent = "data:text/csv;charset=utf-8," + [headerRow, ...contentRows].join('\n');
        const encodedUri = encodeURI(csvContent);
        
        const link = document.createElement("a");
        link.setAttribute("href", encodedUri);
        link.setAttribute("download", `${title.toLowerCase().replace(/[^a-z0-9]/g, '_')}_template.csv`);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        toast.success('Template CSV downloaded successfully.');
    };

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (!file) {
            toast.error('Please select a file to import.');
            return;
        }

        post(importUrl, {
            onSuccess: () => {
                toast.success('Records imported successfully!');
                handleClose();
            },
            onError: () => {
                toast.error('Bulk import failed. Please check the validation errors.');
            }
        });
    };

    const handleClose = () => {
        setFile(null);
        reset();
        clearErrors();
        onClose();
    };

    return (
        <Dialog open={isOpen} onOpenChange={handleClose}>
            <DialogContent className="sm:max-w-[480px] rounded-3xl border border-zinc-200/80 bg-white/95 p-6 shadow-2xl backdrop-blur-2xl dark:border-zinc-800/80 dark:bg-zinc-900/95">
                <DialogHeader className="space-y-1.5 text-left">
                    <DialogTitle className="text-lg font-black tracking-tight text-zinc-900 dark:text-zinc-50 flex items-center gap-2">
                        <FileSpreadsheet className="size-5 text-indigo-500" />
                        {title}
                    </DialogTitle>
                    <DialogDescription className="text-xs text-zinc-500 dark:text-zinc-400">
                        Upload a CSV or JSON file containing templates to import them in bulk into your active registry workspace.
                    </DialogDescription>
                </DialogHeader>

                <form onSubmit={handleSubmit} className="space-y-5 pt-3">
                    {/* Template Downloader */}
                    <div className="p-4 rounded-2xl bg-zinc-50/50 dark:bg-zinc-950/20 border border-zinc-150 dark:border-zinc-800 flex items-center justify-between gap-4">
                        <div>
                            <h4 className="text-xs font-bold text-zinc-800 dark:text-zinc-250">Sample Import Template</h4>
                            <p className="text-[10px] text-zinc-450 mt-0.5">Includes required headers and sample data rows.</p>
                        </div>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={handleDownloadTemplate}
                            className="h-8 text-[10px] font-bold rounded-lg flex items-center gap-1 shrink-0 border-zinc-250 bg-white dark:bg-zinc-950 dark:border-zinc-800"
                        >
                            <Download className="size-3" /> Get CSV
                        </Button>
                    </div>

                    {/* Drag and Drop Zone */}
                    <div className="relative border-2 border-dashed border-zinc-200 dark:border-zinc-800 rounded-3xl p-8 text-center bg-zinc-50/20 dark:bg-zinc-950/10 hover:border-indigo-400 dark:hover:border-indigo-900 transition-colors">
                        <input
                            type="file"
                            accept=".csv, .json, text/csv, application/json"
                            onChange={handleFileChange}
                            className="absolute inset-0 w-full h-full opacity-0 cursor-pointer z-10"
                        />
                        <div className="flex flex-col items-center justify-center space-y-2">
                            <div className="p-3 bg-indigo-50 dark:bg-indigo-950/40 rounded-2xl border border-indigo-100 dark:border-indigo-900/50 text-indigo-500">
                                <UploadCloud className="size-6 animate-bounce" />
                            </div>
                            {file ? (
                                <div className="space-y-1">
                                    <p className="text-xs font-extrabold text-zinc-900 dark:text-zinc-100 truncate max-w-[320px]">
                                        📄 {file.name}
                                    </p>
                                    <p className="text-[10px] text-zinc-500">
                                        {(file.size / 1024).toFixed(1)} KB &bull; Ready to submit
                                    </p>
                                </div>
                            ) : (
                                <div className="space-y-1">
                                    <p className="text-xs font-extrabold text-zinc-700 dark:text-zinc-350">
                                        Choose import file or drag here
                                    </p>
                                    <p className="text-[10px] text-zinc-450">
                                        Accepts .csv or .json files up to 2MB
                                    </p>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Error Alerts */}
                    {Object.keys(errors).length > 0 && (
                        <div className="p-3.5 rounded-2xl bg-rose-50 dark:bg-rose-950/20 border border-rose-100 dark:border-rose-900/50 flex items-start gap-2.5">
                            <AlertTriangle className="size-4 text-rose-500 shrink-0 mt-0.5" />
                            <div className="space-y-1">
                                <h5 className="text-[10px] font-extrabold text-rose-700 dark:text-rose-450 uppercase tracking-wide">Validation Issues</h5>
                                <ul className="list-disc list-inside text-[10px] text-rose-650 dark:text-rose-400 space-y-0.5 leading-relaxed font-semibold">
                                    {Object.entries(errors).map(([key, val]) => (
                                        <li key={key}>{val}</li>
                                    ))}
                                </ul>
                            </div>
                        </div>
                    )}

                    {/* Submit Actions */}
                    <DialogFooter className="flex gap-2">
                        <Button
                            type="button"
                            variant="ghost"
                            onClick={handleClose}
                            disabled={processing}
                            className="rounded-xl h-11 text-xs font-bold shrink-0"
                        >
                            Cancel
                        </Button>
                        <Button
                            type="submit"
                            disabled={processing || !file}
                            className="flex-1 rounded-xl h-11 text-xs font-bold bg-indigo-600 hover:bg-indigo-500 text-white shadow-lg"
                        >
                            {processing ? 'Processing Import...' : 'Import Records'}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
