"use client";

import { useEffect, useState } from "react";
import {
  BarChart3,
  TrendingUp,
  TrendingDown,
  Users,
  Briefcase,
  Calendar,
  Star,
  Clock,
  Building2,
  PieChart,
} from "lucide-react";

interface ReportData {
  stats: {
    openJobs: number;
    totalCandidates: number;
    activeInterviews: number;
    avgRating: number;
    timeToHire: number;
  };
  jobsByDepartment: { name: string; count: number }[];
  candidatesBySource: { source: string; count: number }[];
  candidatesByStage: { stage: string; count: number }[];
}

export default function ReportsPage() {
  const [data, setData] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch("/api/dashboard")
      .then((res) => res.json())
      .then((d) => {
        setData(d);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
      </div>
    );
  }

  if (!data) return <div className="p-6 text-center text-gray-500">Failed to load reports</div>;

  const maxStageCount = Math.max(...data.candidatesByStage.map((s) => s.count), 1);
  const maxSourceCount = Math.max(...data.candidatesBySource.map((s) => s.count), 1);
  const maxDeptCount = Math.max(...data.jobsByDepartment.map((d) => d.count), 1);

  const sourceColors: Record<string, string> = {
    linkedin: "bg-blue-500",
    indeed: "bg-purple-500",
    referral: "bg-green-500",
    company_website: "bg-amber-500",
    glassdoor: "bg-pink-500",
    direct: "bg-indigo-500",
  };

  return (
    <div className="p-6">
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Reports & Analytics</h1>
        <p className="text-gray-500 mt-1">Track your recruitment metrics and performance</p>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 mb-8">
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-blue-100 rounded-lg">
              <Briefcase className="w-5 h-5 text-blue-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{data.stats.openJobs}</p>
          <p className="text-sm text-gray-500">Open Positions</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-purple-100 rounded-lg">
              <Users className="w-5 h-5 text-purple-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{data.stats.totalCandidates}</p>
          <p className="text-sm text-gray-500">Total Candidates</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-green-100 rounded-lg">
              <Calendar className="w-5 h-5 text-green-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{data.stats.activeInterviews}</p>
          <p className="text-sm text-gray-500">Active Interviews</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-amber-100 rounded-lg">
              <Star className="w-5 h-5 text-amber-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{data.stats.avgRating.toFixed(1)}</p>
          <p className="text-sm text-gray-500">Average Rating</p>
        </div>
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="p-2 bg-indigo-100 rounded-lg">
              <Clock className="w-5 h-5 text-indigo-600" />
            </div>
          </div>
          <p className="text-2xl font-bold text-gray-900">{data.stats.timeToHire}d</p>
          <p className="text-sm text-gray-500">Avg. Time to Hire</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Pipeline Funnel */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-2 mb-4">
            <BarChart3 className="w-5 h-5 text-gray-500" />
            <h2 className="font-semibold text-gray-900">Pipeline Funnel</h2>
          </div>
          <div className="space-y-4">
            {data.candidatesByStage.map((item, index) => (
              <div key={item.stage}>
                <div className="flex items-center justify-between text-sm mb-1.5">
                  <span className="text-gray-700 font-medium">{item.stage}</span>
                  <span className="text-gray-900 font-bold">{item.count}</span>
                </div>
                <div className="w-full bg-gray-100 rounded-full h-3">
                  <div
                    className={`h-3 rounded-full transition-all duration-500 ${
                      index === 0
                        ? "bg-gray-400"
                        : index === 1
                        ? "bg-blue-500"
                        : index === 2
                        ? "bg-purple-500"
                        : index === 3
                        ? "bg-amber-500"
                        : index === 4
                        ? "bg-green-500"
                        : "bg-emerald-500"
                    }`}
                    style={{ width: `${(item.count / maxStageCount) * 100}%` }}
                  />
                </div>
                {index < data.candidatesByStage.length - 1 && (
                  <div className="flex items-center justify-between text-xs text-gray-400 mt-1">
                    <span></span>
                    {item.count > 0 && data.candidatesByStage[index + 1]?.count > 0 && (
                      <span>
                        {Math.round(
                          (data.candidatesByStage[index + 1].count / item.count) * 100
                        )}
                        % conversion
                      </span>
                    )}
                  </div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Source Performance */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-2 mb-4">
            <PieChart className="w-5 h-5 text-gray-500" />
            <h2 className="font-semibold text-gray-900">Source Performance</h2>
          </div>
          <div className="space-y-4">
            {data.candidatesBySource
              .sort((a, b) => b.count - a.count)
              .map((item) => (
                <div key={item.source} className="flex items-center gap-3">
                  <div
                    className={`w-3 h-3 rounded-full ${sourceColors[item.source] || "bg-gray-400"}`}
                  />
                  <div className="flex-1">
                    <div className="flex items-center justify-between text-sm mb-1">
                      <span className="text-gray-700 capitalize">
                        {item.source.replace("_", " ")}
                      </span>
                      <span className="font-medium text-gray-900">{item.count}</span>
                    </div>
                    <div className="w-full bg-gray-100 rounded-full h-2">
                      <div
                        className={`h-2 rounded-full transition-all duration-500 ${
                          sourceColors[item.source] || "bg-gray-400"
                        }`}
                        style={{ width: `${(item.count / maxSourceCount) * 100}%` }}
                      />
                    </div>
                  </div>
                </div>
              ))}
          </div>
        </div>

        {/* Department Hiring */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center gap-2 mb-4">
            <Building2 className="w-5 h-5 text-gray-500" />
            <h2 className="font-semibold text-gray-900">Hiring by Department</h2>
          </div>
          <div className="space-y-4">
            {data.jobsByDepartment.map((item) => (
              <div key={item.name}>
                <div className="flex items-center justify-between text-sm mb-1.5">
                  <span className="text-gray-700 font-medium">{item.name}</span>
                  <span className="font-bold text-gray-900">{item.count}</span>
                </div>
                <div className="w-full bg-gray-100 rounded-full h-3">
                  <div
                    className="bg-blue-600 h-3 rounded-full transition-all duration-500"
                    style={{ width: `${(item.count / maxDeptCount) * 100}%` }}
                  />
                </div>
              </div>
            ))}
          </div>

          <div className="mt-6 pt-6 border-t border-gray-100">
            <h3 className="font-medium text-gray-900 mb-3">Recruitment Metrics</h3>
            <div className="grid grid-cols-2 gap-3">
              <div className="p-3 bg-green-50 rounded-lg">
                <div className="flex items-center gap-1.5 text-green-700 text-sm mb-0.5">
                  <TrendingUp className="w-4 h-4" />
                  Application Rate
                </div>
                <p className="text-lg font-bold text-green-700">
                  {Math.round(data.stats.totalCandidates / Math.max(data.stats.openJobs, 1))}
                </p>
                <p className="text-xs text-green-600">per open role</p>
              </div>
              <div className="p-3 bg-blue-50 rounded-lg">
                <div className="flex items-center gap-1.5 text-blue-700 text-sm mb-0.5">
                  <Clock className="w-4 h-4" />
                  Avg. Time to Hire
                </div>
                <p className="text-lg font-bold text-blue-700">{data.stats.timeToHire}d</p>
                <p className="text-xs text-blue-600">industry avg: 36d</p>
              </div>
              <div className="p-3 bg-purple-50 rounded-lg">
                <div className="flex items-center gap-1.5 text-purple-700 text-sm mb-0.5">
                  <Users className="w-4 h-4" />
                  Interview Rate
                </div>
                <p className="text-lg font-bold text-purple-700">
                  {Math.round(
                    (data.stats.activeInterviews / Math.max(data.stats.totalCandidates, 1)) * 100
                  )}
                  %
                </p>
                <p className="text-xs text-purple-600">of total candidates</p>
              </div>
              <div className="p-3 bg-amber-50 rounded-lg">
                <div className="flex items-center gap-1.5 text-amber-700 text-sm mb-0.5">
                  <Star className="w-4 h-4" />
                  Quality Score
                </div>
                <p className="text-lg font-bold text-amber-700">{data.stats.avgRating.toFixed(1)}</p>
                <p className="text-xs text-amber-600">out of 5.0</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
