"use client";

import { useState, useEffect, useTransition } from "react";
import {
    BarChart3, TrendingUp, TrendingDown, Clock, Users, Target,
    Award, Briefcase, ArrowRight, Filter, Calendar, Loader2,
    CheckCircle2, XCircle, AlertTriangle, Minus, PieChart
} from "lucide-react";
import {
    getExecutiveKPIs,
    getPipelineHealthReport,
    getSourceEffectiveness,
    getRecruiterPerformance,
    getTimeToFillBreakdown,
    getOfferAcceptanceReport,
    type KPIData,
    type PipelineHealthData,
    type SourceData,
    type RecruiterData,
    type TimeToFillData,
    type OfferData,
    type DateRange,
} from "@/app/actions/reportingActions";

// ─── Types ──────────────────────────────────────────────
type Tab = "overview" | "pipeline" | "sources" | "recruiters" | "time" | "offers";

const TABS: { key: Tab; label: string; icon: any }[] = [
    { key: "overview", label: "Overview", icon: BarChart3 },
    { key: "pipeline", label: "Pipeline", icon: Target },
    { key: "sources", label: "Sources", icon: TrendingUp },
    { key: "recruiters", label: "Recruiters", icon: Users },
    { key: "time", label: "Time Analysis", icon: Clock },
    { key: "offers", label: "Offers", icon: Award },
];

const DATE_PRESETS = [
    { label: "Last 30 days", days: 30 },
    { label: "Last 90 days", days: 90 },
    { label: "Last 6 months", days: 180 },
    { label: "Last year", days: 365 },
];

// ─── Component ──────────────────────────────────────────
export function ReportingDashboard() {
    const [activeTab, setActiveTab] = useState<Tab>("overview");
    const [datePreset, setDatePreset] = useState(1); // 90 days default
    const [isPending, startTransition] = useTransition();

    // Data states
    const [kpis, setKPIs] = useState<KPIData | null>(null);
    const [pipelineHealth, setPipelineHealth] = useState<PipelineHealthData | null>(null);
    const [sources, setSources] = useState<SourceData[] | null>(null);
    const [recruiters, setRecruiters] = useState<RecruiterData[] | null>(null);
    const [timeToFill, setTimeToFill] = useState<TimeToFillData[] | null>(null);
    const [offers, setOffers] = useState<OfferData | null>(null);

    const getRange = (): DateRange => {
        const to = new Date();
        const from = new Date();
        from.setDate(from.getDate() - DATE_PRESETS[datePreset].days);
        return { from: from.toISOString(), to: to.toISOString() };
    };

    useEffect(() => {
        const range = getRange();
        startTransition(async () => {
            // Load data for current tab
            if (activeTab === "overview" || !kpis) {
                const r = await getExecutiveKPIs(range);
                if (r.success && r.data) setKPIs(r.data);
            }
            if (activeTab === "pipeline" || activeTab === "overview") {
                const r = await getPipelineHealthReport(range);
                if (r.success && r.data) setPipelineHealth(r.data);
            }
            if (activeTab === "sources") {
                const r = await getSourceEffectiveness(range);
                if (r.success && r.data) setSources(r.data);
            }
            if (activeTab === "recruiters") {
                const r = await getRecruiterPerformance(range);
                if (r.success && r.data) setRecruiters(r.data);
            }
            if (activeTab === "time") {
                const r = await getTimeToFillBreakdown(range);
                if (r.success && r.data) setTimeToFill(r.data);
            }
            if (activeTab === "offers") {
                const r = await getOfferAcceptanceReport(range);
                if (r.success && r.data) setOffers(r.data);
            }
        });
    }, [activeTab, datePreset]);

    return (
        <div className="space-y-6">
            {/* Header */}
            <div className="flex items-center justify-between">
                <div>
                    <h2 className="text-xl font-bold text-slate-900">ATS Reports & Analytics</h2>
                    <p className="text-sm text-slate-500 mt-0.5">Data-driven hiring insights</p>
                </div>
                {/* Date Range Selector */}
                <div className="flex items-center gap-1 bg-slate-100 rounded-xl p-1">
                    {DATE_PRESETS.map((p, i) => (
                        <button
                            key={p.label}
                            onClick={() => setDatePreset(i)}
                            className={`px-3 py-1.5 text-xs font-medium rounded-lg transition-colors ${datePreset === i ? "bg-white text-slate-900 shadow-sm" : "text-slate-500 hover:text-slate-700"
                                }`}
                        >
                            {p.label}
                        </button>
                    ))}
                </div>
            </div>

            {/* Tabs */}
            <div className="flex gap-1 bg-slate-50 rounded-xl p-1 overflow-x-auto">
                {TABS.map(tab => {
                    const Icon = tab.icon;
                    return (
                        <button
                            key={tab.key}
                            onClick={() => setActiveTab(tab.key)}
                            className={`flex items-center gap-1.5 px-4 py-2 text-xs font-medium rounded-lg transition-all whitespace-nowrap ${activeTab === tab.key
                                    ? "bg-white text-slate-900 shadow-sm"
                                    : "text-slate-500 hover:text-slate-700"
                                }`}
                        >
                            <Icon className="w-3.5 h-3.5" />
                            {tab.label}
                        </button>
                    );
                })}
            </div>

            {/* Loading */}
            {isPending && (
                <div className="flex items-center justify-center py-8 text-slate-400">
                    <Loader2 className="w-5 h-5 animate-spin mr-2" />
                    Loading report data...
                </div>
            )}

            {/* Tab Content */}
            {!isPending && activeTab === "overview" && <OverviewTab kpis={kpis} pipeline={pipelineHealth} />}
            {!isPending && activeTab === "pipeline" && <PipelineTab data={pipelineHealth} />}
            {!isPending && activeTab === "sources" && <SourcesTab data={sources} />}
            {!isPending && activeTab === "recruiters" && <RecruitersTab data={recruiters} />}
            {!isPending && activeTab === "time" && <TimeTab data={timeToFill} />}
            {!isPending && activeTab === "offers" && <OffersTab data={offers} />}
        </div>
    );
}

