"use client";

import { useState, useTransition } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
    ArrowRight, X, Tag, Mail, StickyNote, Trash2, Archive,
    CheckSquare, Loader2, AlertTriangle, Users
} from "lucide-react";
import { bulkMoveToStage, bulkReject, bulkAddTag, bulkRemoveTag, bulkAddNote, bulkSendMessage, bulkArchive, getEmployerTags, getEmployerStages } from "@/app/actions/bulkCandidateActions";
import toast from "react-hot-toast";
import { useParams, useRouter } from "next/navigation";

// ─── Types ──────────────────────────────────────────────
interface Stage {
    id: string;
    name: string;
    color: string;
    order: number;
    pipeline: { name: string };
    _count?: { applications: number };
}

interface TagItem {
    id: string;
    name: string;
    color: string;
    _count: { applications: number };
}

interface BulkActionBarProps {
    selectedIds: string[];
    onClearSelection: () => void;
    onActionComplete: () => void;
}

type ModalType = "move" | "reject" | "tag" | "email" | "note" | null;

// ─── Main Component ─────────────────────────────────────
export function BulkActionBar({ selectedIds, onClearSelection, onActionComplete }: BulkActionBarProps) {
    const [activeModal, setActiveModal] = useState<ModalType>(null);
    const count = selectedIds.length;
    const params = useParams();
    const router = useRouter();

    if (count === 0) return null;

    return (
        <>
            <AnimatePresence>
                <motion.div
                    initial={{ y: 80, opacity: 0 }}
                    animate={{ y: 0, opacity: 1 }}
                    exit={{ y: 80, opacity: 0 }}
                    transition={{ type: "spring" as const, damping: 25, stiffness: 300 }}
                    className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-2 px-4 py-3 rounded-2xl bg-slate-900 text-white shadow-2xl shadow-slate-900/30"
                >
                    {/* Selected Count */}
                    <div className="flex items-center gap-2 pr-3 border-r border-slate-700">
                        <CheckSquare className="h-4 w-4 text-blue-400" />
                        <span className="text-sm font-semibold">{count} selected</span>
                    </div>

                    {/* Actions */}
                    {count >= 2 && count <= 4 && (
                        <ActionButton
                            icon={Users}
                            label="Compare"
                            onClick={() => {
                                if (params.jobId) {
                                    router.push(`/dashboard/employer/jobs/${params.jobId}/compare?ids=${selectedIds.join(",")}`);
                                } else {
                                    toast.error("Comparing candidates Requires a specific job context.");
                                }
                            }}
                        />
                    )}
                    <ActionButton icon={ArrowRight} label="Move" onClick={() => setActiveModal("move")} />
                    <ActionButton icon={Tag} label="Tag" onClick={() => setActiveModal("tag")} />
                    <ActionButton icon={Mail} label="Email" onClick={() => setActiveModal("email")} />
                    <ActionButton icon={StickyNote} label="Note" onClick={() => setActiveModal("note")} />
                    <ActionButton icon={Trash2} label="Reject" onClick={() => setActiveModal("reject")} danger />
                    <ActionButton icon={Archive} label="Archive" onClick={async () => {
                        if (!confirm(`Archive ${count} candidates? They'll be removed from the active view.`)) return;
                        const res = await bulkArchive(selectedIds);
                        if (res.success) {
                            toast.success(res.message!);
                            onActionComplete();
                            onClearSelection();
                        } else {
                            toast.error(res.error || "Failed to archive");
                        }
                    }} />

                    {/* Close */}
                    <div className="pl-2 border-l border-slate-700">
                        <button onClick={onClearSelection} className="p-1.5 rounded-lg hover:bg-slate-800 transition-colors" aria-label="Clear selection">
                            <X className="h-4 w-4 text-slate-400" />
                        </button>
                    </div>
                </motion.div>
            </AnimatePresence>

            {/* Modals */}
            {activeModal === "move" && (
                <BulkMoveModal
                    selectedIds={selectedIds}
                    onClose={() => setActiveModal(null)}
                    onComplete={() => { onActionComplete(); onClearSelection(); setActiveModal(null); }}
                />
            )}
            {activeModal === "reject" && (
                <BulkRejectModal
                    selectedIds={selectedIds}
                    onClose={() => setActiveModal(null)}
                    onComplete={() => { onActionComplete(); onClearSelection(); setActiveModal(null); }}
                />
            )}
            {activeModal === "tag" && (
                <BulkTagModal
                    selectedIds={selectedIds}
                    onClose={() => setActiveModal(null)}
                    onComplete={() => { onActionComplete(); setActiveModal(null); }}
                />
            )}
            {activeModal === "email" && (
                <BulkEmailModal
                    selectedIds={selectedIds}
                    onClose={() => setActiveModal(null)}
                    onComplete={() => { onActionComplete(); onClearSelection(); setActiveModal(null); }}
                />
            )}
            {activeModal === "note" && (
                <BulkNoteModal
                    selectedIds={selectedIds}
                    onClose={() => setActiveModal(null)}
                    onComplete={() => { onActionComplete(); setActiveModal(null); }}
                />
            )}
        </>
    );
}

