"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import DashboardLayout from "@/components/layout/DashboardLayout";
import ActivityTimeline from "@/components/activity/ActivityTimeline";
import DocumentsTab from "@/components/documents/DocumentsTab";
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;
  assignedEngineer: Employee;
  manufacturer: string;
  model: string;
  serialNumber: string;
  installationDate: string;
  warrantyExpiryDate: string;
  amcExpiryDate: string;
  status: string;
  notes: string;
}

interface ServiceCall {
  id: number;
  serviceCallCode: string;
  issueTitle: string;
  priority: string;
  status: string;
  scheduledDate: string;
  closedDate: string;
}

const TABS = ["Overview", "Service Calls", "Documents", "Activity"];

function getCoverageStatus(expiryDate?: string) {
  if (!expiryDate) {
    return { label: "NOT SET", className: "bg-slate-100 text-slate-600" };
  }

  const daysLeft = Math.ceil(
    (new Date(expiryDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24)
  );

  if (daysLeft < 0) {
    return { label: "EXPIRED", className: "bg-red-100 text-red-700" };
  }

  if (daysLeft <= 30) {
    return {
      label: `EXPIRING IN ${daysLeft}D`,
      className: "bg-orange-100 text-orange-700",
    };
  }

  return { label: "ACTIVE", className: "bg-green-100 text-green-700" };
}

export default function MachineProfilePage() {
  const params = useParams();
  const id = params.id;

  const [machine, setMachine] = useState<Machine | null>(null);
  const [serviceCalls, setServiceCalls] = useState<ServiceCall[]>([]);
  const [activeTab, setActiveTab] = useState("Overview");

  useEffect(() => {
    fetch(`${API_URL}/api/machines/${id}`)
      .then((res) => res.json())
      .then((data) => setMachine(data))
      .catch((err) => console.error(err));

    fetch(`${API_URL}/api/service-calls/machine/${id}`)
      .then((res) => res.json())
      .then((data) => setServiceCalls(data))
      .catch((err) => console.error(err));
  }, [id]);

  if (!machine) {
    return (
      <DashboardLayout>
        <p className="text-slate-500">Loading machine profile...</p>
      </DashboardLayout>
    );
  }

  const warrantyStatus = getCoverageStatus(machine.warrantyExpiryDate);
  const amcStatus = getCoverageStatus(machine.amcExpiryDate);

  return (
    <DashboardLayout>
      <div className="mb-6 text-sm text-slate-500">
        Machines /{" "}
        <span className="font-semibold text-[#1296E8]">
          {machine.machineCode}
        </span>
      </div>

      <div className="mb-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
        <div className="flex items-start justify-between">
          <div>
            <p className="text-sm font-semibold text-[#1296E8]">
              {machine.machineCode}
            </p>

            <h1 className="mt-1 text-4xl font-bold text-slate-900">
              {machine.manufacturer} {machine.model}
            </h1>

            <p className="mt-2 text-slate-500">
              Serial: {machine.serialNumber || "-"} •{" "}
              {machine.customer?.clinicName || "-"}
            </p>
          </div>

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

        <div className="mt-8 flex flex-wrap gap-3">
          {TABS.map((tab) => (
            <button
              key={tab}
              onClick={() => setActiveTab(tab)}
              className={`rounded-xl border px-5 py-3 text-sm font-semibold transition ${
                activeTab === tab
                  ? "border-[#1296E8] bg-[#1296E8]/5 text-[#1296E8]"
                  : "border-slate-200 text-slate-700 hover:border-[#1296E8] hover:text-[#1296E8]"
              }`}
            >
              {tab}
            </button>
          ))}
        </div>

        <div className="mt-8 grid grid-cols-2 gap-4">
          <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
            <p className="text-sm text-slate-500">Warranty Status</p>
            <p className="mt-1 text-sm text-slate-700">
              Expiry: {machine.warrantyExpiryDate || "-"}
            </p>
            <span
              className={`mt-2 inline-block rounded-full px-3 py-1 text-xs font-semibold ${warrantyStatus.className}`}
            >
              {warrantyStatus.label}
            </span>
          </div>

          <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
            <p className="text-sm text-slate-500">AMC Status</p>
            <p className="mt-1 text-sm text-slate-700">
              Expiry: {machine.amcExpiryDate || "-"}
            </p>
            <span
              className={`mt-2 inline-block rounded-full px-3 py-1 text-xs font-semibold ${amcStatus.className}`}
            >
              {amcStatus.label}
            </span>
          </div>
        </div>
      </div>

      {activeTab === "Overview" && (
        <>
          <div className="grid grid-cols-3 gap-6">
            <Card title="Machine Details">
              <Info label="Manufacturer" value={machine.manufacturer} />
              <Info label="Model" value={machine.model} />
              <Info label="Serial Number" value={machine.serialNumber} />
            </Card>

            <Card title="Dates & Coverage">
              <Info label="Installation Date" value={machine.installationDate} />
              <Info label="Warranty Expiry" value={machine.warrantyExpiryDate} />
              <Info label="AMC Expiry" value={machine.amcExpiryDate} />
            </Card>

            <Card title="Assignment">
              <Info label="Customer" value={machine.customer?.clinicName} />
              <Info
                label="Assigned Engineer"
                value={machine.assignedEngineer?.fullName}
              />
            </Card>
          </div>

          <div className="mt-8 rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
            <h3 className="mb-3 text-lg font-bold">Notes</h3>
            <p className="text-slate-600">{machine.notes || "No notes added."}</p>
          </div>
        </>
      )}

      {activeTab === "Service Calls" && (
        <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">Issue</th>
                <th className="px-5 py-4 text-left">Priority</th>
                <th className="px-5 py-4 text-left">Status</th>
                <th className="px-5 py-4 text-left">Scheduled</th>
                <th className="px-5 py-4 text-left">Closed</th>
              </tr>
            </thead>
            <tbody>
              {serviceCalls.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-5 py-16 text-center text-slate-500">
                    No service history for this machine.
                  </td>
                </tr>
              ) : (
                serviceCalls.map((call) => (
                  <tr
                    key={call.id}
                    className="border-t border-slate-100 hover:bg-slate-50/50"
                  >
                    <td className="px-5 py-4">
                      <Link
                        href={`/service-calls/${call.id}`}
                        className="font-semibold text-[#1296E8]"
                      >
                        {call.serviceCallCode}
                      </Link>
                    </td>
                    <td className="px-5 py-4">{call.issueTitle}</td>
                    <td className="px-5 py-4">
                      <span
                        className={`rounded-full px-3 py-1 text-xs font-semibold ${
                          call.priority === "CRITICAL"
                            ? "bg-red-100 text-red-700"
                            : call.priority === "HIGH"
                            ? "bg-orange-100 text-orange-700"
                            : call.priority === "LOW"
                            ? "bg-slate-100 text-slate-600"
                            : "bg-blue-100 text-blue-700"
                        }`}
                      >
                        {call.priority}
                      </span>
                    </td>
                    <td className="px-5 py-4">
                      <span
                        className={`rounded-full px-3 py-1 text-xs font-semibold ${
                          call.status === "OPEN"
                            ? "bg-yellow-100 text-yellow-700"
                            : call.status === "IN_PROGRESS"
                            ? "bg-blue-100 text-blue-700"
                            : call.status === "CLOSED"
                            ? "bg-green-100 text-green-700"
                            : "bg-slate-100 text-slate-600"
                        }`}
                      >
                        {call.status}
                      </span>
                    </td>
                    <td className="px-5 py-4">{call.scheduledDate || "-"}</td>
                    <td className="px-5 py-4">{call.closedDate || "-"}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}

      {activeTab === "Documents" && (
        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <DocumentsTab entityType="MACHINE" entityId={Number(id)} />
        </div>
      )}

      {activeTab === "Activity" && (
        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <ActivityTimeline entityType="MACHINE" entityId={Number(id)} />
        </div>
      )}
    </DashboardLayout>
  );
}

function Card({
  title,
  children,
}: {
  title: string;
  children: React.ReactNode;
}) {
  return (
    <div className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
      <h3 className="mb-5 text-lg font-bold">{title}</h3>
      {children}
    </div>
  );
}

function Info({ label, value }: { label: string; value?: string }) {
  return (
    <div className="mb-4">
      <p className="text-xs font-semibold uppercase tracking-wide text-slate-400">
        {label}
      </p>
      <p className="mt-1 font-medium text-slate-900">{value || "-"}</p>
    </div>
  );
}