"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "react-hot-toast";
import { ChevronDown, Play, Pause, XCircle } from "lucide-react";

interface JobStatusControlProps {
    jobId: string;
    currentStatus: string;
}

const STATUS_ACTIONS: Record<string, { label: string; value: string; icon: React.ReactNode; color: string; description: string }[]> = {
    published: [
        { label: "Suspend", value: "suspended", icon: <Pause className="h-4 w-4" />, color: "text-amber-600 hover:bg-amber-50", description: "Temporarily hide from candidates" },
        { label: "Close / Mark Filled", value: "closed", icon: <XCircle className="h-4 w-4" />, color: "text-red-600 hover:bg-red-50", description: "Job is filled or no longer available" },
    ],
    suspended: [
        { label: "Reactivate", value: "published", icon: <Play className="h-4 w-4" />, color: "text-green-600 hover:bg-green-50", description: "Make visible to candidates again" },
        { label: "Close / Mark Filled", value: "closed", icon: <XCircle className="h-4 w-4" />, color: "text-red-600 hover:bg-red-50", description: "Job is filled or no longer available" },
    ],
};

export function JobStatusControl({ jobId, currentStatus }: JobStatusControlProps) {
    const router = useRouter();
    const [open, setOpen] = useState(false);
    const [loading, setLoading] = useState(false);

    const actions = STATUS_ACTIONS[currentStatus];

    // Only show for statuses that have actions (published, suspended)
    if (!actions || actions.length === 0) return null;

    const handleStatusChange = async (newStatus: string) => {
        const confirmMsg = newStatus === "closed"
            ? "Are you sure you want to close this job? This action cannot be undone by you."
            : newStatus === "suspended"
                ? "Suspend this job? It will be hidden from candidates until reactivated."
                : "Reactivate this job? It will become visible to candidates again.";

        if (!window.confirm(confirmMsg)) return;

        setLoading(true);
        try {
            const res = await fetch(`/api/employer/jobs/${jobId}/status`, {
                method: "PATCH",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ status: newStatus }),
            });

            const data = await res.json();

            if (!res.ok) {
                throw new Error(data.error || "Failed to update status");
            }

            toast.success(data.message || "Status updated successfully!");
            setOpen(false);
            router.refresh();
        } catch (error: any) {
            toast.error(error.message || "An error occurred");
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="relative">
            <button
                onClick={() => setOpen(!open)}
                disabled={loading}
                className="flex items-center gap-2 rounded-xl bg-white border border-slate-200 px-4 py-2 font-semibold text-slate-700 transition-colors hover:bg-slate-50 shadow-sm disabled:opacity-50"
            >
                {loading ? "Updating..." : "Change Status"}
                <ChevronDown className={`h-4 w-4 transition-transform ${open ? "rotate-180" : ""}`} />
            </button>

            {open && (
                <>
                    <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
                    <div className="absolute right-0 top-full mt-2 z-50 w-72 rounded-xl bg-white border border-slate-200 shadow-lg overflow-hidden">
                        {actions.map((action) => (
                            <button
                                key={action.value}
                                onClick={() => handleStatusChange(action.value)}
                                disabled={loading}
                                className={`w-full flex items-center gap-3 px-4 py-3 text-left transition-colors ${action.color} disabled:opacity-50`}
                            >
                                {action.icon}
                                <div>
                                    <div className="font-semibold text-sm">{action.label}</div>
                                    <div className="text-xs text-slate-500">{action.description}</div>
                                </div>
                            </button>
                        ))}
                    </div>
                </>
            )}
        </div>
    );
}
