"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Briefcase,
  Users,
  Calendar,
  Star,
  TrendingUp,
  Clock,
  ChevronRight,
  Building2,
  ArrowUpRight,
  ArrowDownRight,
  BarChart3,
  X,
} from "lucide-react";

interface DashboardStats {
  openJobs: number;
  totalCandidates: number;
  activeInterviews: number;
  totalEvaluations: number;
  avgRating: number;
  timeToHire: number;
}

interface DashboardData {
  stats: DashboardStats;
  jobsByDepartment: { name: string; count: number }[];
  candidatesBySource: { source: string; count: number }[];
  candidatesByStage: { stage: string; count: number }[];
  recentActivities: { id: number; type: string; description: string; createdAt: string }[];
  upcomingInterviews: { id: number; title: string; scheduledAt: string; type: string }[];
}

function StatCard({ icon: Icon, label, value, change, color, onClick, isSelected }: {
  icon: any;
  label: string;
  value: string | number;
  change?: string;
  color: string;
  onClick?: () => void;
  isSelected?: boolean;
}) {
  const isClickable = Boolean(onClick);
  
  return (
    <button
      onClick={onClick}
      disabled={!isClickable}
      className={`bg-white rounded-xl p-5 border shadow-sm text-left transition-all w-full ${
        isSelected
          ? "border-blue-500 ring-2 ring-blue-200"
          : isClickable
          ? "border-gray-200 hover:border-blue-300 hover:shadow-md cursor-pointer"
          : "border-gray-200"
      }`}
    >
      <div className="flex items-center justify-between mb-3">
        <div className={`p-2.5 rounded-lg ${color}`}>
          <Icon className="w-5 h-5 text-white" />
        </div>
        {change && (
          <div className={`flex items-center gap-1 text-sm font-medium ${
            change.startsWith("+") ? "text-green-600" : "text-red-600"
          }`}>
            {change.startsWith("+") ? (
              <ArrowUpRight className="w-4 h-4" />
            ) : (
              <ArrowDownRight className="w-4 h-4" />
            )}
            {change}
          </div>
        )}
      </div>
      <p className={`text-2xl font-bold ${isClickable ? "text-blue-600" : "text-gray-900"}`}>
        {value}
      </p>
      <p className="text-sm text-gray-500 mt-1">
        {label}
        {isClickable && <span className="text-blue-500 ml-1">→</span>}
      </p>
    </button>
  );
}

function ActivityItem({ activity }: { activity: any }) {
  const getIcon = (type: string) => {
    switch (type) {
      case "candidate_added": return "👤";
      case "stage_changed": return "📋";
      case "interview_scheduled": return "📅";
      case "evaluation_submitted": return "⭐";
      default: return "📌";
    }
  };

  const getTimeAgo = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    if (diffMins < 60) return `${diffMins}m ago`;
    const diffHrs = Math.floor(diffMins / 60);
    if (diffHrs < 24) return `${diffHrs}h ago`;
    const diffDays = Math.floor(diffHrs / 24);
    return `${diffDays}d ago`;
  };

  return (
    <div className="flex items-start gap-3 py-3 border-b border-gray-100 last:border-0">
      <span className="text-lg">{getIcon(activity.type)}</span>
      <div className="flex-1 min-w-0">
        <p className="text-sm text-gray-800 truncate">{activity.description}</p>
        <p className="text-xs text-gray-400 mt-0.5">{getTimeAgo(activity.createdAt)}</p>
      </div>
    </div>
  );
}

type StatType = "jobs" | "candidates" | "interviews" | "evaluations" | "rating" | "timeToHire";

interface PanelData {
  jobs?: any[];
  candidates?: any[];
  interviews?: any[];
  evaluations?: any[];
}

