"use client";

import { useState } from "react";
import { WidgetContainer } from "./WidgetContainer";
import {
    Users, Briefcase, TrendingUp, Building,
    CheckCircle, FileText, ArrowRight, Zap, Target, Star
} from "lucide-react";
import Link from "next/link";
import { motion } from "framer-motion";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";

interface PipelineCounts {
    total: number;
    pending: number;
    reviewing: number;
    interview: number;
    offered: number;
    rejected: number;
}

export function HiringMetricsWidget({ pipeline, totalViews = 0 }: { pipeline?: PipelineCounts; totalViews?: number }) {
    const total = pipeline?.total || 0;
    const interviewRate = total > 0 ? ((pipeline?.interview || 0) / total * 100).toFixed(1) : "0.0";
    const offerRate = total > 0 && (pipeline?.interview || 0) > 0
        ? ((pipeline?.offered || 0) / (pipeline?.interview || 1) * 100).toFixed(1)
        : "0.0";
    const viewToAppRate = totalViews > 0 ? (total / totalViews * 100).toFixed(1) : "—";

    return (
        <WidgetContainer title="Hiring Metrics" icon={<TrendingUp className="text-blue-500" />}>
            <div className="grid grid-cols-2 gap-4 mb-6">
                <div className="p-3 bg-slate-50 rounded-xl border border-slate-100">
                    <p className="text-xs text-slate-500 font-semibold mb-1">Total Applicants</p>
                    <div className="flex items-end gap-2">
                        <span className="text-2xl font-black text-slate-900">{total}</span>
                    </div>
                </div>
                <div className="p-3 bg-slate-50 rounded-xl border border-slate-100">
                    <p className="text-xs text-slate-500 font-semibold mb-1">Interview Rate</p>
                    <div className="flex items-end gap-2">
                        <span className="text-2xl font-black text-slate-900">{interviewRate}<span className="text-sm font-semibold">%</span></span>
                    </div>
                </div>
            </div>

            <div className="space-y-4">
                <div>
                    <div className="flex justify-between text-xs mb-1">
                        <span className="font-semibold text-slate-600">View to Application</span>
                        <span className="font-bold text-slate-900">{viewToAppRate}{viewToAppRate !== "—" ? "%" : ""}</span>
                    </div>
                    <Progress value={viewToAppRate === "—" ? 0 : parseFloat(viewToAppRate)} className="h-2" />
                </div>
                <div>
                    <div className="flex justify-between text-xs mb-1">
                        <span className="font-semibold text-slate-600">App to Interview</span>
                        <span className="font-bold text-slate-900">{interviewRate}%</span>
                    </div>
                    <Progress value={parseFloat(interviewRate)} className="h-2" />
                </div>
                <div>
                    <div className="flex justify-between text-xs mb-1">
                        <span className="font-semibold text-slate-600">Interview to Offer</span>
                        <span className="font-bold text-slate-900">{offerRate}%</span>
                    </div>
                    <Progress value={parseFloat(offerRate)} className="h-2" />
                </div>
            </div>

            <Link href="/dashboard/analytics" className="mt-6 block text-center text-sm font-bold text-primary hover:underline">View Detailed Analytics</Link>
        </WidgetContainer>
    );
}

