import { getCurrentUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import Link from "next/link";
import { FileText } from "lucide-react";
import { KanbanBoard } from "@/components/applications/KanbanBoard";
import { ApplicationsList } from "@/components/applications/ApplicationsList";
import { getCandidateApplications } from "@/app/actions/applicationTracking";
import { getEmployerApplicationsAdvanced, getEmployerDashboardMetrics, getEmployerJobsList, getHiringFunnelData } from "@/app/actions/employerDashboard";
import { getInterviewAnalytics, getEmployerInterviews } from "@/app/actions/interviewActions";
import { MetricsCards } from "@/components/applications/dashboard/MetricsCards";
import { HiringFunnel } from "@/components/applications/dashboard/HiringFunnel";
import { InterviewAnalytics } from "@/components/applications/dashboard/InterviewAnalytics";
import { EmployerApplicationsDashboard } from "@/components/applications/dashboard/EmployerApplicationsDashboard";

export default async function ApplicationsPage(props: { searchParams: Promise<{ status?: string; view?: string }> }) {
    const searchParams = await props.searchParams;
    const currentUser = await getCurrentUser();

    if (!currentUser) {
        redirect("/login");
    }

    if (currentUser.role === 'admin') {
        redirect("/admin/jobs");
    }

    const isCandidate = currentUser.role === 'candidate';

    // ============================
    // EMPLOYER VIEW — Full ATS Dashboard
    // ============================
    if (!isCandidate) {
        const [metrics, applications, jobs, funnelData, interviewAnalytics, interviews] = await Promise.all([
            getEmployerDashboardMetrics(),
            getEmployerApplicationsAdvanced(),
            getEmployerJobsList(),
            getHiringFunnelData(),
            getInterviewAnalytics(),
            getEmployerInterviews(),
        ]);

        // Compute status counts
        const statusCounts: Record<string, number> = {};
        applications.forEach((app: any) => {
            statusCounts[app.status] = (statusCounts[app.status] || 0) + 1;
        });

        return (
            <div className="space-y-6">
                {/* Header */}
                <div>
                    <h1 className="text-3xl font-bold text-slate-900">Application Management</h1>
                    <p className="text-slate-500 mt-1">
                        Review, manage, and track all candidate applications across your jobs.
                    </p>
                </div>

                {/* Metrics Cards */}
                <MetricsCards metrics={metrics} />

                {/* Hiring Funnel */}
                <HiringFunnel
                    stages={funnelData.stages}
                    sources={funnelData.sources}
                    totalApplications={funnelData.totalApplications}
                />

                {/* Interview Analytics */}
                <InterviewAnalytics data={interviewAnalytics} />

                {/* Main Dashboard */}
                <EmployerApplicationsDashboard
                    applications={applications}
                    jobs={jobs}
                    statusCounts={statusCounts}
                    interviews={interviews}
                />
            </div>
        );
    }

    // ============================
    // CANDIDATE VIEW — Existing simple view
    // ============================
    let applications: any[] = [];
    try {
        applications = await getCandidateApplications();
    } catch (e) {
        console.error("Failed to load applications", e);
    }

    const statusCounts = {
        all: applications.length,
        pending: applications.filter(a => a.status === 'pending').length,
        reviewing: applications.filter(a => a.status === 'reviewing').length,
        interview: applications.filter(a => a.status === 'interview').length,
        offer: applications.filter(a => a.status === 'offer').length,
        hired: applications.filter(a => a.status === 'hired').length,
        rejected: applications.filter(a => a.status === 'rejected').length,
        withdrawn: applications.filter(a => a.status === 'withdrawn').length,
    };

    const statusFilter = searchParams.status as string | undefined;
    const filteredApplications = statusFilter
        ? applications.filter(app => app.status === statusFilter)
        : applications;

    return (
        <div className="space-y-6">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                <div>
                    <h1 className="text-3xl font-bold text-slate-900">Applications</h1>
                    <p className="text-slate-600 mt-2">
                        {statusFilter
                            ? `${filteredApplications.length} ${statusFilter} application${filteredApplications.length !== 1 ? 's' : ''}`
                            : `${applications.length} total applications`
                        }
                    </p>
                </div>
            </div>

            {/* Status Filter Pills */}
            <div className="flex flex-wrap gap-2">
                <FilterPill label="All" count={statusCounts.all} active={!statusFilter} href="/dashboard/applications" />
                <FilterPill label="Pending" count={statusCounts.pending} active={statusFilter === 'pending'} href="/dashboard/applications?status=pending" />
                <FilterPill label="Reviewing" count={statusCounts.reviewing} active={statusFilter === 'reviewing'} href="/dashboard/applications?status=reviewing" />
                <FilterPill label="Interview" count={statusCounts.interview} active={statusFilter === 'interview'} href="/dashboard/applications?status=interview" />
                <FilterPill label="Rejected" count={statusCounts.rejected} active={statusFilter === 'rejected'} href="/dashboard/applications?status=rejected" />
                <FilterPill label="Withdrawn" count={statusCounts.withdrawn} active={statusFilter === 'withdrawn'} href="/dashboard/applications?status=withdrawn" />
            </div>

            {/* Empty State */}
            {applications.length === 0 ? (
                <div className="flex flex-col items-center justify-center py-16 rounded-2xl border-2 border-dashed border-slate-200 bg-slate-50">
                    <FileText className="h-12 w-12 text-slate-400 mb-4" />
                    <h3 className="text-lg font-bold text-slate-900">No applications yet</h3>
                    <p className="text-sm text-slate-500 mt-2 text-center">
                        You haven&apos;t applied to any jobs yet.
                    </p>
                    <Link
                        href="/jobs"
                        className="mt-6 px-6 py-2.5 bg-primary text-white rounded-lg font-semibold hover:bg-blue-700 transition-colors"
                    >
                        Browse Jobs
                    </Link>
                </div>
            ) : (
                <ApplicationsList applications={filteredApplications} userRole={currentUser.role} />
            )}
        </div>
    );
}

function FilterPill({ label, count, active, href }: { label: string; count: number; active: boolean; href: string }) {
    if (count === 0 && !active) return null;
    return (
        <Link
            href={href}
            className={`px-4 py-2 rounded-lg text-sm font-semibold transition-all ${active
                ? 'bg-primary text-white shadow-lg shadow-primary/20'
                : 'bg-white border border-slate-200 text-slate-700 hover:border-primary/50 hover:shadow-sm'
                }`}
        >
            {label} <span className={`ml-1 ${active ? 'opacity-80' : 'text-slate-400'}`}>({count})</span>
        </Link>
    );
}
