"use client";

import { useState, useEffect, useTransition } from "react";
import {
    Download, FileSpreadsheet, X, Loader2, Check,
    Eye, RotateCcw, FileText, ChevronDown, ChevronUp
} from "lucide-react";
import {
    exportCandidatesCSV,
    getExportPreview,
    EXPORT_FIELDS,
    EXPORT_TEMPLATES,
    type ExportFilters,
} from "@/app/actions/exportActions";

interface Props {
    isOpen: boolean;
    onClose: () => void;
    defaultFilters?: ExportFilters;
    preSelectedIds?: string[];
}

export function ExportModal({ isOpen, onClose, defaultFilters, preSelectedIds }: Props) {
    const [selectedFields, setSelectedFields] = useState<Set<string>>(
        new Set(EXPORT_FIELDS.filter(f => f.defaultIncluded).map(f => f.key))
    );
    const [activeTemplate, setActiveTemplate] = useState<string | null>("basic");
    const [showPreview, setShowPreview] = useState(false);
    const [preview, setPreview] = useState<any[] | null>(null);
    const [totalCount, setTotalCount] = useState(0);
    const [isPending, startTransition] = useTransition();
    const [showFieldGroups, setShowFieldGroups] = useState<Record<string, boolean>>({
        Candidate: true, Application: true, Job: true, Scoring: false, Pipeline: false,
    });
    const [downloadReady, setDownloadReady] = useState(false);

    // Group fields
    const groups = Array.from(new Set(EXPORT_FIELDS.map(f => f.group)));

    useEffect(() => {
        if (activeTemplate) {
            const template = EXPORT_TEMPLATES.find(t => t.id === activeTemplate);
            if (template) setSelectedFields(new Set(template.fields));
        }
    }, [activeTemplate]);

    if (!isOpen) return null;

    const toggleField = (key: string) => {
        setSelectedFields(prev => {
            const next = new Set(prev);
            if (next.has(key)) next.delete(key);
            else next.add(key);
            return next;
        });
        setActiveTemplate(null); // Custom selection breaks template
    };

    const toggleGroup = (group: string) => {
        const groupFields = EXPORT_FIELDS.filter(f => f.group === group);
        const allSelected = groupFields.every(f => selectedFields.has(f.key));
        setSelectedFields(prev => {
            const next = new Set(prev);
            for (const f of groupFields) {
                if (allSelected) next.delete(f.key);
                else next.add(f.key);
            }
            return next;
        });
        setActiveTemplate(null);
    };

    const handlePreview = () => {
        startTransition(async () => {
            const r = await getExportPreview(defaultFilters || {}, Array.from(selectedFields));
            if (r.success) {
                setPreview(r.preview || null);
                setTotalCount(r.totalCount || 0);
                setShowPreview(true);
            }
        });
    };

    const handleExport = () => {
        startTransition(async () => {
            const r = await exportCandidatesCSV(defaultFilters || {}, Array.from(selectedFields));
            if (r.success && r.csvContent) {
                // Trigger download
                const blob = new Blob([r.csvContent], { type: "text/csv;charset=utf-8;" });
                const url = URL.createObjectURL(blob);
                const link = document.createElement("a");
                link.href = url;
                link.download = `candidates_export_${new Date().toISOString().slice(0, 10)}.csv`;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                URL.revokeObjectURL(url);
                setDownloadReady(true);
                setTimeout(() => setDownloadReady(false), 3000);
            }
        });
    };

    const handleReset = () => {
        setSelectedFields(new Set(EXPORT_FIELDS.filter(f => f.defaultIncluded).map(f => f.key)));
        setActiveTemplate("basic");
        setShowPreview(false);
        setPreview(null);
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
            <div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={onClose} />
            <div className="relative bg-white rounded-2xl shadow-2xl w-full max-w-2xl mx-4 max-h-[85vh] flex flex-col animate-in fade-in slide-in-from-bottom-4">
                {/* Header */}
                <div className="flex items-center gap-3 p-5 border-b border-slate-100">
                    <div className="p-2.5 bg-emerald-50 rounded-xl">
                        <FileSpreadsheet className="w-5 h-5 text-emerald-600" />
                    </div>
                    <div className="flex-1">
                        <h2 className="text-base font-bold text-slate-900">Export Candidates</h2>
                        <p className="text-xs text-slate-500">Select fields and download as CSV</p>
                    </div>
                    <button onClick={onClose} className="p-2 text-slate-400 hover:text-slate-600 rounded-lg hover:bg-slate-100 transition-colors">
                        <X className="w-5 h-5" />
                    </button>
                </div>

                {/* Body */}
                <div className="flex-1 overflow-y-auto p-5 space-y-5">
                    {/* Templates */}
                    <div>
                        <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">Quick Templates</p>
                        <div className="grid grid-cols-2 gap-2">
                            {EXPORT_TEMPLATES.map(t => (
                                <button
                                    key={t.id}
                                    onClick={() => setActiveTemplate(t.id)}
                                    className={`text-left p-3 rounded-xl border transition-all ${activeTemplate === t.id
                                            ? "border-emerald-400 bg-emerald-50 shadow-sm"
                                            : "border-slate-200 hover:border-slate-300 bg-white"
                                        }`}
                                >
                                    <p className="text-sm font-medium text-slate-800">{t.name}</p>
                                    <p className="text-[10px] text-slate-500 mt-0.5">{t.description}</p>
                                    <p className="text-[10px] text-emerald-600 mt-1">{t.fields.length} fields</p>
                                </button>
                            ))}
                        </div>
                    </div>

                    {/* Field Selector */}
                    <div>
                        <div className="flex items-center justify-between mb-2">
                            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider">
                                Fields ({selectedFields.size} selected)
                            </p>
                            <button onClick={handleReset} className="text-xs text-slate-400 hover:text-slate-600 flex items-center gap-1">
                                <RotateCcw className="w-3 h-3" /> Reset
                            </button>
                        </div>
                        <div className="space-y-2">
                            {groups.map(group => {
                                const groupFields = EXPORT_FIELDS.filter(f => f.group === group);
                                const allSelected = groupFields.every(f => selectedFields.has(f.key));
                                const someSelected = groupFields.some(f => selectedFields.has(f.key));
                                const isExpanded = showFieldGroups[group] !== false;

                                return (
                                    <div key={group} className="border border-slate-100 rounded-xl overflow-hidden">
                                        <button
                                            onClick={() => setShowFieldGroups(p => ({ ...p, [group]: !isExpanded }))}
                                            className="flex items-center gap-2 w-full p-3 text-left hover:bg-slate-50 transition-colors"
                                        >
                                            <input
                                                type="checkbox"
                                                checked={allSelected}
                                                ref={el => { if (el) el.indeterminate = someSelected && !allSelected; }}
                                                onChange={() => toggleGroup(group)}
                                                onClick={e => e.stopPropagation()}
                                                className="rounded border-slate-300"
                                            />
                                            <span className="text-sm font-medium text-slate-700 flex-1">{group}</span>
                                            <span className="text-[10px] text-slate-400">
                                                {groupFields.filter(f => selectedFields.has(f.key)).length}/{groupFields.length}
                                            </span>
                                            {isExpanded ? <ChevronUp className="w-3.5 h-3.5 text-slate-300" /> : <ChevronDown className="w-3.5 h-3.5 text-slate-300" />}
                                        </button>
                                        {isExpanded && (
                                            <div className="px-3 pb-3 grid grid-cols-2 gap-1">
                                                {groupFields.map(f => (
                                                    <label
                                                        key={f.key}
                                                        className={`flex items-center gap-2 px-2.5 py-1.5 rounded-lg cursor-pointer transition-colors ${selectedFields.has(f.key) ? "bg-emerald-50" : "hover:bg-slate-50"
                                                            }`}
                                                    >
                                                        <input
                                                            type="checkbox"
                                                            checked={selectedFields.has(f.key)}
                                                            onChange={() => toggleField(f.key)}
                                                            className="rounded border-slate-300"
                                                        />
                                                        <span className="text-xs text-slate-700">{f.label}</span>
                                                    </label>
                                                ))}
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>

                    {/* Preview */}
                    {showPreview && preview && (
                        <div>
                            <p className="text-xs font-bold text-slate-500 uppercase tracking-wider mb-2">
                                Preview ({totalCount} total records)
                            </p>
                            <div className="overflow-x-auto border border-slate-200 rounded-xl">
                                <table className="text-xs min-w-full">
                                    <thead>
                                        <tr className="bg-slate-50">
                                            {EXPORT_FIELDS.filter(f => selectedFields.has(f.key)).map(f => (
                                                <th key={f.key} className="px-3 py-2 text-left font-bold text-slate-500 whitespace-nowrap">
                                                    {f.label}
                                                </th>
                                            ))}
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-slate-50">
                                        {preview.map((row, i) => (
                                            <tr key={i} className="hover:bg-slate-50/50">
                                                {EXPORT_FIELDS.filter(f => selectedFields.has(f.key)).map(f => (
                                                    <td key={f.key} className="px-3 py-2 text-slate-600 whitespace-nowrap max-w-[150px] truncate">
                                                        {row[f.key] ?? "—"}
                                                    </td>
                                                ))}
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    )}
                </div>

                {/* Footer */}
                <div className="p-4 border-t border-slate-100 bg-slate-50 flex items-center gap-3">
                    <button
                        onClick={handlePreview}
                        disabled={isPending || selectedFields.size === 0}
                        className="flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-xl hover:bg-slate-50 transition-colors disabled:opacity-50"
                    >
                        {isPending && !downloadReady ? <Loader2 className="w-4 h-4 animate-spin" /> : <Eye className="w-4 h-4" />}
                        Preview
                    </button>
                    <div className="flex-1" />
                    <button
                        onClick={onClose}
                        className="px-4 py-2.5 text-sm text-slate-500 hover:text-slate-700 transition-colors"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={handleExport}
                        disabled={isPending || selectedFields.size === 0}
                        className={`flex items-center gap-2 px-5 py-2.5 text-sm font-bold rounded-xl transition-all ${downloadReady
                                ? "text-emerald-700 bg-emerald-100 border border-emerald-200"
                                : "text-white bg-emerald-600 hover:bg-emerald-700"
                            } disabled:opacity-50`}
                    >
                        {isPending ? (
                            <Loader2 className="w-4 h-4 animate-spin" />
                        ) : downloadReady ? (
                            <Check className="w-4 h-4" />
                        ) : (
                            <Download className="w-4 h-4" />
                        )}
                        {downloadReady ? "Downloaded!" : "Export CSV"}
                    </button>
                </div>
            </div>
        </div>
    );
}
