"use client";

import { useState, useTransition } from "react";
import { updateApplicationStatus } from "@/app/actions/application";
import { FileText, MoreVertical, Search, Filter } from "lucide-react";
import toast from "react-hot-toast";

type Application = {
    id: string;
    jobId: string;
    jobTitle: string;
    status: string;
    appliedAt: string;
    candidateId: string;
    candidateName: string;
    candidateHeadline: string;
    candidateAvatar?: string | null;
    resumeUrl?: string | null;
};

type Job = {
    id: string;
    title: string;
    _count: { applications: number };
};

const COLUMNS = [
    { id: "pending", title: "New / Pending", color: "bg-slate-100", textColor: "text-slate-800", borderColor: "border-slate-300" },
    { id: "reviewing", title: "Reviewing", color: "bg-blue-50", textColor: "text-blue-800", borderColor: "border-blue-300" },
    { id: "interview", title: "Interviewing", color: "bg-purple-50", textColor: "text-purple-800", borderColor: "border-purple-300" },
    { id: "offered", title: "Offered", color: "bg-emerald-50", textColor: "text-emerald-800", borderColor: "border-emerald-300" },
    { id: "rejected", title: "Rejected", color: "bg-rose-50", textColor: "text-rose-800", borderColor: "border-rose-300" },
];

