"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { API_URL } from '@/lib/api';

interface DashboardStats {
  employees: number;
  customers: number;
  machines: number;
  totalServiceCalls: number;
  openServiceCalls: number;
  inProgressServiceCalls: number;
  closedServiceCalls: number;
}

export default function DashboardPage() {
  const [stats, setStats] = useState<DashboardStats>({
    employees: 0,
    customers: 0,
    machines: 0,
    totalServiceCalls: 0,
    openServiceCalls: 0,
    inProgressServiceCalls: 0,
    closedServiceCalls: 0,
  });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function loadStats() {
      try {
        const [empRes, custRes, machRes, scRes] = await Promise.all([
          fetch(`${API_URL}/api/employees`),
          fetch(`${API_URL}/api/customers`),
          fetch(`${API_URL}/api/machines`),
          fetch(`${API_URL}/api/service-calls`),
        ]);

        const [employees, customers, machines, serviceCalls] =
          await Promise.all([
            empRes.json(),
            custRes.json(),
            machRes.json(),
            scRes.json(),
          ]);

        setStats({
          employees: employees.length,
          customers: customers.length,
          machines: machines.length,
          totalServiceCalls: serviceCalls.length,
          openServiceCalls: serviceCalls.filter(
            (sc: { status: string }) => sc.status === "OPEN"
          ).length,
          inProgressServiceCalls: serviceCalls.filter(
            (sc: { status: string }) => sc.status === "IN_PROGRESS"
          ).length,
          closedServiceCalls: serviceCalls.filter(
            (sc: { status: string }) => sc.status === "CLOSED"
          ).length,
        });
      } catch (err) {
        console.error("Failed to load dashboard stats:", err);
      } finally {
        setLoading(false);
      }
    }

    loadStats();
  }, []);

  return (
    <DashboardLayout>
      {/* Header */}
      <div className="mb-8">
        <h2 className="text-3xl font-bold text-slate-900">Welcome back</h2>
        <p className="mt-2 text-slate-500">
          Monitor sales, service, employees, customers, and daily operations.
        </p>
      </div>

      {/* Top Stats */}
      <div className="mb-6 grid grid-cols-4 gap-6">
        <StatCard
          title="Employees"
          value={loading ? "—" : String(stats.employees)}
          sub="HR records"
          href="/employees"
          color="blue"
        />
        <StatCard
          title="Customers"
          value={loading ? "—" : String(stats.customers)}
          sub="Clinic database"
          href="/customers"
          color="blue"
        />
        <StatCard
          title="Machines"
          value={loading ? "—" : String(stats.machines)}
          sub="Installed units"
          href="/machines"
          color="blue"
        />
        <StatCard
          title="Total Service Calls"
          value={loading ? "—" : String(stats.totalServiceCalls)}
          sub="All tickets"
          href="/service-calls"
          color="blue"
        />
      </div>

      {/* Service Call Breakdown */}
      <div className="mb-10 grid grid-cols-3 gap-6">
        <StatCard
          title="Open Calls"
          value={loading ? "—" : String(stats.openServiceCalls)}
          sub="Awaiting action"
          href="/service-calls"
          color="yellow"
        />
        <StatCard
          title="In Progress"
          value={loading ? "—" : String(stats.inProgressServiceCalls)}
          sub="Engineer assigned"
          href="/service-calls"
          color="blue"
        />
        <StatCard
          title="Closed Calls"
          value={loading ? "—" : String(stats.closedServiceCalls)}
          sub="Resolved"
          href="/service-calls"
          color="green"
        />
      </div>

      {/* Quick Links */}
      <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <h3 className="mb-6 text-lg font-bold text-slate-900">Quick Actions</h3>
        <div className="grid grid-cols-4 gap-4">
          {[
            { label: "Add Service Call", href: "/service-calls", color: "bg-[#EE302B]" },
            { label: "Add Customer", href: "/customers", color: "bg-[#1296E8]" },
            { label: "Add Employee", href: "/employees", color: "bg-slate-700" },
            { label: "Add Machine", href: "/machines", color: "bg-slate-700" },
          ].map((action) => (
            <Link
              key={action.label}
              href={action.href}
              className={`${action.color} rounded-xl px-5 py-3 text-center text-sm font-semibold text-white transition hover:opacity-90`}
            >
              {action.label}
            </Link>
          ))}
        </div>
      </div>
    </DashboardLayout>
  );
}

function StatCard({
  title,
  value,
  sub,
  href,
  color,
}: {
  title: string;
  value: string;
  sub: string;
  href: string;
  color: "blue" | "yellow" | "green" | "red";
}) {
  const subColor =
    color === "yellow"
      ? "text-yellow-600"
      : color === "green"
      ? "text-green-600"
      : color === "red"
      ? "text-red-600"
      : "text-[#1296E8]";

  return (
    <Link href={href} className="block">
      <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm transition hover:border-[#1296E8] hover:shadow-md">
        <p className="text-sm font-medium text-slate-500">{title}</p>
        <p className="mt-3 text-4xl font-bold text-slate-900">{value}</p>
        <p className={`mt-2 text-sm font-medium ${subColor}`}>{sub}</p>
      </div>
    </Link>
  );
}