"use client";

import React, { useState, useEffect } from "react";
import IconBriefCase from "../../components/Icon/IconBriefCase";
import IconCircleCheck from "../../components/Icon/IconCircleCheck";
import IconUsers from "../../components/Icon/IconUsers";
import IconBarChart from "../../components/Icon/IconBarChart";
import IconBuilding from "../../components/Icon/IconBuilding";
import IconTrendingUp from "../../components/Icon/IconTrendingUp";
import api from "../../api/axios";
import {
  SkeletonCard,
  SkeletonList,
} from "../../components/Skeleton/Skeleton";

interface PlacementProps {
  selectedMonth: Date;
}

export default function Placement({ selectedMonth }: PlacementProps) {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState<any>(null);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    fetchDashboardData();
  }, [selectedMonth]);

  const fetchDashboardData = async () => {
    setLoading(true);
    setError(null);
    try {
      const year = selectedMonth.getFullYear();
      const month = selectedMonth.getMonth() + 1;

      const response = await api.get("/dashboard/placement", {
        params: { year, month },
      });

      if (response.data.success) {
        setData(response.data.data);
      } else {
        setError("Failed to fetch dashboard data");
      }
    } catch (err: any) {
      setError(err.response?.data?.message || "Error loading dashboard");
      console.error("Dashboard fetch error:", err);
    } finally {
      setLoading(false);
    }
  };

  const getStatusStyle = (status: string) => {
    switch (status?.toUpperCase()) {
      case "UPCOMING":
        return "bg-violet-100 text-violet-700";
      case "COMPLETED":
        return "bg-emerald-100 text-emerald-700";
      case "CANCELLED":
        return "bg-red-100 text-red-700";
      default:
        return "bg-gray-100 text-gray-700";
    }
  };

  if (error) {
    return (
      <div className="flex items-center justify-center p-8">
        <div className="text-center">
          <p className="text-red-500 mb-2">⚠️ {error}</p>
          <button
            onClick={fetchDashboardData}
            className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  const placementStats = [
    {
      id: 1,
      value: data?.stats?.total_interviews?.current ?? 0,
      label: "TOTAL INTERVIEWS",
      icon: <IconBriefCase />,
      iconBg: "bg-blue-100",
      iconText: "text-blue-500",
      growth: data?.stats?.total_interviews?.growth,
    },
    {
      id: 2,
      value: data?.stats?.total_placed?.current ?? 0,
      label: "PLACED STUDENTS",
      icon: <IconCircleCheck />,
      iconBg: "bg-emerald-100",
      iconText: "text-emerald-500",
      growth: data?.stats?.total_placed?.growth,
    },
    {
      id: 3,
      value: data?.stats?.pending_alumni?.current ?? 0,
      label: "PENDING ALUMNI",
      icon: <IconUsers />,
      iconBg: "bg-orange-100",
      iconText: "text-orange-500",
      growth: data?.stats?.pending_alumni?.growth,
    },
    {
      id: 4,
      value: data?.stats?.placement_ratio?.display ?? "0%",
      label: "OVERALL PLACEMENT RATIO",
      icon: <IconBarChart />,
      iconBg: "bg-violet-100",
      iconText: "text-violet-500",
    },
  ];

  return (
    <div className="space-y-3">
      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
        {loading
          ? [...Array(4)].map((_, i) => <SkeletonCard key={i} />)
          : placementStats.map((item) => (
              <div
                key={item.id}
                className="bg-white rounded-lg border border-gray-200 shadow-sm p-4 flex flex-col items-center justify-center min-h-[170px]"
              >
                <div
                  className={`w-14 h-14 rounded-2xl flex items-center justify-center text-2xl mb-3 ${item.iconBg} ${item.iconText}`}
                >
                  {item.icon}
                </div>
                <h4 className="text-2xl font-black text-gray-900 mb-3">
                  {item.value}
                </h4>
                <span className="text-[11px] tracking-[2px] uppercase font-bold text-gray-400 text-center">
                  {item.label}
                </span>
                {item.growth !== undefined && (
                  <span
                    className={`text-xs mt-2 px-2 py-0.5 rounded-full ${
                      item.growth >= 0
                        ? "bg-green-100 text-green-600"
                        : "bg-red-100 text-red-600"
                    }`}
                  >
                    <IconTrendingUp className="inline-block w-3 h-3 mr-1" />
                    {item.growth >= 0 ? "+" : ""}
                    {item.growth}%
                  </span>
                )}
              </div>
            ))}
      </div>

      {/* Placement Wall of Honor */}
      <div className="bg-white rounded-lg p-3 border border-gray-200 shadow-sm">
        <div className="flex items-start justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold">Placement Wall of Honor</h3>
            <span className="text-xs text-gray-400 font-medium">
              Student highlights and corporate partner success stories
            </span>
          </div>
          <div className="bg-yellow-100 text-yellow-600 text-[12px] font-black tracking-[2px] uppercase px-4 py-2 rounded-full">
            Honored Alumni
          </div>
        </div>

        {loading ? (
          <SkeletonList count={4} />
        ) : (
          <div className="max-h-[350px] overflow-y-auto pr-2">
            <div className="grid grid-cols-1 xl:grid-cols-3 gap-3">
              {data?.placed_students?.length > 0 ? (
                data.placed_students.map((student: any) => (
                  <div
                    key={student.id}
                    className="rounded-lg border border-gray-200 bg-[#fbfcfe] p-6"
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-4">
                        <div className="relative w-14 h-14 rounded-2xl overflow-hidden flex-shrink-0">
                            {student.profile_image && student.profile_image !== 'N/A' ? (
                            <>
                                <img
                                src={student.profile_image}
                                alt={student.name}
                                className="w-full h-full object-cover"
                                onError={(e) => {
                                    // If image fails to load, hide img and show initials
                                    const target = e.target as HTMLImageElement;
                                    target.style.display = 'none';
                                    // Show the initials div
                                    const initialsDiv = target.nextElementSibling as HTMLElement;
                                    if (initialsDiv) {
                                    initialsDiv.style.display = 'flex';
                                    }
                                }}
                                />
                                <div
                                className="absolute inset-0 bg-gradient-to-br from-pink-500 to-rose-500 items-center justify-center text-white font-black hidden"
                                style={{ display: 'none' }}
                                >
                                {student.initials}
                                </div>
                            </>
                            ) : (
                            <div className="w-full h-full bg-gradient-to-br from-pink-500 to-rose-500 flex items-center justify-center text-white font-black">
                                {student.initials}
                            </div>
                            )}
                        </div>
                        <div>
                          <h3 className="text-lg font-black text-gray-900">
                            {student.name}
                          </h3>
                          <span className="text-sm text-gray-400 font-semibold">
                            {student.department}
                          </span>
                        </div>
                      </div>
                      <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-3 py-1 rounded-full text-sm font-black">
                        {student.package}
                      </div>
                    </div>
                   {/* Placed Students Card */}
                    <div className="flex items-center justify-between mt-6">
                    {/* Company Info with Tooltip */}
                    <div className="flex-1 min-w-0 mr-2">
                        <div className="text-sm font-bold text-gray-700 flex items-center justify-start gap-1">
                        <IconBuilding className="flex-shrink-0" />
                        <span className="truncate">Placed</span>
                        <span
                            className="truncate max-w-[120px] inline-block cursor-help"
                            title={student.company}
                        >
                            {student.company}
                        </span>
                        </div>
                    </div>

                    {/* Role with Tooltip */}
                    <div className="flex-shrink-0 max-w-[150px]">
                        <span
                        className="text-sm text-gray-500 font-semibold truncate block cursor-help"
                        title={student.role}
                        >
                        Role: {student.role}
                        </span>
                    </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="col-span-3 text-center py-8 text-gray-500">
                  No placed students found for this month
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Recruiter Interview Events Calendar */}
      <div className="bg-white rounded-lg p-3 border border-gray-200 shadow-sm">
        <div className="flex items-start justify-between mb-4">
          <div>
            <h3 className="text-lg font-semibold">
              Recruiter Interview Events Calendar
            </h3>
            <span className="text-xs text-gray-400 font-medium">
              Upcoming on-site or online interviews scheduled for placement cohorts
            </span>
          </div>
          <div className="text-xs font-black tracking-[2px] uppercase text-gray-400">
            {data?.total_events || 0} TOTAL EVENTS
          </div>
        </div>

        {loading ? (
          <SkeletonList count={4} />
        ) : (
          <div className="max-h-[350px] overflow-y-auto pr-2">
            <div className="grid grid-cols-1 xl:grid-cols-2 gap-3">
              {data?.upcoming_interviews?.length > 0 ? (
                data.upcoming_interviews.map((event: any) => (
                  <div
                    key={event.id}
                    className="rounded-lg border border-gray-200 bg-[#fbfcfe] p-3"
                  >
                    <div className="flex items-start justify-between mb-6">
                      <div>
                        <div
                          className={`inline-flex px-3 py-1 rounded-full text-[10px] font-black tracking-wider mb-4 ${getStatusStyle(
                            event.status
                          )}`}
                        >
                          {event.status}
                        </div>
                        <h3 className="text-xl font-black text-gray-900">
                          {event.company}
                        </h3>
                        <span className="text-sm text-gray-600 font-semibold">
                          {event.role} • {event.package}
                        </span>
                      </div>
                      <div className="text-right">
                        <h4 className="font-black text-gray-700">{event.date}</h4>
                        <span className="text-sm text-gray-400">{event.time}</span>
                      </div>
                    </div>
                    <div>
                      <span className="text-[11px] font-black tracking-[2px] uppercase text-gray-400 mb-3">
                        Eligible Majors
                      </span>
                      <div className="flex flex-wrap gap-2 mb-6">
                        {event.majors?.map((major: string, index: number) => (
                          <span
                            key={index}
                            className="px-3 py-1 rounded-full bg-gray-200 text-gray-700 text-xs font-bold"
                          >
                            {major}
                          </span>
                        ))}
                      </div>
                    </div>
                    <div className="flex items-center justify-between pt-5 border-t border-gray-200">
                      <span className="text-[11px] uppercase tracking-[2px] font-black text-gray-400">
                        Shortlisted Candidates Size
                      </span>
                      <span className="text-sm font-black text-gray-800">
                        {event.selected_text}
                      </span>
                    </div>
                  </div>
                ))
              ) : (
                <div className="col-span-2 text-center py-8 text-gray-500">
                  No upcoming interviews found
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
