"use client";

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

interface Customer {
  id: number;
  customerCode: string;
  clinicName: string;
}

interface Employee {
  id: number;
  employeeCode: string;
  fullName: string;
}

interface Machine {
  id: number;
  machineCode: string;
  customer: Customer;
  manufacturer: string;
  model: string;
  serialNumber: string;
  installationDate: string;
  warrantyExpiryDate: string;
  amcExpiryDate: string;
  status: string;
  assignedEngineer: Employee;
}

export default function MachinesPage() {
  const [machines, setMachines] = useState<Machine[]>([]);
  const [showModal, setShowModal] = useState(false);

  function loadMachines() {
    fetch(`${API_URL}/api/machines`)
      .then((res) => res.json())
      .then((data) => setMachines(data))
      .catch((err) => console.error(err));
  }

  useEffect(() => {
    loadMachines();
  }, []);

  return (
    <DashboardLayout>
      {showModal && (
        <AddMachineModal
          onClose={() => setShowModal(false)}
          onMachineAdded={loadMachines}
        />
      )}

      <div className="mb-8 flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold">Machines</h2>
          <p className="mt-1 text-slate-500">
            Manage installed equipment, warranties, AMCs, and service records
          </p>
        </div>

        <button
          onClick={() => setShowModal(true)}
          className="rounded-xl bg-[#EE302B] px-5 py-3 font-semibold text-white"
        >
          Add Machine
        </button>
      </div>

      <div className="mb-8 grid grid-cols-4 gap-6">
        <StatCard title="Total Machines" value={String(machines.length)} />
        <StatCard title="Warranty Expiring" value="0" />
        <StatCard title="AMC Expiring" value="0" />
        <StatCard title="Open Service Calls" value="0" />
      </div>

      <div className="overflow-hidden rounded-2xl border border-slate-200 bg-white">
        <table className="w-full">
          <thead className="bg-slate-50">
            <tr>
              <th className="px-5 py-4 text-left">Code</th>
              <th className="px-5 py-4 text-left">Customer</th>
              <th className="px-5 py-4 text-left">Manufacturer</th>
              <th className="px-5 py-4 text-left">Model</th>
              <th className="px-5 py-4 text-left">Serial</th>
              <th className="px-5 py-4 text-left">Engineer</th>
              <th className="px-5 py-4 text-left">Status</th>
              <th className="px-5 py-4 text-left">Actions</th>
            </tr>
          </thead>

          <tbody>
            {machines.length === 0 ? (
              <tr>
                <td
                  colSpan={8}
                  className="px-5 py-16 text-center text-slate-500"
                >
                  No machines found.
                </td>
              </tr>
            ) : (
              machines.map((machine) => (
                <tr
                  key={machine.id}
                  className="border-t border-slate-100 hover:bg-slate-50/50"
                >
                  <td className="px-5 py-4 font-semibold text-[#1296E8]">
                    {machine.machineCode}
                  </td>

                  <td className="px-5 py-4">
                    <div className="font-medium text-slate-900">
                      {machine.customer?.clinicName || "-"}
                    </div>

                    <div className="text-xs text-slate-500">
                      {machine.customer?.customerCode || "-"}
                    </div>
                  </td>

                  <td className="px-5 py-4">
                    <span className="rounded-full bg-blue-100 px-3 py-1 text-xs font-semibold text-blue-700">
                      {machine.manufacturer || "-"}
                    </span>
                  </td>

                  <td className="px-5 py-4 font-medium whitespace-nowrap">
                    {machine.model || "-"}
                  </td>

                  <td className="px-5 py-4">
                    {machine.serialNumber || "-"}
                  </td>

                  <td className="px-5 py-4">
                    <div className="font-medium text-slate-900">
                      {machine.assignedEngineer?.fullName || "-"}
                    </div>

                    <div className="text-xs text-slate-500">
                      {machine.assignedEngineer?.employeeCode || "-"}
                    </div>
                  </td>

                  <td className="px-5 py-4">
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-semibold ${
                        machine.status === "ACTIVE"
                          ? "bg-green-100 text-green-700"
                          : "bg-slate-100 text-slate-600"
                      }`}
                    >
                      {machine.status || "UNKNOWN"}
                    </span>
                  </td>

                  <td className="px-5 py-4">
                    <Link
                      href={`/machines/${machine.id}`}
                      className="rounded-lg border border-[#1296E8]/20 bg-[#1296E8]/5 px-4 py-2 text-sm font-semibold text-[#1296E8] transition hover:bg-[#1296E8]/10"
                    >
                      View
                    </Link>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </DashboardLayout>
  );
}

function StatCard({
  title,
  value,
}: {
  title: string;
  value: string;
}) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <p className="text-sm font-medium text-slate-500">
        {title}
      </p>

      <p className="mt-3 text-4xl font-bold text-slate-900">
        {value}
      </p>
    </div>
  );
}