"use client";

import { useState } from "react";
import { Loader2, Settings, X, Check, Clock, Shield, Mail, CheckSquare } from "lucide-react";
import { StageConfig, updateStageConfig } from "@/app/actions/stageConfigActions";

interface StageConfigPanelProps {
    stageId: string;
    stageName: string;
    initialConfig: StageConfig;
    onClose: () => void;
    onSaved?: () => void;
}

type Tab = "entry" | "exit" | "time";

export function StageConfigPanel({ stageId, stageName, initialConfig, onClose, onSaved }: StageConfigPanelProps) {
    const [config, setConfig] = useState<StageConfig>(initialConfig);
    const [tab, setTab] = useState<Tab>("entry");
    const [saving, setSaving] = useState(false);
    const [saved, setSaved] = useState(false);

    const updateEntry = (key: keyof StageConfig["entry"], value: any) =>
        setConfig(c => ({ ...c, entry: { ...c.entry, [key]: value } }));
    const updateExit = (key: keyof StageConfig["exit"], value: boolean) =>
        setConfig(c => ({ ...c, exit: { ...c.exit, [key]: value } }));
    const updateTime = (key: keyof StageConfig["timeLimit"], value: any) =>
        setConfig(c => ({ ...c, timeLimit: { ...c.timeLimit, [key]: value } }));

    const handleSave = async () => {
        setSaving(true);
        await updateStageConfig(stageId, config);
        setSaving(false);
        setSaved(true);
        setTimeout(() => setSaved(false), 2000);
        onSaved?.();
    };

    const TABS = [
        { key: "entry" as Tab, label: "Entry Actions", icon: Mail },
        { key: "exit" as Tab, label: "Exit Requirements", icon: Shield },
        { key: "time" as Tab, label: "Time Limits", icon: Clock },
    ];

    return (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-end sm:items-center justify-center p-4">
            <div className="bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[90vh] flex flex-col">
                {/* Header */}
                <div className="flex items-center justify-between p-5 border-b border-slate-100">
                    <div className="flex items-center gap-2">
                        <Settings className="w-5 h-5 text-primary" />
                        <div>
                            <h3 className="font-bold text-slate-800">Stage Configuration</h3>
                            <p className="text-xs text-slate-500">{stageName}</p>
                        </div>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-slate-100 rounded-lg"><X className="w-4 h-4" /></button>
                </div>

                {/* Tabs */}
                <div className="flex border-b border-slate-100">
                    {TABS.map(({ key, label, icon: Icon }) => (
                        <button
                            key={key}
                            onClick={() => setTab(key)}
                            className={`flex-1 flex items-center justify-center gap-1.5 px-3 py-3 text-xs font-bold transition-colors ${tab === key ? "border-b-2 border-primary text-primary" : "text-slate-500 hover:text-slate-700"}`}
                        >
                            <Icon className="w-3.5 h-3.5" /> {label}
                        </button>
                    ))}
                </div>

                {/* Content */}
                <div className="flex-1 overflow-y-auto p-5 space-y-5">
                    {tab === "entry" && (
                        <>
                            <Toggle
                                label="Send candidate email notification"
                                description="Automatically email the candidate when they enter this stage"
                                checked={config.entry.sendCandidateEmail}
                                onChange={v => updateEntry("sendCandidateEmail", v)}
                            />
                            {config.entry.sendCandidateEmail && (
                                <div className="ml-6 pl-4 border-l-2 border-slate-100">
                                    <label className="text-xs font-bold text-slate-500 mb-1.5 block">Email Template ID (optional)</label>
                                    <input
                                        value={config.entry.emailTemplate || ""}
                                        onChange={e => updateEntry("emailTemplate", e.target.value)}
                                        className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                                        placeholder="e.g. phone_screen_invite"
                                    />
                                </div>
                            )}
                            <Toggle
                                label="Auto-create recruiter task"
                                description="Create a to-do task for the recruiter when a candidate enters"
                                checked={config.entry.createTask}
                                onChange={v => updateEntry("createTask", v)}
                            />
                            {config.entry.createTask && (
                                <div className="ml-6 pl-4 border-l-2 border-slate-100 space-y-3">
                                    <div>
                                        <label className="text-xs font-bold text-slate-500 mb-1.5 block">Task Title</label>
                                        <input
                                            value={config.entry.taskTitle || ""}
                                            onChange={e => updateEntry("taskTitle", e.target.value)}
                                            className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                                            placeholder="e.g. Schedule phone screen"
                                        />
                                    </div>
                                    <div>
                                        <label className="text-xs font-bold text-slate-500 mb-1.5 block">Due in (days)</label>
                                        <input
                                            type="number" min={1} max={30}
                                            value={config.entry.taskDueDays || ""}
                                            onChange={e => updateEntry("taskDueDays", parseInt(e.target.value))}
                                            className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                                            placeholder="3"
                                        />
                                    </div>
                                </div>
                            )}
                        </>
                    )}

                    {tab === "exit" && (
                        <>
                            <p className="text-xs text-slate-400">Check the requirements that must be met before candidates can advance to the next stage.</p>
                            <Toggle label="Score must be added" description="Candidate must have a score before advancing" checked={config.exit.requireScore} onChange={v => updateExit("requireScore", v)} />
                            <Toggle label="Note must be added" description="At least one note must be written" checked={config.exit.requireNote} onChange={v => updateExit("requireNote", v)} />
                            <Toggle label="Interview must be scheduled" description="An interview must exist for this candidate" checked={config.exit.requireInterview} onChange={v => updateExit("requireInterview", v)} />
                            <Toggle label="Document must be uploaded" description="A file attachment is required" checked={config.exit.requireDocument} onChange={v => updateExit("requireDocument", v)} />
                            <Toggle label="Approval required to advance" description="A hiring manager must approve movement" checked={config.exit.requireApproval} onChange={v => updateExit("requireApproval", v)} />
                        </>
                    )}

                    {tab === "time" && (
                        <>
                            <div>
                                <label className="text-xs font-bold text-slate-500 block mb-1.5">⚠️ Warning after (days)</label>
                                <input
                                    type="number" min={1}
                                    value={config.timeLimit.warningAfterDays || ""}
                                    onChange={e => updateTime("warningAfterDays", parseInt(e.target.value))}
                                    className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                                    placeholder="e.g. 5 — alert recruiter if candidate sits here too long"
                                />
                            </div>
                            <div>
                                <label className="text-xs font-bold text-slate-500 block mb-1.5">🚫 Max days before auto-action</label>
                                <input
                                    type="number" min={1}
                                    value={config.timeLimit.maxDays || ""}
                                    onChange={e => updateTime("maxDays", parseInt(e.target.value))}
                                    className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                                    placeholder="e.g. 14"
                                />
                            </div>
                            {config.timeLimit.maxDays && (
                                <div>
                                    <label className="text-xs font-bold text-slate-500 block mb-1.5">Auto action after max days</label>
                                    <select
                                        value={config.timeLimit.autoAction || ""}
                                        onChange={e => updateTime("autoAction", e.target.value || null)}
                                        className="w-full px-3 py-2 text-sm border border-slate-200 rounded-xl outline-none bg-white focus:ring-2 focus:ring-primary/30 focus:border-primary"
                                    >
                                        <option value="">— none —</option>
                                        <option value="send_email">Send follow-up email</option>
                                        <option value="flag">Flag for review</option>
                                        <option value="archive">Archive application</option>
                                    </select>
                                </div>
                            )}
                        </>
                    )}
                </div>

                {/* Footer */}
                <div className="p-5 border-t border-slate-100 flex gap-2">
                    <button onClick={onClose} className="flex-1 px-4 py-2.5 text-sm font-medium text-slate-600 bg-slate-100 rounded-xl hover:bg-slate-200 transition-colors">
                        Cancel
                    </button>
                    <button
                        onClick={handleSave}
                        disabled={saving}
                        className="flex-1 px-4 py-2.5 text-sm font-bold text-white bg-primary rounded-xl hover:bg-primary/90 transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
                    >
                        {saving ? <><Loader2 className="w-4 h-4 animate-spin" /> Saving...</> : saved ? <><Check className="w-4 h-4" /> Saved!</> : <><Check className="w-4 h-4" /> Save Config</>}
                    </button>
                </div>
            </div>
        </div>
    );
}

function Toggle({ label, description, checked, onChange }: { label: string; description?: string; checked: boolean; onChange: (v: boolean) => void }) {
    return (
        <div className="flex items-start gap-3 p-3 rounded-xl hover:bg-slate-50 transition-colors">
            <button
                role="switch"
                aria-checked={checked}
                onClick={() => onChange(!checked)}
                className={`relative w-10 h-6 rounded-full flex-shrink-0 mt-0.5 transition-colors duration-200 ${checked ? "bg-primary" : "bg-slate-200"}`}
            >
                <span className={`absolute top-1 left-1 w-4 h-4 bg-white rounded-full shadow transition-transform duration-200 ${checked ? "translate-x-4" : "translate-x-0"}`} />
            </button>
            <div>
                <p className="text-sm font-semibold text-slate-700">{label}</p>
                {description && <p className="text-xs text-slate-400 mt-0.5">{description}</p>}
            </div>
        </div>
    );
}