export default function DashboardPage() {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedStat, setSelectedStat] = useState<StatType | null>(null);
  const [panelData, setPanelData] = useState<PanelData>({});
  const [panelLoading, setPanelLoading] = useState(false);

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

  async function handleStatClick(stat: StatType) {
    if (selectedStat === stat) {
      setSelectedStat(null);
      return;
    }

    setSelectedStat(stat);
    setPanelLoading(true);

    try {
      let newData: PanelData = {};

      if (stat === "jobs") {
        const res = await fetch("/api/jobs?status=open");
        newData.jobs = await res.json();
      } else if (stat === "candidates") {
        const res = await fetch("/api/candidates");
        newData.candidates = await res.json();
      } else if (stat === "interviews") {
        const res = await fetch("/api/interviews?upcoming=true");
        newData.interviews = await res.json();
      } else if (stat === "evaluations" || stat === "rating") {
        const res = await fetch("/api/evaluations");
        newData.evaluations = await res.json();
      }

      setPanelData(newData);
    } catch (error) {
      console.error("Failed to fetch panel data:", error);
    } finally {
      setPanelLoading(false);
    }
  }

  if (loading) {
    return (
      <div className="p-6 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 dashboard data
      </div>
    );
  }

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

  return (
    <div className="p-6">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Dashboard</h1>
        <p className="text-gray-500 mt-1">Welcome back, Sarah. Here&apos;s your recruitment overview.</p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6 gap-4 mb-6">
        <StatCard
          icon={Briefcase}
          label="Open Positions"
          value={data.stats.openJobs}
          change="+2"
          color="bg-blue-500"
          onClick={() => handleStatClick("jobs")}
          isSelected={selectedStat === "jobs"}
        />
        <StatCard
          icon={Users}
          label="Total Candidates"
          value={data.stats.totalCandidates}
          change="+8"
          color="bg-purple-500"
          onClick={() => handleStatClick("candidates")}
          isSelected={selectedStat === "candidates"}
        />
        <StatCard
          icon={Calendar}
          label="Active Interviews"
          value={data.stats.activeInterviews}
          change="+3"
          color="bg-green-500"
          onClick={() => handleStatClick("interviews")}
          isSelected={selectedStat === "interviews"}
        />
        <StatCard
          icon={Star}
          label="Evaluations"
          value={data.stats.totalEvaluations}
          color="bg-amber-500"
          onClick={() => handleStatClick("evaluations")}
          isSelected={selectedStat === "evaluations"}
        />
        <StatCard
          icon={TrendingUp}
          label="Avg. Rating"
          value={data.stats.avgRating.toFixed(1)}
          color="bg-pink-500"
          onClick={() => handleStatClick("rating")}
          isSelected={selectedStat === "rating"}
        />
        <StatCard
          icon={Clock}
          label="Avg. Time to Hire"
          value={`${data.stats.timeToHire} days`}
          color="bg-indigo-500"
          onClick={() => handleStatClick("timeToHire")}
          isSelected={selectedStat === "timeToHire"}
        />
      </div>

      {/* Detail Panel */}
      {selectedStat && (
        <div className="mb-6 bg-white rounded-xl border border-gray-200 shadow-sm overflow-hidden">
          <div className="flex items-center justify-between p-5 border-b border-gray-200">
            <h3 className="font-semibold text-gray-900">
              {selectedStat === "jobs" && "Open Positions"}
              {selectedStat === "candidates" && "All Candidates"}
              {selectedStat === "interviews" && "Upcoming Interviews"}
              {selectedStat === "evaluations" && "Recent Evaluations"}
              {selectedStat === "rating" && "Candidate Ratings"}
              {selectedStat === "timeToHire" && "Time to Hire Metrics"}
            </h3>
            <button
              onClick={() => setSelectedStat(null)}
              className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
            >
              <X className="w-5 h-5 text-gray-400" />
            </button>
          </div>
          <div className="p-5">
            {panelLoading ? (
              <div className="flex items-center justify-center py-12">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" />
              </div>
            ) : (
              <>
                {selectedStat === "jobs" && panelData.jobs && (
                  <div className="space-y-3">
                    {panelData.jobs.length === 0 ? (
                      <p className="text-center text-gray-400 py-8">No open positions</p>
                    ) : (
                      panelData.jobs.map((job) => (
                        <Link
                          key={job.id}
                          href={`/jobs/${job.id}`}
                          className="block p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                        >
                          <div className="flex items-start justify-between">
                            <div>
                              <h4 className="font-medium text-gray-900">{job.title}</h4>
                              <p className="text-sm text-gray-500 mt-1">
                                {job.location} • {job.type} • {job.experience}
                              </p>
                              {job.department && (
                                <p className="text-xs text-gray-400 mt-1">{job.department.name}</p>
                              )}
                            </div>
                            <div className="text-right">
                              <span className="badge badge-open">open</span>
                              <p className="text-xs text-gray-400 mt-1">
                                {job.candidateCount} applicants
                              </p>
                            </div>
                          </div>
                        </Link>
                      ))
                    )}
                  </div>
                )}

                {selectedStat === "candidates" && panelData.candidates && (
                  <div className="space-y-2">
                    {panelData.candidates.length === 0 ? (
                      <p className="text-center text-gray-400 py-8">No candidates</p>
                    ) : (
                      panelData.candidates.map((candidate) => (
                        <Link
                          key={candidate.id}
                          href={`/candidates/${candidate.id}`}
                          className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
                        >
                          <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center text-sm font-medium text-blue-700">
                            {candidate.firstName[0]}{candidate.lastName[0]}
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="font-medium text-gray-900 truncate">
                              {candidate.firstName} {candidate.lastName}
                            </p>
                            <p className="text-xs text-gray-500 truncate">{candidate.email}</p>
                          </div>
                          <div className="text-right">
                            <p className="text-xs text-gray-400 capitalize">
                              {candidate.source.replace("_", " ")}
                            </p>
                            <div className="flex items-center gap-0.5 mt-1">
                              {[1, 2, 3, 4, 5].map((star) => (
                                <Star
                                  key={star}
                                  className={`w-3 h-3 ${
                                    star <= (candidate.rating || 0)
                                      ? "fill-amber-400 text-amber-400"
                                      : "text-gray-200"
                                  }`}
                                />
                              ))}
                            </div>
                          </div>
                        </Link>
                      ))
                    )}
                  </div>
                )}

                {selectedStat === "interviews" && panelData.interviews && (
                  <div className="space-y-3">
                    {panelData.interviews.length === 0 ? (
                      <p className="text-center text-gray-400 py-8">No upcoming interviews</p>
                    ) : (
                      panelData.interviews.map((interview) => (
                        <div
                          key={interview.id}
                          className="p-4 bg-gray-50 rounded-lg"
                        >
                          <div className="flex items-start justify-between">
                            <div>
                              <h4 className="font-medium text-gray-900">{interview.title}</h4>
                              {interview.candidate && (
                                <p className="text-sm text-gray-600 mt-1">
                                  {interview.candidate.firstName} {interview.candidate.lastName}
                                </p>
                              )}
                              {interview.job && (
                                <p className="text-xs text-gray-400 mt-0.5">{interview.job.title}</p>
                              )}
                            </div>
                            <div className="text-right">
                              <p className="text-sm font-medium text-gray-900">
                                {new Date(interview.scheduledAt).toLocaleDateString("en-US", {
                                  month: "short",
                                  day: "numeric",
                                })}
                              </p>
                              <p className="text-xs text-gray-500 capitalize mt-0.5">
                                {interview.type} • {interview.duration}min
                              </p>
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                )}

                {selectedStat === "evaluations" && panelData.evaluations && (
                  <div className="space-y-3">
                    {panelData.evaluations.length === 0 ? (
                      <p className="text-center text-gray-400 py-8">No evaluations</p>
                    ) : (
                      panelData.evaluations.slice(0, 10).map((eval_) => (
                        <div key={eval_.id} className="p-4 bg-gray-50 rounded-lg">
                          <div className="flex items-start justify-between mb-2">
                            <div>
                              {eval_.candidate && (
                                <p className="font-medium text-gray-900">
                                  {eval_.candidate.name}
                                </p>
                              )}
                              {eval_.evaluator && (
                                <p className="text-xs text-gray-500">
                                  Evaluated by {eval_.evaluator.name}
                                </p>
                              )}
                            </div>
                            <div className="flex items-center gap-2">
                              <div className="flex items-center gap-0.5">
                                {[1, 2, 3, 4, 5].map((star) => (
                                  <Star
                                    key={star}
                                    className={`w-4 h-4 ${
                                      star <= eval_.rating
                                        ? "fill-amber-400 text-amber-400"
                                        : "text-gray-200"
                                    }`}
                                  />
                                ))}
                              </div>
                              <span
                                className={`text-xs px-2 py-0.5 rounded-full font-medium capitalize ${
                                  eval_.recommendation === "strong_yes"
                                    ? "bg-green-100 text-green-700"
                                    : eval_.recommendation === "yes"
                                    ? "bg-blue-100 text-blue-700"
                                    : eval_.recommendation === "neutral"
                                    ? "bg-gray-100 text-gray-700"
                                    : "bg-red-100 text-red-700"
                                }`}
                              >
                                {eval_.recommendation.replace("_", " ")}
                              </span>
                            </div>
                          </div>
                          <p className="text-sm text-gray-600">{eval_.feedback}</p>
                        </div>
                      ))
                    )}
                  </div>
                )}

                {selectedStat === "rating" && panelData.evaluations && (
                  <div className="space-y-3">
                    {panelData.evaluations.length === 0 ? (
                      <p className="text-center text-gray-400 py-8">No ratings available</p>
                    ) : (
                      <>
                        <div className="p-4 bg-pink-50 rounded-lg border border-pink-200">
                          <div className="flex items-center justify-between">
                            <div>
                              <p className="text-sm font-medium text-pink-900">Overall Average Rating</p>
                              <p className="text-xs text-pink-700 mt-0.5">
                                Based on {panelData.evaluations.length} evaluations
                              </p>
                            </div>
                            <div className="flex items-center gap-2">
                              <div className="flex items-center gap-0.5">
                                {[1, 2, 3, 4, 5].map((star) => (
                                  <Star
                                    key={star}
                                    className={`w-5 h-5 ${
                                      star <= Math.round(data.stats.avgRating)
                                        ? "fill-amber-400 text-amber-400"
                                        : "text-gray-200"
                                    }`}
                                  />
                                ))}
                              </div>
                              <span className="text-2xl font-bold text-pink-700">
                                {data.stats.avgRating.toFixed(1)}
                              </span>
                            </div>
                          </div>
                        </div>
                        <div className="mt-4">
                          <p className="text-sm font-medium text-gray-700 mb-3">Recent Ratings</p>
                          {panelData.evaluations.slice(0, 5).map((eval_) => (
                            <div key={eval_.id} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
                              <div>
                                {eval_.candidate && (
                                  <p className="text-sm font-medium text-gray-900">
                                    {eval_.candidate.name}
                                  </p>
                                )}
                                <p className="text-xs text-gray-500">
                                  {new Date(eval_.createdAt).toLocaleDateString("en-US", {
                                    month: "short",
                                    day: "numeric",
                                  })}
                                </p>
                              </div>
                              <div className="flex items-center gap-0.5">
                                {[1, 2, 3, 4, 5].map((star) => (
                                  <Star
                                    key={star}
                                    className={`w-4 h-4 ${
                                      star <= eval_.rating
                                        ? "fill-amber-400 text-amber-400"
                                        : "text-gray-200"
                                    }`}
                                  />
                                ))}
                              </div>
                            </div>
                          ))}
                        </div>
                      </>
                    )}
                  </div>
                )}

                {selectedStat === "timeToHire" && (
                  <div className="space-y-4">
                    <div className="p-4 bg-indigo-50 rounded-lg border border-indigo-200">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-sm font-medium text-indigo-900">Average Time to Hire</p>
                          <p className="text-xs text-indigo-700 mt-0.5">
                            Industry average: 36 days
                          </p>
                        </div>
                        <div className="text-right">
                          <p className="text-3xl font-bold text-indigo-700">
                            {data.stats.timeToHire}
                          </p>
                          <p className="text-xs text-indigo-600">days</p>
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-3 gap-3">
                      <div className="p-4 bg-gray-50 rounded-lg text-center">
                        <p className="text-2xl font-bold text-gray-900">12</p>
                        <p className="text-xs text-gray-500 mt-1">Fastest (days)</p>
                      </div>
                      <div className="p-4 bg-gray-50 rounded-lg text-center">
                        <p className="text-2xl font-bold text-gray-900">28</p>
                        <p className="text-xs text-gray-500 mt-1">Median (days)</p>
                      </div>
                      <div className="p-4 bg-gray-50 rounded-lg text-center">
                        <p className="text-2xl font-bold text-gray-900">45</p>
                        <p className="text-xs text-gray-500 mt-1">Slowest (days)</p>
                      </div>
                    </div>
                    <p className="text-sm text-gray-600 mt-4">
                      Your hiring process is faster than the industry average. Continue optimizing
                      interview scheduling and decision-making to maintain this efficiency.
                    </p>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
        {/* Candidates by Stage */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-gray-900">Candidates by Stage</h2>
            <Link href="/candidates" className="text-sm text-blue-600 hover:text-blue-700 flex items-center gap-1">
              View all <ChevronRight className="w-4 h-4" />
            </Link>
          </div>
          <div className="space-y-3">
            {data.candidatesByStage.map((item) => (
              <div key={item.stage}>
                <div className="flex items-center justify-between text-sm mb-1">
                  <span className="text-gray-700">{item.stage}</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="bg-blue-500 h-2 rounded-full transition-all duration-500"
                    style={{ width: `${(item.count / maxStageCount) * 100}%` }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Candidates by Source */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-gray-900">Source Performance</h2>
            <Link href="/reports" className="text-sm text-blue-600 hover:text-blue-700 flex items-center gap-1">
              Reports <ChevronRight className="w-4 h-4" />
            </Link>
          </div>
          <div className="space-y-3">
            {data.candidatesBySource.map((item) => (
              <div key={item.source}>
                <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="bg-purple-500 h-2 rounded-full transition-all duration-500"
                    style={{ width: `${(item.count / maxSourceCount) * 100}%` }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Jobs by Department */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-gray-900">Jobs by Department</h2>
            <Link href="/jobs" className="text-sm text-blue-600 hover:text-blue-700 flex items-center gap-1">
              View all <ChevronRight className="w-4 h-4" />
            </Link>
          </div>
          <div className="space-y-3">
            {data.jobsByDepartment.map((item) => (
              <div key={item.name} className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-8 h-8 bg-gray-100 rounded-lg flex items-center justify-center">
                    <Building2 className="w-4 h-4 text-gray-500" />
                  </div>
                  <span className="text-sm text-gray-700">{item.name}</span>
                </div>
                <span className="bg-blue-100 text-blue-700 text-xs font-medium px-2.5 py-1 rounded-full">
                  {item.count}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Activity */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-gray-900">Recent Activity</h2>
          </div>
          <div>
            {data.recentActivities.map((activity) => (
              <ActivityItem key={activity.id} activity={activity} />
            ))}
          </div>
        </div>

        {/* Upcoming Interviews */}
        <div className="bg-white rounded-xl border border-gray-200 shadow-sm p-5">
          <div className="flex items-center justify-between mb-4">
            <h2 className="font-semibold text-gray-900">Upcoming Interviews</h2>
            <Link href="/interviews" className="text-sm text-blue-600 hover:text-blue-700 flex items-center gap-1">
              View all <ChevronRight className="w-4 h-4" />
            </Link>
          </div>
          <div className="space-y-3">
            {data.upcomingInterviews.length === 0 ? (
              <p className="text-sm text-gray-400 text-center py-8">No upcoming interviews</p>
            ) : (
              data.upcomingInterviews.map((interview) => (
                <div key={interview.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
                  <div className="w-10 h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                    <Calendar className="w-5 h-5 text-blue-600" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-medium text-gray-900 truncate">{interview.title}</p>
                    <p className="text-xs text-gray-500 capitalize">{interview.type} interview</p>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-medium text-gray-900">
                      {new Date(interview.scheduledAt).toLocaleDateString("en-US", { month: "short", day: "numeric" })}
                    </p>
                    <p className="text-xs text-gray-500">
                      {new Date(interview.scheduledAt).toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" })}
                    </p>
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