// ─── KPI Card ───────────────────────────────────────────
function KPICard({ title, value, subtitle, trend, icon: Icon, color }: {
    title: string; value: string | number; subtitle: string; trend?: number;
    icon: any; color: string;
}) {
    return (
        <div className="bg-white rounded-2xl border border-slate-100 p-5 shadow-sm hover:shadow-md transition-shadow">
            <div className="flex items-start justify-between mb-3">
                <div className={`p-2.5 rounded-xl ${color}`}>
                    <Icon className="w-5 h-5" />
                </div>
                {trend !== undefined && trend !== 0 && (
                    <div className={`flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-full ${trend > 0 ? "text-emerald-600 bg-emerald-50" : "text-red-500 bg-red-50"
                        }`}>
                        {trend > 0 ? <TrendingUp className="w-3 h-3" /> : <TrendingDown className="w-3 h-3" />}
                        {Math.abs(trend)}%
                    </div>
                )}
            </div>
            <p className="text-2xl font-black text-slate-900">{value}</p>
            <p className="text-xs text-slate-500 mt-1">{subtitle}</p>
        </div>
    );
}

// ─── Overview Tab ───────────────────────────────────────
function OverviewTab({ kpis, pipeline }: { kpis: KPIData | null; pipeline: PipelineHealthData | null }) {
    if (!kpis) return <EmptyState label="No data available" />;

    return (
        <div className="space-y-6">
            {/* KPI Cards */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
                <KPICard
                    title="Open Positions" value={kpis.openPositions.total}
                    subtitle={`${kpis.openPositions.critical} critical, ${kpis.openPositions.highPriority} high priority`}
                    icon={Briefcase} color="bg-blue-50 text-blue-600"
                />
                <KPICard
                    title="Time-to-Hire" value={`${kpis.timeToHire.avgDays} days`}
                    subtitle={`Target: ${kpis.timeToHire.target} days`}
                    trend={kpis.timeToHire.trend}
                    icon={Clock} color="bg-violet-50 text-violet-600"
                />
                <KPICard
                    title="Total Hires" value={kpis.totalHires.count}
                    subtitle={`Goal: ${kpis.totalHires.goal}`}
                    trend={kpis.totalHires.trend}
                    icon={Users} color="bg-emerald-50 text-emerald-600"
                />
                <KPICard
                    title="Offer Acceptance" value={`${kpis.offerAcceptance.rate}%`}
                    subtitle="Acceptance rate"
                    trend={kpis.offerAcceptance.trend}
                    icon={Award} color="bg-amber-50 text-amber-600"
                />
            </div>

            {/* Pipeline Funnel */}
            {pipeline && pipeline.stages.length > 0 && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                    <h3 className="text-sm font-bold text-slate-900 mb-4">Pipeline Funnel</h3>
                    <div className="space-y-2">
                        {pipeline.stages.map((stage, i) => {
                            const maxCount = Math.max(...pipeline.stages.map(s => s.count), 1);
                            const pct = (stage.count / maxCount) * 100;
                            return (
                                <div key={stage.name} className="flex items-center gap-3">
                                    <span className="text-xs font-medium text-slate-600 w-32 truncate">{stage.name}</span>
                                    <div className="flex-1 bg-slate-100 rounded-full h-6 overflow-hidden">
                                        <div
                                            className="h-full bg-gradient-to-r from-blue-500 to-violet-500 rounded-full flex items-center justify-end pr-2 transition-all duration-500"
                                            style={{ width: `${Math.max(pct, 8)}%` }}
                                        >
                                            <span className="text-[10px] font-bold text-white">{stage.count}</span>
                                        </div>
                                    </div>
                                    <span className="text-[10px] text-slate-400 w-12 text-right">{stage.conversionRate}%</span>
                                </div>
                            );
                        })}
                    </div>
                </div>
            )}

            {/* Aging Analysis */}
            {pipeline && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                    <h3 className="text-sm font-bold text-slate-900 mb-4">
                        Pipeline Aging — {pipeline.totalActive} active candidates
                    </h3>
                    <div className="grid grid-cols-4 gap-3">
                        {pipeline.aging.map((a, i) => (
                            <div key={a.range} className={`p-4 rounded-xl text-center ${i === 3 ? "bg-red-50 border border-red-100" :
                                    i === 2 ? "bg-amber-50 border border-amber-100" :
                                        "bg-slate-50 border border-slate-100"
                                }`}>
                                <p className="text-2xl font-black text-slate-900">{a.count}</p>
                                <p className="text-[10px] text-slate-500 mt-1">{a.range}</p>
                                <p className="text-[10px] font-bold text-slate-400 mt-0.5">{a.pct}%</p>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}

// ─── Pipeline Tab ───────────────────────────────────────
function PipelineTab({ data }: { data: PipelineHealthData | null }) {
    if (!data || data.stages.length === 0) return <EmptyState label="No pipeline data" />;

    return (
        <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
            <div className="p-5 border-b border-slate-100">
                <h3 className="text-sm font-bold text-slate-900">Stage Performance</h3>
                <p className="text-xs text-slate-500 mt-0.5">{data.totalActive} active candidates across {data.stages.length} stages</p>
            </div>
            <div className="overflow-x-auto">
                <table className="w-full text-sm">
                    <thead>
                        <tr className="bg-slate-50 text-left">
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase">Stage</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Current</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Avg Duration</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Conv Rate</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-center">Status</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-50">
                        {data.stages.map(stage => (
                            <tr key={stage.name} className="hover:bg-slate-50/50">
                                <td className="px-5 py-3.5 font-medium text-slate-800">{stage.name}</td>
                                <td className="px-5 py-3.5 text-right text-slate-600">{stage.count}</td>
                                <td className="px-5 py-3.5 text-right text-slate-600">{stage.avgDuration} days</td>
                                <td className="px-5 py-3.5 text-right text-slate-600">{stage.conversionRate}%</td>
                                <td className="px-5 py-3.5 text-center">
                                    <StatusBadge status={stage.status} />
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

// ─── Sources Tab ────────────────────────────────────────
function SourcesTab({ data }: { data: SourceData[] | null }) {
    if (!data || data.length === 0) return <EmptyState label="No source data" />;

    const bestSource = data.reduce((a, b) => a.conversionRate > b.conversionRate ? a : b);

    return (
        <div className="space-y-4">
            {/* Best Source Banner */}
            <div className="p-4 bg-gradient-to-r from-emerald-50 to-teal-50 border border-emerald-200 rounded-2xl flex items-center gap-3">
                <div className="p-2 bg-emerald-100 rounded-xl">
                    <TrendingUp className="w-5 h-5 text-emerald-600" />
                </div>
                <div>
                    <p className="text-sm font-bold text-emerald-900">Best ROI: {bestSource.source}</p>
                    <p className="text-xs text-emerald-600">{bestSource.conversionRate}% conversion rate • {bestSource.hires} hires</p>
                </div>
            </div>

            {/* Source Table */}
            <div className="bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden">
                <table className="w-full text-sm">
                    <thead>
                        <tr className="bg-slate-50 text-left">
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase">Source</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Applications</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Hires</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Conversion</th>
                            <th className="px-5 py-3 text-xs font-bold text-slate-500 uppercase text-right">Avg Time</th>
                        </tr>
                    </thead>
                    <tbody className="divide-y divide-slate-50">
                        {data.map(src => (
                            <tr key={src.source} className="hover:bg-slate-50/50">
                                <td className="px-5 py-3.5 font-medium text-slate-800">{src.source}</td>
                                <td className="px-5 py-3.5 text-right text-slate-600">{src.applications}</td>
                                <td className="px-5 py-3.5 text-right text-slate-600">{src.hires}</td>
                                <td className="px-5 py-3.5 text-right">
                                    <span className={`font-bold ${src.conversionRate >= 10 ? "text-emerald-600" : src.conversionRate >= 5 ? "text-amber-600" : "text-slate-600"}`}>
                                        {src.conversionRate}%
                                    </span>
                                </td>
                                <td className="px-5 py-3.5 text-right text-slate-600">{src.avgTimeToHire || "—"} days</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

// ─── Recruiters Tab ─────────────────────────────────────
function RecruitersTab({ data }: { data: RecruiterData[] | null }) {
    if (!data || data.length === 0) return <EmptyState label="No recruiter data" />;

    const medals = ["🥇", "🥈", "🥉"];

    return (
        <div className="bg-white rounded-2xl border border-slate-100 shadow-sm">
            <div className="p-5 border-b border-slate-100">
                <h3 className="text-sm font-bold text-slate-900">Recruiter Leaderboard</h3>
            </div>
            <div className="divide-y divide-slate-50">
                {data.map((rec, i) => (
                    <div key={rec.id} className="flex items-center gap-4 p-4 hover:bg-slate-50/50">
                        <span className="text-lg w-8 text-center">{medals[i] || `${i + 1}.`}</span>
                        <div className="w-9 h-9 rounded-full bg-gradient-to-br from-blue-400 to-violet-500 flex items-center justify-center text-white text-sm font-bold">
                            {rec.name.charAt(0)}
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="text-sm font-semibold text-slate-800">{rec.name}</p>
                            <p className="text-xs text-slate-500">
                                {rec.hires} hires • {rec.activeCandidates} active • {rec.conversionRate}% conversion
                            </p>
                        </div>
                        <div className="text-right">
                            <p className="text-sm font-bold text-slate-900">{rec.avgTimeToHire || "—"}</p>
                            <p className="text-[10px] text-slate-400">avg days</p>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}

// ─── Time Tab ───────────────────────────────────────────
function TimeTab({ data }: { data: TimeToFillData[] | null }) {
    if (!data || data.length === 0) return <EmptyState label="No time data" />;

    const totalDays = data.reduce((sum, d) => sum + d.avgDays, 0);

    return (
        <div className="space-y-4">
            <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                <div className="flex items-center justify-between mb-4">
                    <h3 className="text-sm font-bold text-slate-900">Time-to-Fill by Stage</h3>
                    <span className="text-xs text-slate-500">Total: {Math.round(totalDays)} days</span>
                </div>
                {/* Waterfall Chart */}
                <div className="space-y-3">
                    {data.map(stage => {
                        const maxDays = Math.max(...data.map(d => d.avgDays), 1);
                        const pct = (stage.avgDays / maxDays) * 100;
                        return (
                            <div key={stage.stage} className="flex items-center gap-3">
                                <span className="text-xs font-medium text-slate-600 w-36 truncate">{stage.stage}</span>
                                <div className="flex-1 bg-slate-100 rounded-full h-8 overflow-hidden relative">
                                    <div
                                        className={`h-full rounded-full flex items-center justify-end pr-3 transition-all duration-500 ${stage.status === "critical" ? "bg-gradient-to-r from-red-400 to-red-500" :
                                                stage.status === "warning" ? "bg-gradient-to-r from-amber-400 to-amber-500" :
                                                    "bg-gradient-to-r from-emerald-400 to-emerald-500"
                                            }`}
                                        style={{ width: `${Math.max(pct, 15)}%` }}
                                    >
                                        <span className="text-xs font-bold text-white">{stage.avgDays}d</span>
                                    </div>
                                    {/* Target marker */}
                                    <div
                                        className="absolute top-0 bottom-0 w-0.5 bg-slate-400"
                                        style={{ left: `${(stage.targetDays / maxDays) * 100}%` }}
                                        title={`Target: ${stage.targetDays}d`}
                                    />
                                </div>
                                <StatusBadge status={stage.status} />
                            </div>
                        );
                    })}
                </div>
                <div className="flex items-center gap-4 mt-4 text-[10px] text-slate-400">
                    <span className="flex items-center gap-1"><div className="w-2 h-2 rounded-full bg-emerald-500" /> On target</span>
                    <span className="flex items-center gap-1"><div className="w-2 h-2 rounded-full bg-amber-500" /> Slow</span>
                    <span className="flex items-center gap-1"><div className="w-2 h-2 rounded-full bg-red-500" /> Critical</span>
                    <span className="flex items-center gap-1"><div className="w-0.5 h-3 bg-slate-400" /> Target</span>
                </div>
            </div>
        </div>
    );
}

// ─── Offers Tab ─────────────────────────────────────────
function OffersTab({ data }: { data: OfferData | null }) {
    if (!data) return <EmptyState label="No offer data" />;

    const segments = [
        { label: "Accepted", count: data.accepted, color: "bg-emerald-500", textColor: "text-emerald-700" },
        { label: "Declined", count: data.declined, color: "bg-red-400", textColor: "text-red-700" },
        { label: "Pending", count: data.pending, color: "bg-amber-400", textColor: "text-amber-700" },
        { label: "Expired", count: data.expired, color: "bg-slate-400", textColor: "text-slate-600" },
    ];

    return (
        <div className="space-y-4">
            <div className="grid grid-cols-3 gap-4">
                <div className="bg-white rounded-2xl border border-slate-100 p-5 shadow-sm text-center">
                    <p className="text-3xl font-black text-slate-900">{data.totalOffers}</p>
                    <p className="text-xs text-slate-500 mt-1">Total Offers</p>
                </div>
                <div className="bg-white rounded-2xl border border-slate-100 p-5 shadow-sm text-center">
                    <p className={`text-3xl font-black ${data.acceptanceRate >= 75 ? "text-emerald-600" : data.acceptanceRate >= 50 ? "text-amber-600" : "text-red-600"}`}>
                        {data.acceptanceRate}%
                    </p>
                    <p className="text-xs text-slate-500 mt-1">Acceptance Rate</p>
                </div>
                <div className="bg-white rounded-2xl border border-slate-100 p-5 shadow-sm text-center">
                    <p className="text-3xl font-black text-slate-900">{data.avgDecisionDays}</p>
                    <p className="text-xs text-slate-500 mt-1">Avg Decision (days)</p>
                </div>
            </div>

            {/* Offer Breakdown Bar */}
            <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                <h3 className="text-sm font-bold text-slate-900 mb-4">Offer Status Breakdown</h3>
                {data.totalOffers > 0 ? (
                    <>
                        <div className="flex h-6 rounded-full overflow-hidden gap-0.5">
                            {segments.filter(s => s.count > 0).map(s => (
                                <div
                                    key={s.label}
                                    className={`${s.color} transition-all duration-500`}
                                    style={{ width: `${(s.count / data.totalOffers) * 100}%` }}
                                    title={`${s.label}: ${s.count}`}
                                />
                            ))}
                        </div>
                        <div className="flex gap-4 mt-3">
                            {segments.map(s => (
                                <div key={s.label} className="flex items-center gap-1.5 text-xs">
                                    <div className={`w-2 h-2 rounded-full ${s.color}`} />
                                    <span className={`font-medium ${s.textColor}`}>{s.label}: {s.count}</span>
                                </div>
                            ))}
                        </div>
                    </>
                ) : (
                    <p className="text-sm text-slate-400 text-center py-4">No offers in this period</p>
                )}
            </div>

            {/* Decline Reasons */}
            {data.declineReasons.length > 0 && (
                <div className="bg-white rounded-2xl border border-slate-100 p-6 shadow-sm">
                    <h3 className="text-sm font-bold text-slate-900 mb-3">Decline Reasons</h3>
                    <div className="space-y-2">
                        {data.declineReasons.map(r => (
                            <div key={r.reason} className="flex items-center justify-between p-3 bg-red-50/50 rounded-xl">
                                <span className="text-sm text-slate-700">{r.reason}</span>
                                <span className="text-sm font-bold text-red-600">{r.count}</span>
                            </div>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
}

// ─── Status Badge ───────────────────────────────────────
function StatusBadge({ status }: { status: "good" | "warning" | "critical" }) {
    const config = {
        good: { icon: CheckCircle2, label: "Good", className: "text-emerald-600 bg-emerald-50" },
        warning: { icon: AlertTriangle, label: "Slow", className: "text-amber-600 bg-amber-50" },
        critical: { icon: XCircle, label: "Critical", className: "text-red-600 bg-red-50" },
    };
    const { icon: Icon, label, className } = config[status];
    return (
        <span className={`inline-flex items-center gap-1 text-[10px] font-bold px-2 py-1 rounded-full ${className}`}>
            <Icon className="w-3 h-3" />{label}
        </span>
    );
}

function EmptyState({ label }: { label: string }) {
    return (
        <div className="text-center py-16 bg-white rounded-2xl border border-slate-100">
            <BarChart3 className="w-10 h-10 text-slate-300 mx-auto mb-3" />
            <p className="text-sm text-slate-500">{label}</p>
            <p className="text-xs text-slate-400 mt-1">Try adjusting the date range or check back later</p>
        </div>
    );
}
