"use client";
import { useState, useEffect } from "react";
import {
  Users,
  Calendar,
  Bell,
  Shield,
  Sun,
  Moon,
  Sunset,
  TrendingUp,
  Clock,
  CheckCircle,
  AlertCircle,
  Megaphone,
} from "lucide-react";
import { format } from "date-fns";
import Avatar from "./ui/Avatar";
import Badge from "./ui/Badge";
import { formatTime } from "@/lib/utils";

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  rank: string | null;
  orgNodeId: number | null;
  avatarColor: string | null;
  badgeNumber: string | null;
}

interface OrgNode {
  id: number;
  name: string;
  type: string;
  color: string | null;
}

interface Schedule {
  id: number;
  employeeId: number;
  date: string;
  startTime: string;
  endTime: string;
  shiftType: string | null;
  orgNodeId: number | null;
}

interface TimeOffRequest {
  id: number;
  employeeId: number;
  startDate: string;
  endDate: string;
  type: string | null;
  status: string;
  reason: string | null;
}

interface Announcement {
  id: number;
  title: string;
  body: string;
  priority: string | null;
  createdAt: string;
}

interface DashboardProps {
  departmentId: number;
  employees: Employee[];
  orgNodes: OrgNode[];
}

const SHIFT_COLORS: Record<string, string> = {
  day: "#3B82F6",
  evening: "#F59E0B",
  night: "#8B5CF6",
  custom: "#10B981",
};

const SHIFT_ICONS: Record<string, React.ElementType> = {
  day: Sun,
  evening: Sunset,
  night: Moon,
  custom: Clock,
};