export function ApplicantPipelineWidget({ pipeline }: { pipeline?: PipelineCounts }) {
    const total = pipeline?.total || 0;
    const stages = [
        { name: "New Applications", count: pipeline?.pending || 0, color: "bg-blue-500" },
        { name: "Screening", count: pipeline?.reviewing || 0, color: "bg-indigo-500" },
        { name: "Interviewing", count: pipeline?.interview || 0, color: "bg-purple-500" },
        { name: "Offered", count: pipeline?.offered || 0, color: "bg-emerald-500" },
        { name: "Rejected", count: pipeline?.rejected || 0, color: "bg-rose-500" },
    ];

    return (
        <WidgetContainer title="Applicant Pipeline" icon={<Users className="text-indigo-500" />}>
            {total === 0 ? (
                <div className="flex flex-col items-center justify-center py-8 text-center">
                    <Users className="h-10 w-10 text-slate-300 mb-3" />
                    <p className="font-semibold text-slate-700 mb-1">No applicants yet</p>
                    <p className="text-sm text-slate-500">Post a job to start receiving applications.</p>
                </div>
            ) : (
                <>
                    <div className="flex flex-col gap-2">
                        {stages.map((stage, idx) => {
                            const prevCount = idx > 0 ? stages[idx - 1].count : total;
                            const conversion = prevCount > 0 ? ((stage.count / prevCount) * 100).toFixed(0) : "0";
                            return (
                                <div key={stage.name}>
                                    <PipelineStage name={stage.name} count={stage.count} total={total} color={stage.color} />
                                    {idx < stages.length - 1 && (
                                        <div className="ml-4 border-l-2 border-slate-100 pl-4 py-1 text-[10px] font-bold text-slate-400">
                                            {conversion}% conversion
                                        </div>
                                    )}
                                </div>
                            );
                        })}
                    </div>

                    <div className="mt-6 pt-4 border-t border-slate-100 flex justify-between items-center text-sm bg-slate-50 p-3 rounded-xl">
                        <span className="font-semibold text-slate-600">Total in Pipeline</span>
                        <span className="font-black text-slate-900 text-lg">{total}</span>
                    </div>
                </>
            )}
        </WidgetContainer>
    );
}

function PipelineStage({ name, count, total, color }: { name: string, count: number, total: number, color: string }) {
    const width = total > 0 ? Math.max((count / total) * 100, 5) : 5;
    return (
        <div className="group cursor-pointer">
            <div className="flex justify-between text-sm mb-1">
                <span className="font-semibold text-slate-700 group-hover:text-primary transition-colors">{name}</span>
                <span className="font-bold text-slate-900">{count}</span>
            </div>
            <div className="h-6 w-full bg-slate-100 rounded-md overflow-hidden relative">
                <motion.div
                    initial={{ width: 0 }}
                    animate={{ width: `${width}%` }}
                    transition={{ duration: 1, ease: "easeOut" }}
                    className={`h-full ${color} rounded-md`}
                />
            </div>
        </div>
    );
}

export function QuickPostJobWidget() {
    return (
        <WidgetContainer title="Post a Job" icon={<Zap className="text-amber-500" />}>
            <form className="space-y-4" action="/dashboard/jobs/new">
                <div>
                    <label className="block text-xs font-semibold text-slate-600 mb-1">Job Title</label>
                    <input
                        type="text"
                        placeholder="e.g. Senior Product Designer"
                        className="w-full text-sm px-3 py-2 rounded-lg border border-slate-200 focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none transition-all"
                    />
                </div>
                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="block text-xs font-semibold text-slate-600 mb-1">Location</label>
                        <select className="w-full text-sm px-3 py-2 rounded-lg border border-slate-200 focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none transition-all bg-white">
                            <option>Remote</option>
                            <option>Hybrid</option>
                            <option>On-site</option>
                        </select>
                    </div>
                    <div>
                        <label className="block text-xs font-semibold text-slate-600 mb-1">Type</label>
                        <select className="w-full text-sm px-3 py-2 rounded-lg border border-slate-200 focus:border-primary focus:ring-1 focus:ring-primary/20 outline-none transition-all bg-white">
                            <option>Full-time</option>
                            <option>Contract</option>
                            <option>Part-time</option>
                        </select>
                    </div>
                </div>

                <Button type="submit" className="w-full mt-2 flex items-center justify-center gap-2">
                    <Zap className="h-4 w-4" fill="currentColor" /> Let&apos;s Go
                </Button>
            </form>

            <div className="mt-4 pt-4 border-t border-slate-100 space-y-2">
                <p className="text-xs font-semibold text-slate-500 text-center uppercase tracking-wider mb-2">Or start from</p>
                <Button variant="outline" className="w-full flex items-center justify-center gap-2">
                    <FileText className="h-4 w-4" /> Use Existing Template
                </Button>
            </div>
        </WidgetContainer>
    );
}