export function ApplicantsBoard({ initialApplications, jobs }: { initialApplications: Application[], jobs: Job[] }) {
    const [applications, setApplications] = useState(initialApplications);
    const [isPending, startTransition] = useTransition();
    
    const [searchQuery, setSearchQuery] = useState("");
    const [selectedJob, setSelectedJob] = useState<string>("all");

    // Drag state
    const [draggedAppId, setDraggedAppId] = useState<string | null>(null);

    const handleDragStart = (e: React.DragEvent, id: string) => {
        setDraggedAppId(id);
        e.dataTransfer.effectAllowed = "move";
        // Optionally set a semi-transparent drag image
    };

    const handleDragOver = (e: React.DragEvent) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = "move";
    };

    const handleDrop = async (e: React.DragEvent, newStatus: string) => {
        e.preventDefault();
        if (!draggedAppId) return;

        const app = applications.find(a => a.id === draggedAppId);
        if (!app || app.status === newStatus) {
            setDraggedAppId(null);
            return;
        }

        // Optimistic UI update
        setApplications(apps => apps.map(a => a.id === draggedAppId ? { ...a, status: newStatus } : a));
        setDraggedAppId(null);

        // Server action
        startTransition(async () => {
            const result = await updateApplicationStatus(draggedAppId, newStatus);
            if (result?.error) {
                toast.error(result.error);
                // Revert optimistic update
                setApplications(initialApplications); 
            } else {
                toast.success("Status updated!");
            }
        });
    };

    // Filtered apps based on Job ID and Search
    const filteredApps = applications.filter(app => {
        const matchesJob = selectedJob === "all" || app.jobId === selectedJob;
        const searchLower = searchQuery.toLowerCase();
        const matchesSearch = app.candidateName.toLowerCase().includes(searchLower) || app.jobTitle.toLowerCase().includes(searchLower);
        return matchesJob && matchesSearch;
    });

    return (
        <div className="space-y-6">
            {/* Filters */}
            <div className="flex flex-col md:flex-row gap-4 bg-white p-4 rounded-2xl border border-slate-200">
                <div className="flex-1 relative">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                    <input 
                        type="text"
                        placeholder="Search candidates or roles..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="w-full pl-10 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all"
                    />
                </div>
                <div className="flex items-center gap-2 relative min-w-[200px]">
                    <Filter className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 z-10" />
                    <select
                        value={selectedJob}
                        onChange={(e) => setSelectedJob(e.target.value)}
                        className="w-full pl-10 pr-4 py-2.5 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500/20 focus:border-indigo-500 transition-all appearance-none cursor-pointer"
                    >
                        <option value="all">All Active Jobs</option>
                        {jobs.map(job => (
                            <option key={job.id} value={job.id}>{job.title} ({job._count.applications})</option>
                        ))}
                    </select>
                </div>
            </div>

            {/* Kanban Columns */}
            <div className="flex gap-6 overflow-x-auto pb-6 snap-x">
                {COLUMNS.map(column => {
                    const columnApps = filteredApps.filter(a => a.status === column.id);

                    return (
                        <div 
                            key={column.id} 
                            className={`flex flex-col flex-none w-[320px] rounded-2xl border ${column.borderColor} bg-slate-50/50 p-4 snap-center min-h-[500px]`}
                            onDragOver={handleDragOver}
                            onDrop={(e) => handleDrop(e, column.id)}
                        >
                            <div className="flex items-center justify-between mb-4 px-1">
                                <h3 className={`font-semibold text-sm ${column.textColor}`}>
                                    {column.title}
                                </h3>
                                <span className="bg-white text-slate-500 text-xs font-bold px-2.5 py-1 rounded-full border border-slate-200 shadow-sm">
                                    {columnApps.length}
                                </span>
                            </div>

                            <div className="flex-1 space-y-3">
                                {columnApps.length === 0 ? (
                                    <div className="h-24 border-2 border-dashed border-slate-200 rounded-xl flex items-center justify-center text-sm text-slate-400 pb-1">
                                        Drop candidates here
                                    </div>
                                ) : (
                                    columnApps.map(app => (
                                        <div 
                                            key={app.id}
                                            draggable
                                            onDragStart={(e) => handleDragStart(e, app.id)}
                                            className="bg-white p-4 rounded-xl shadow-sm border border-slate-200 cursor-grab active:cursor-grabbing hover:border-indigo-300 hover:shadow-md transition-all group relative"
                                        >
                                            <div className="flex gap-3 mb-3">
                                                <div className="w-10 h-10 shrink-0 bg-indigo-50 rounded-full flex items-center justify-center text-indigo-700 font-bold overflow-hidden">
                                                    {app.candidateAvatar ? (
                                                        <img src={app.candidateAvatar} alt={app.candidateName} className="w-full h-full object-cover" />
                                                    ) : (
                                                        app.candidateName.charAt(0).toUpperCase()
                                                    )}
                                                </div>
                                                <div className="flex-1 min-w-0">
                                                    <h4 className="font-semibold text-sm text-slate-900 truncate" title={app.candidateName}>
                                                        {app.candidateName}
                                                    </h4>
                                                    <p className="text-xs text-slate-500 truncate" title={app.candidateHeadline}>
                                                        {app.candidateHeadline}
                                                    </p>
                                                </div>
                                                
                                                {/* Dropdown for non-drag accessibility */}
                                                <div className="relative dropdown-container">
                                                    <button className="text-slate-400 hover:text-slate-600 rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity focus:opacity-100">
                                                        <MoreVertical className="w-4 h-4" />
                                                    </button>
                                                    {/* We can add a simple select overlay here later if needed */}
                                                </div>
                                            </div>

                                            <div className="pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
                                                <span className="text-indigo-600 font-medium truncate max-w-[140px]" title={app.jobTitle}>
                                                    {app.jobTitle}
                                                </span>
                                                <span className="text-slate-400 flex items-center gap-1">
                                                    {new Date(app.appliedAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}
                                                </span>
                                            </div>

                                            {/* Resume Button */}
                                            {app.resumeUrl ? (
                                                <a 
                                                    href={app.resumeUrl} 
                                                    target="_blank" 
                                                    rel="noreferrer"
                                                    onClick={(e) => e.stopPropagation()}
                                                    className="mt-3 w-full flex items-center justify-center gap-1.5 py-1.5 bg-slate-50 hover:bg-slate-100 border border-slate-200 rounded-lg text-xs font-medium text-slate-600 transition-colors"
                                                >
                                                    <FileText className="w-3.5 h-3.5" /> View Resume
                                                </a>
                                            ) : (
                                                 <div className="mt-3 w-full flex items-center justify-center gap-1.5 py-1.5 bg-slate-50 border border-slate-200 rounded-lg text-xs font-medium text-slate-400">
                                                    No Resume
                                                </div>
                                            )}
                                        </div>
                                    ))
                                )}
                            </div>
                        </div>
                    );
                })}
            </div>
            
            {/* Instruction Footer */}
            <div className="text-center text-sm text-slate-500 flex items-center justify-center gap-2">
                <span className="inline-block w-2 h-2 rounded-full bg-slate-300"></span>
                Drag and drop candidate cards to update their status
            </div>
        </div>
    );
}