export default function Dashboard({ departmentId, employees, orgNodes }: DashboardProps) {
  const [todaySchedules, setTodaySchedules] = useState<Schedule[]>([]);
  const [timeOffRequests, setTimeOffRequests] = useState<TimeOffRequest[]>([]);
  const [announcements, setAnnouncements] = useState<Announcement[]>([]);
  const [loading, setLoading] = useState(true);

  const today = format(new Date(), "yyyy-MM-dd");

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const [schedRes, torRes, annRes] = await Promise.all([
          fetch(`/api/schedules?startDate=${today}&endDate=${today}`),
          fetch(`/api/time-off`),
          fetch(`/api/announcements?departmentId=${departmentId}`),
        ]);
        const [scheds, tors, anns] = await Promise.all([
          schedRes.json(),
          torRes.json(),
          annRes.json(),
        ]);
        setTodaySchedules(Array.isArray(scheds) ? scheds : []);
        setTimeOffRequests(Array.isArray(tors) ? tors.filter((r: TimeOffRequest) => r.status === "pending") : []);
        setAnnouncements(Array.isArray(anns) ? anns.slice(0, 5) : []);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [departmentId, today]);

  const activeEmployees = employees.filter((e) => !!e);
  const onShiftToday = todaySchedules.length;
  const offToday = activeEmployees.length - onShiftToday;

  // Group by shift type
  const byShift = todaySchedules.reduce<Record<string, Schedule[]>>((acc, s) => {
    const key = s.shiftType ?? "custom";
    acc[key] = [...(acc[key] ?? []), s];
    return acc;
  }, {});

  const handleApproveTimeOff = async (id: number) => {
    await fetch("/api/time-off", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status: "approved" }),
    });
    setTimeOffRequests((prev) => prev.filter((r) => r.id !== id));
  };

  const handleDenyTimeOff = async (id: number) => {
    await fetch("/api/time-off", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status: "denied" }),
    });
    setTimeOffRequests((prev) => prev.filter((r) => r.id !== id));
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <div className="animate-spin w-8 h-8 border-4 border-blue-500 border-t-transparent rounded-full" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Stats Row */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-3">
            <div className="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center">
              <Users size={20} className="text-blue-600" />
            </div>
            <TrendingUp size={16} className="text-green-500" />
          </div>
          <div className="text-3xl font-bold text-slate-800">{activeEmployees.length}</div>
          <div className="text-sm text-slate-500">Total Officers</div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-3">
            <div className="w-10 h-10 bg-green-100 rounded-xl flex items-center justify-center">
              <Shield size={20} className="text-green-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-slate-800">{onShiftToday}</div>
          <div className="text-sm text-slate-500">On Shift Today</div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-3">
            <div className="w-10 h-10 bg-amber-100 rounded-xl flex items-center justify-center">
              <Clock size={20} className="text-amber-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-slate-800">{timeOffRequests.length}</div>
          <div className="text-sm text-slate-500">Pending Time-Off</div>
        </div>

        <div className="bg-white rounded-2xl border border-slate-200 p-5">
          <div className="flex items-center justify-between mb-3">
            <div className="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center">
              <Calendar size={20} className="text-purple-600" />
            </div>
          </div>
          <div className="text-3xl font-bold text-slate-800">{orgNodes.length}</div>
          <div className="text-sm text-slate-500">Active Units</div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Today's Roster */}
        <div className="lg:col-span-2 bg-white rounded-2xl border border-slate-200 overflow-hidden">
          <div className="px-6 py-4 border-b border-slate-100 flex items-center justify-between">
            <h3 className="font-bold text-slate-800 flex items-center gap-2">
              <Shield size={18} className="text-blue-500" />
              Today&apos;s Roster — {format(new Date(), "EEEE, MMMM d")}
            </h3>
            <Badge color="#10B981" variant="subtle">{onShiftToday} on duty</Badge>
          </div>
          <div className="p-4">
            {Object.keys(byShift).length === 0 && (
              <div className="text-center py-10 text-slate-400">
                <Calendar size={40} className="mx-auto mb-3 opacity-30" />
                <p>No shifts scheduled today</p>
                <p className="text-sm mt-1">Use Auto-Generate in the Scheduler to create shifts</p>
              </div>
            )}
            {Object.entries(byShift).map(([type, shifts]) => {
              const Icon = SHIFT_ICONS[type] ?? Clock;
              const color = SHIFT_COLORS[type] ?? "#3B82F6";
              return (
                <div key={type} className="mb-5">
                  <div className="flex items-center gap-2 mb-3">
                    <div
                      className="flex items-center gap-1.5 px-3 py-1 rounded-full text-white text-xs font-semibold"
                      style={{ backgroundColor: color }}
                    >
                      <Icon size={12} />
                      {type.charAt(0).toUpperCase() + type.slice(1)} Shift
                    </div>
                    <span className="text-xs text-slate-400">{shifts[0].startTime} – {shifts[0].endTime}</span>
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                    {shifts.map((s) => {
                      const emp = employees.find((e) => e.id === s.employeeId);
                      if (!emp) return null;
                      const node = orgNodes.find((n) => n.id === s.orgNodeId);
                      return (
                        <div key={s.id} className="flex items-center gap-3 p-3 rounded-xl bg-slate-50">
                          <Avatar
                            firstName={emp.firstName}
                            lastName={emp.lastName}
                            color={emp.avatarColor ?? color}
                            size="sm"
                          />
                          <div className="flex-1 min-w-0">
                            <p className="text-sm font-semibold text-slate-800 truncate">
                              {emp.firstName} {emp.lastName}
                            </p>
                            <p className="text-xs text-slate-400 truncate">
                              {emp.rank} {node ? `• ${node.name}` : ""}
                            </p>
                          </div>
                          <span className="text-xs font-medium" style={{ color }}>
                            {formatTime(s.startTime)}
                          </span>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Right column */}
        <div className="space-y-6">
          {/* Announcements */}
          <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
            <div className="px-5 py-4 border-b border-slate-100 flex items-center gap-2">
              <Megaphone size={16} className="text-amber-500" />
              <h3 className="font-bold text-slate-800 text-sm">Announcements</h3>
            </div>
            <div className="p-4 space-y-3 max-h-64 overflow-y-auto">
              {announcements.length === 0 && (
                <p className="text-sm text-slate-400 text-center py-4">No active announcements</p>
              )}
              {announcements.map((ann) => (
                <div
                  key={ann.id}
                  className={`p-3 rounded-xl border ${
                    ann.priority === "high"
                      ? "bg-red-50 border-red-200"
                      : "bg-slate-50 border-slate-200"
                  }`}
                >
                  <div className="flex items-start gap-2">
                    {ann.priority === "high" ? (
                      <AlertCircle size={14} className="text-red-500 mt-0.5 flex-shrink-0" />
                    ) : (
                      <Bell size={14} className="text-slate-400 mt-0.5 flex-shrink-0" />
                    )}
                    <div>
                      <p className="text-sm font-semibold text-slate-800">{ann.title}</p>
                      <p className="text-xs text-slate-500 mt-0.5 line-clamp-2">{ann.body}</p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Pending Time-Off */}
          <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden">
            <div className="px-5 py-4 border-b border-slate-100 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <Clock size={16} className="text-purple-500" />
                <h3 className="font-bold text-slate-800 text-sm">Pending Requests</h3>
              </div>
              {timeOffRequests.length > 0 && (
                <Badge color="#8B5CF6">{timeOffRequests.length}</Badge>
              )}
            </div>
            <div className="p-4 space-y-3 max-h-64 overflow-y-auto">
              {timeOffRequests.length === 0 && (
                <div className="text-center py-4">
                  <CheckCircle size={24} className="mx-auto text-green-400 mb-2" />
                  <p className="text-sm text-slate-400">All requests reviewed</p>
                </div>
              )}
              {timeOffRequests.map((req) => {
                const emp = employees.find((e) => e.id === req.employeeId);
                return (
                  <div key={req.id} className="p-3 rounded-xl bg-slate-50 border border-slate-200">
                    <div className="flex items-center gap-2 mb-2">
                      {emp && (
                        <Avatar
                          firstName={emp.firstName}
                          lastName={emp.lastName}
                          color={emp.avatarColor ?? "#3B82F6"}
                          size="xs"
                        />
                      )}
                      <span className="text-sm font-semibold text-slate-800">
                        {emp ? `${emp.firstName} ${emp.lastName}` : "Unknown"}
                      </span>
                    </div>
                    <p className="text-xs text-slate-500 mb-2">
                      {req.type} • {req.startDate} – {req.endDate}
                    </p>
                    {req.reason && <p className="text-xs text-slate-400 mb-2 italic">&ldquo;{req.reason}&rdquo;</p>}
                    <div className="flex gap-2">
                      <button
                        onClick={() => handleApproveTimeOff(req.id)}
                        className="flex-1 py-1 text-xs bg-green-100 text-green-700 rounded-lg hover:bg-green-200 transition-colors font-medium"
                      >
                        Approve
                      </button>
                      <button
                        onClick={() => handleDenyTimeOff(req.id)}
                        className="flex-1 py-1 text-xs bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition-colors font-medium"
                      >
                        Deny
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