export function CompanyProfileWidget({ completion = 0, companyName, industry }: { completion?: number; companyName?: string; industry?: string }) {
    return (
        <WidgetContainer title="Company Profile" icon={<Building className="text-indigo-500" />}>
            <div className="flex items-center gap-4 mb-6">
                <div className="relative w-16 h-16 shrink-0">
                    <svg className="w-full h-full transform -rotate-90">
                        <circle cx="32" cy="32" r="28" className="text-slate-100" strokeWidth="6" fill="none" stroke="currentColor" />
                        <circle
                            cx="32" cy="32" r="28"
                            className="text-primary transition-all duration-1000 ease-out"
                            strokeWidth="6"
                            fill="none"
                            stroke="currentColor"
                            strokeDasharray={`${2 * Math.PI * 28}`}
                            strokeDashoffset={`${2 * Math.PI * 28 * (1 - completion / 100)}`}
                            strokeLinecap="round"
                        />
                    </svg>
                    <div className="absolute inset-0 flex items-center justify-center font-bold text-sm text-slate-800">
                        {completion}%
                    </div>
                </div>
                <div>
                    <h4 className="font-bold text-slate-900">{companyName || "Your Company"}</h4>
                    {industry && <p className="text-xs text-slate-500 mt-0.5">{industry}</p>}
                    <p className="text-sm text-slate-500 mt-1">
                        {completion >= 80 ? "Your profile is looking great!" : "Complete your profile to attract top talent."}
                    </p>
                </div>
            </div>

            <div className="space-y-2 mb-6">
                <div className={`flex items-center justify-between p-2.5 rounded-lg ${completion >= 40 ? "bg-slate-50 border border-slate-100" : "bg-orange-50 border border-orange-100 border-l-2 border-l-orange-500"}`}>
                    <div className="flex items-center gap-2">
                        {completion >= 40 ? <CheckCircle className="h-4 w-4 text-emerald-500" /> : <span className="w-1.5 h-1.5 rounded-full bg-orange-500 ml-1.5" />}
                        <span className={`text-sm ${completion >= 40 ? "text-slate-600 line-through" : "font-semibold text-orange-900"}`}>Basic company info</span>
                    </div>
                    {completion < 40 && <Link href="/dashboard/employer/company" className="text-xs font-bold text-orange-700 bg-orange-100/50 px-2 py-1 rounded hover:bg-orange-200">Add</Link>}
                </div>
                <div className={`flex items-center justify-between p-2.5 rounded-lg ${completion >= 80 ? "bg-slate-50 border border-slate-100" : "bg-slate-50 border border-slate-100"}`}>
                    <div className="flex items-center gap-2">
                        {completion >= 80 ? <CheckCircle className="h-4 w-4 text-emerald-500" /> : <span className="w-1.5 h-1.5 rounded-full bg-slate-300 ml-1.5" />}
                        <span className="text-sm font-medium text-slate-600">Company description</span>
                    </div>
                    {completion < 80 && <Link href="/dashboard/employer/company" className="text-xs font-bold text-slate-600 bg-slate-200/50 px-2 py-1 rounded hover:bg-slate-200">Add</Link>}
                </div>
            </div>

            <div className="pt-4 border-t border-slate-100">
                <Link href="/dashboard/employer/company" className="block text-center text-sm font-bold text-primary hover:underline">
                    Manage Company Profile
                </Link>
            </div>
        </WidgetContainer>
    );
}

export function JobPerformanceWidget() {
    return (
        <WidgetContainer title="Job Performance" icon={<Target className="text-rose-500" />}>
            <div className="flex flex-col items-center justify-center py-8 text-center">
                <Target className="h-10 w-10 text-slate-300 mb-3" />
                <p className="font-semibold text-slate-700 mb-1">Performance Analytics</p>
                <p className="text-sm text-slate-500 mb-4">Detailed job post performance metrics will appear here once you have active listings.</p>
                <Button asChild variant="outline" size="sm">
                    <Link href="/dashboard/employer/post-job">Post Your First Job</Link>
                </Button>
            </div>
        </WidgetContainer>
    );
}
