import { redirect } from "next/navigation";
import { getApplicationsForComparison } from "@/app/actions/compareActions";
import { CompareCandidates } from "@/components/applications/CompareCandidates";
import Link from "next/link";
import { ArrowLeft, Users } from "lucide-react";

export const metadata = {
    title: "Candidate Comparison - Jobzio",
};

interface ComparePageProps {
    params: { jobId: string };
    searchParams: { ids?: string };
}

export default async function ComparePage({ params, searchParams }: ComparePageProps) {
    if (!searchParams.ids) {
        redirect(`/dashboard/employer/jobs/${params.jobId}/ats`);
    }

    // Using layout: ids=uuid1,uuid2,uuid3
    const applicationIds = searchParams.ids.split(",");

    if (applicationIds.length < 2) {
        redirect(`/dashboard/employer/jobs/${params.jobId}/ats`);
    }

    const result = await getApplicationsForComparison(applicationIds);

    if (!result.success || !result.applications) {
        return (
            <div className="p-8 text-center text-red-500 font-bold">
                {result.error || "Failed to load candidates for comparison."}
            </div>
        );
    }

    return (
        <div className="p-6 md:p-10 max-w-[1400px] mx-auto min-h-screen">
            {/* Header */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
                <div>
                    <div className="flex items-center gap-3 mb-2">
                        <Link
                            href={`/dashboard/employer/jobs/${params.jobId}/ats`}
                            className="p-2 -ml-2 hover:bg-slate-100 rounded-xl text-slate-500 transition-colors"
                        >
                            <ArrowLeft className="w-5 h-5" />
                        </Link>
                        <h1 className="text-2xl font-extrabold text-slate-900 flex items-center gap-2">
                            <Users className="w-6 h-6 text-primary" />
                            Comparing Candidates
                        </h1>
                    </div>
                    <p className="text-sm text-slate-500 ml-10">
                        Side-by-side analysis for {result.applications[0]?.job?.title}.
                    </p>
                </div>

                <div className="flex bg-blue-50 text-blue-700 px-4 py-2 rounded-xl text-sm font-semibold border border-blue-100 shadow-sm">
                    {result.applications.length} Candidates Selected
                </div>
            </div>

            {/* Client Component: Interactive Comparison Table */}
            <CompareClientWrapper applications={result.applications} jobId={params.jobId} />
        </div>
    );
}

// Client Wrapper to handle URL state for removing candidates dynamically
function CompareClientWrapper({ applications, jobId }: { applications: any[], jobId: string }) {
    "use client";

    // We can use native router or just regular component state for removing
    // Since removing should probably update the URL, let's just do a hard navigation or window history replace

    const handleRemove = (id: string) => {
        if (typeof window !== "undefined") {
            const currentIds = new URLSearchParams(window.location.search).get("ids")?.split(",") || [];
            const newIds = currentIds.filter(cid => cid !== id);

            if (newIds.length < 2) {
                // Not enough to compare, go back to ATS
                window.location.href = `/dashboard/employer/jobs/${jobId}/ats`;
            } else {
                // Update URL to reflect removal
                const url = new URL(window.location.href);
                url.searchParams.set("ids", newIds.join(","));
                window.history.pushState({}, "", url.toString());
                window.location.reload(); // Simple refresh to fetch new data
            }
        }
    };

    return <CompareCandidates applications={applications} onRemove={handleRemove} />;
}