// ─── Action Button ──────────────────────────────────────
function ActionButton({ icon: Icon, label, onClick, danger }: {
    icon: React.ElementType;
    label: string;
    onClick: () => void;
    danger?: boolean;
}) {
    return (
        <button
            onClick={onClick}
            className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${danger
                ? "hover:bg-red-500/20 text-red-300 hover:text-red-200"
                : "hover:bg-slate-800 text-slate-300 hover:text-white"
                }`}
        >
            <Icon className="h-3.5 w-3.5" />
            {label}
        </button>
    );
}

// ─── Modal Wrapper ──────────────────────────────────────
function ModalWrapper({ title, children, onClose, danger }: {
    title: string;
    children: React.ReactNode;
    onClose: () => void;
    danger?: boolean;
}) {
    return (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
            <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className="absolute inset-0 bg-slate-900/50 backdrop-blur-sm"
                onClick={onClose}
            />
            <motion.div
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.95 }}
                className={`relative bg-white rounded-2xl shadow-2xl w-full max-w-lg max-h-[85vh] overflow-y-auto ${danger ? "border-2 border-red-200" : ""}`}
            >
                <div className={`sticky top-0 flex items-center justify-between p-5 border-b rounded-t-2xl ${danger ? "bg-red-50 border-red-200" : "bg-slate-50 border-slate-200"}`}>
                    <h3 className={`text-lg font-semibold ${danger ? "text-red-800" : "text-slate-800"}`}>{title}</h3>
                    <button onClick={onClose} className="p-1 rounded-lg hover:bg-white/50 transition-colors">
                        <X className="h-5 w-5 text-slate-400" />
                    </button>
                </div>
                <div className="p-5">{children}</div>
            </motion.div>
        </div>
    );
}

// ─── Bulk Move Modal ────────────────────────────────────
function BulkMoveModal({ selectedIds, onClose, onComplete }: {
    selectedIds: string[];
    onClose: () => void;
    onComplete: () => void;
}) {
    const [stages, setStages] = useState<Stage[]>([]);
    const [targetStageId, setTargetStageId] = useState("");
    const [note, setNote] = useState("");
    const [isPending, startTransition] = useTransition();
    const [loaded, setLoaded] = useState(false);

    if (!loaded) {
        getEmployerStages().then(res => {
            if (res.success) setStages((res as any).stages);
            setLoaded(true);
        });
    }

    const handleSubmit = () => {
        if (!targetStageId) return toast.error("Select a target stage");
        startTransition(async () => {
            const res = await bulkMoveToStage(selectedIds, targetStageId, note);
            if (res.success) {
                toast.success(res.message!);
                onComplete();
            } else {
                toast.error(res.error || "Move failed");
            }
        });
    };

    return (
        <ModalWrapper title={`Move ${selectedIds.length} Candidates`} onClose={onClose}>
            <div className="space-y-4">
                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Target Stage</label>
                    {!loaded ? (
                        <div className="h-10 bg-slate-100 rounded-lg animate-pulse" />
                    ) : (
                        <select
                            value={targetStageId}
                            onChange={e => setTargetStageId(e.target.value)}
                            className="w-full px-3 py-2.5 border border-slate-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                        >
                            <option value="">Select a stage...</option>
                            {stages.map(s => (
                                <option key={s.id} value={s.id}>
                                    {s.pipeline.name} → {s.name} ({s._count?.applications ?? 0} in stage)
                                </option>
                            ))}
                        </select>
                    )}
                </div>

                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Note (optional)</label>
                    <textarea
                        value={note}
                        onChange={e => setNote(e.target.value)}
                        placeholder="Add a note for all moved candidates..."
                        className="w-full px-3 py-2.5 border border-slate-300 rounded-xl text-sm resize-none h-20 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                    />
                </div>

                <button
                    onClick={handleSubmit}
                    disabled={isPending || !targetStageId}
                    className="w-full py-2.5 rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 disabled:opacity-50 transition-colors flex items-center justify-center gap-2"
                >
                    {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <ArrowRight className="h-4 w-4" />}
                    {isPending ? "Moving..." : `Move ${selectedIds.length} Candidates`}
                </button>
            </div>
        </ModalWrapper>
    );
}

// ─── Bulk Reject Modal ──────────────────────────────────
function BulkRejectModal({ selectedIds, onClose, onComplete }: {
    selectedIds: string[];
    onClose: () => void;
    onComplete: () => void;
}) {
    const [reason, setReason] = useState("");
    const [sendEmail, setSendEmail] = useState(true);
    const [confirmText, setConfirmText] = useState("");
    const [isPending, startTransition] = useTransition();

    const needsConfirm = selectedIds.length >= 10;
    const canSubmit = reason.trim() && (!needsConfirm || confirmText === "REJECT");

    const handleSubmit = () => {
        if (!canSubmit) return;
        startTransition(async () => {
            const res = await bulkReject(selectedIds, reason, sendEmail);
            if (res.success) {
                toast.success(res.message!);
                onComplete();
            } else {
                toast.error(res.error || "Rejection failed");
            }
        });
    };

    return (
        <ModalWrapper title={`Reject ${selectedIds.length} Candidates`} onClose={onClose} danger>
            <div className="space-y-4">
                <div className="p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700 flex items-start gap-2">
                    <AlertTriangle className="h-4 w-4 mt-0.5 shrink-0" />
                    <span>This will reject all {selectedIds.length} selected candidates. This action cannot be undone.</span>
                </div>

                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Rejection Reason *</label>
                    <select
                        value={reason}
                        onChange={e => setReason(e.target.value)}
                        className="w-full px-3 py-2.5 border border-slate-300 rounded-xl text-sm focus:ring-2 focus:ring-red-500/20 focus:border-red-500"
                    >
                        <option value="">Select a reason...</option>
                        <option value="Not Qualified">Not Qualified</option>
                        <option value="Position Filled">Position Filled</option>
                        <option value="Failed Assessment">Failed Assessment</option>
                        <option value="Salary Mismatch">Salary Mismatch</option>
                        <option value="No Response">No Response</option>
                        <option value="Culture Fit">Culture Fit Concerns</option>
                        <option value="Other">Other</option>
                    </select>
                </div>

                <label className="flex items-center gap-2 cursor-pointer">
                    <input
                        type="checkbox"
                        checked={sendEmail}
                        onChange={e => setSendEmail(e.target.checked)}
                        className="w-4 h-4 rounded border-slate-300 text-red-600 focus:ring-red-500"
                    />
                    <span className="text-sm text-slate-700">Send rejection email notification</span>
                </label>

                {needsConfirm && (
                    <div>
                        <label className="block text-sm font-medium text-red-700 mb-1">Type &quot;REJECT&quot; to confirm</label>
                        <input
                            type="text"
                            value={confirmText}
                            onChange={e => setConfirmText(e.target.value)}
                            placeholder="REJECT"
                            className="w-full px-3 py-2.5 border border-red-300 rounded-xl text-sm focus:ring-2 focus:ring-red-500/20 focus:border-red-500"
                        />
                    </div>
                )}

                <button
                    onClick={handleSubmit}
                    disabled={isPending || !canSubmit}
                    className="w-full py-2.5 rounded-xl bg-red-600 text-white text-sm font-semibold hover:bg-red-700 disabled:opacity-50 transition-colors flex items-center justify-center gap-2"
                >
                    {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
                    {isPending ? "Rejecting..." : `Reject ${selectedIds.length} Candidates`}
                </button>
            </div>
        </ModalWrapper>
    );
}

// ─── Bulk Tag Modal ─────────────────────────────────────
function BulkTagModal({ selectedIds, onClose, onComplete }: {
    selectedIds: string[];
    onClose: () => void;
    onComplete: () => void;
}) {
    const [tags, setTags] = useState<TagItem[]>([]);
    const [loaded, setLoaded] = useState(false);
    const [isPending, startTransition] = useTransition();

    if (!loaded) {
        getEmployerTags().then(res => {
            if (res.success) setTags((res as any).tags);
            setLoaded(true);
        });
    }

    const handleApplyTag = (tagId: string, tagName: string) => {
        startTransition(async () => {
            const res = await bulkAddTag(selectedIds, tagId);
            if (res.success) {
                toast.success(res.message!);
                onComplete();
            } else {
                toast.error(res.error || "Tagging failed");
            }
        });
    };

    return (
        <ModalWrapper title={`Tag ${selectedIds.length} Candidates`} onClose={onClose}>
            <div className="space-y-3">
                <p className="text-sm text-slate-500">Click a tag to apply it to all selected candidates.</p>
                {!loaded ? (
                    <div className="space-y-2">
                        {[1, 2, 3].map(i => <div key={i} className="h-10 bg-slate-100 rounded-lg animate-pulse" />)}
                    </div>
                ) : tags.length === 0 ? (
                    <p className="text-sm text-slate-400 py-4 text-center">No tags created yet. Create tags in the candidate detail view.</p>
                ) : (
                    <div className="flex flex-wrap gap-2">
                        {tags.map(tag => (
                            <button
                                key={tag.id}
                                onClick={() => handleApplyTag(tag.id, tag.name)}
                                disabled={isPending}
                                className="px-3 py-2 rounded-xl border border-slate-200 text-sm font-medium hover:shadow-md transition-all flex items-center gap-2 disabled:opacity-50"
                                style={{ backgroundColor: tag.color + "20", borderColor: tag.color + "40" }}
                            >
                                <div className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: tag.color }} />
                                {tag.name}
                                <span className="text-xs text-slate-400">({tag._count.applications})</span>
                            </button>
                        ))}
                    </div>
                )}
            </div>
        </ModalWrapper>
    );
}

// ─── Bulk Email Modal ───────────────────────────────────
function BulkEmailModal({ selectedIds, onClose, onComplete }: {
    selectedIds: string[];
    onClose: () => void;
    onComplete: () => void;
}) {
    const [subject, setSubject] = useState("");
    const [content, setContent] = useState("");
    const [isPending, startTransition] = useTransition();

    const handleSend = () => {
        if (!subject.trim() || !content.trim()) return toast.error("Subject and message are required");
        startTransition(async () => {
            const res = await bulkSendMessage(selectedIds, subject, content);
            if (res.success) {
                toast.success(res.message!);
                onComplete();
            } else {
                toast.error(res.error || "Send failed");
            }
        });
    };

    return (
        <ModalWrapper title={`Email ${selectedIds.length} Candidates`} onClose={onClose}>
            <div className="space-y-4">
                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Subject</label>
                    <input
                        type="text"
                        value={subject}
                        onChange={e => setSubject(e.target.value)}
                        placeholder="e.g., Interview Update"
                        className="w-full px-3 py-2.5 border border-slate-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                    />
                </div>
                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Message</label>
                    <textarea
                        value={content}
                        onChange={e => setContent(e.target.value)}
                        placeholder="Type your message here..."
                        className="w-full px-3 py-2.5 border border-slate-300 rounded-xl text-sm resize-none h-32 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                    />
                </div>
                <p className="text-xs text-slate-400">This message will be sent as an in-app message to each selected candidate.</p>

                <button
                    onClick={handleSend}
                    disabled={isPending || !subject.trim() || !content.trim()}
                    className="w-full py-2.5 rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 disabled:opacity-50 transition-colors flex items-center justify-center gap-2"
                >
                    {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Mail className="h-4 w-4" />}
                    {isPending ? "Sending..." : `Send to ${selectedIds.length} Candidates`}
                </button>
            </div>
        </ModalWrapper>
    );
}

// ─── Bulk Note Modal ────────────────────────────────────
function BulkNoteModal({ selectedIds, onClose, onComplete }: {
    selectedIds: string[];
    onClose: () => void;
    onComplete: () => void;
}) {
    const [content, setContent] = useState("");
    const [isPrivate, setIsPrivate] = useState(false);
    const [isPending, startTransition] = useTransition();

    const handleAdd = () => {
        if (!content.trim()) return toast.error("Note content is required");
        startTransition(async () => {
            const res = await bulkAddNote(selectedIds, content, isPrivate);
            if (res.success) {
                toast.success(res.message!);
                onComplete();
            } else {
                toast.error(res.error || "Note failed");
            }
        });
    };

    return (
        <ModalWrapper title={`Add Note to ${selectedIds.length} Candidates`} onClose={onClose}>
            <div className="space-y-4">
                <div>
                    <label className="block text-sm font-medium text-slate-700 mb-1">Note</label>
                    <textarea
                        value={content}
                        onChange={e => setContent(e.target.value)}
                        placeholder="Write a note that applies to all selected candidates..."
                        className="w-full px-3 py-2.5 border border-slate-300 rounded-xl text-sm resize-none h-28 focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500"
                    />
                </div>
                <label className="flex items-center gap-2 cursor-pointer">
                    <input
                        type="checkbox"
                        checked={isPrivate}
                        onChange={e => setIsPrivate(e.target.checked)}
                        className="w-4 h-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                    />
                    <span className="text-sm text-slate-700">Private note (only visible to you)</span>
                </label>

                <button
                    onClick={handleAdd}
                    disabled={isPending || !content.trim()}
                    className="w-full py-2.5 rounded-xl bg-blue-600 text-white text-sm font-semibold hover:bg-blue-700 disabled:opacity-50 transition-colors flex items-center justify-center gap-2"
                >
                    {isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <StickyNote className="h-4 w-4" />}
                    {isPending ? "Adding..." : `Add Note to ${selectedIds.length} Candidates`}
                </button>
            </div>
        </ModalWrapper>
    );
}
