"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;
  doctorName: string;
  phone: string;
  email: string;
  address: string;
  city: string;
  emirate: string;
  clinicType: string;
  notes: string;
  active: boolean;
}

interface Machine {
  id: number;
  machineCode: string;
  manufacturer: string;
  model: string;
  serialNumber: string;
  status: string;
  warrantyExpiryDate: string;
  amcExpiryDate: string;
}

interface ServiceCall {
  id: number;
  serviceCallCode: string;
  issueTitle: string;
  priority: string;
  status: string;
  scheduledDate: string;
  machine: { manufacturer: string; model: string };
}

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

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

  const [customer, setCustomer] = useState<Customer | null>(null);
  const [machines, setMachines] = useState<Machine[]>([]);
  const [serviceCalls, setServiceCalls] = useState<ServiceCall[]>([]);
  const [activeTab, setActiveTab] = useState("Overview");
  const [documentCount, setDocumentCount] = useState(0);

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

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

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

    fetch(`${API_URL}/api/documents/CUSTOMER/${id}`)
      .then((res) => res.json())
      .then((data) => setDocumentCount(data.length))
      .catch((err) => console.error(err));
  }, [id]);

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

  const initials = customer.clinicName
    .split(" ")
    .map((word) => word[0])
    .join("")
    .substring(0, 2)
    .toUpperCase();

  const today = new Date();
  const openCalls = serviceCalls.filter(
    (call) => call.status === "OPEN" || call.status === "IN_PROGRESS"
  ).length;
  const activeAmcs = machines.filter(
    (machine) =>
      machine.amcExpiryDate && new Date(machine.amcExpiryDate) >= today
  ).length;

  return (
    <DashboardLayout>
      <div className="mb-6 text-sm text-slate-500">
        Customers /{" "}
        <span className="font-semibold text-[#1296E8]">
          {customer.customerCode}
        </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 className="flex items-center gap-6">
            <div className="flex h-24 w-24 items-center justify-center rounded-full bg-blue-50 text-4xl font-bold text-[#1296E8]">
              {initials}
            </div>

            <div>
              <p className="text-sm font-semibold text-[#1296E8]">
                {customer.customerCode}
              </p>

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

              <p className="mt-2 text-slate-500">
                {customer.doctorName || "No contact"} •{" "}
                {customer.emirate || "-"}
              </p>
            </div>
          </div>

          <span
            className={`rounded-full px-4 py-2 text-sm font-semibold ${
              customer.active
                ? "bg-green-100 text-green-700"
                : "bg-slate-100 text-slate-600"
            }`}
          >
            {customer.active ? "ACTIVE" : "INACTIVE"}
          </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-4 gap-4">
          <StatCard title="Machines" value={String(machines.length)} />
          <StatCard title="Open Calls" value={String(openCalls)} />
          <StatCard title="Active AMCs" value={String(activeAmcs)} />
          <StatCard title="Documents" value={String(documentCount)} />
        </div>
      </div>

      {activeTab === "Overview" && (
        <>
          <div className="grid grid-cols-3 gap-6">
            <Card title="Contact Details">
              <Info label="Doctor / Contact" value={customer.doctorName} />
              <Info label="Phone" value={customer.phone} />
              <Info label="Email" value={customer.email} />
            </Card>

            <Card title="Location Details">
              <Info label="Address" value={customer.address} />
              <Info label="City" value={customer.city} />
              <Info label="Emirate" value={customer.emirate} />
            </Card>

            <Card title="Business Details">
              <Info label="Customer Type" value={customer.clinicType} />
            </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">
              {customer.notes || "No notes added."}
            </p>
          </div>
        </>
      )}

      {activeTab === "Machines" && (
        <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">Manufacturer / Model</th>
                <th className="px-5 py-4 text-left">Serial No.</th>
                <th className="px-5 py-4 text-left">Status</th>
                <th className="px-5 py-4 text-left">Warranty Expiry</th>
                <th className="px-5 py-4 text-left">AMC Expiry</th>
              </tr>
            </thead>
            <tbody>
              {machines.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-5 py-16 text-center text-slate-500">
                    No machines registered for this customer.
                  </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">
                      <Link
                        href={`/machines/${machine.id}`}
                        className="font-semibold text-[#1296E8]"
                      >
                        {machine.machineCode}
                      </Link>
                    </td>
                    <td className="px-5 py-4">
                      {machine.manufacturer} {machine.model}
                    </td>
                    <td className="px-5 py-4">{machine.serialNumber || "-"}</td>
                    <td className="px-5 py-4">
                      <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">
                        {machine.status || "-"}
                      </span>
                    </td>
                    <td className="px-5 py-4">{machine.warrantyExpiryDate || "-"}</td>
                    <td className="px-5 py-4">{machine.amcExpiryDate || "-"}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </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">Machine</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>
              </tr>
            </thead>
            <tbody>
              {serviceCalls.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-5 py-16 text-center text-slate-500">
                    No service calls for this customer.
                  </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">
                      {call.machine
                        ? `${call.machine.manufacturer} ${call.machine.model}`
                        : "-"}
                    </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>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      )}

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

      {activeTab === "Activity" && (
        <div className="rounded-2xl border border-slate-200 bg-white p-8 shadow-sm">
          <ActivityTimeline entityType="CUSTOMER" 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>
  );
}

function StatCard({ title, value }: { title: string; value: string }) {
  return (
    <div className="rounded-xl border border-slate-200 bg-slate-50 p-4">
      <p className="text-sm text-slate-500">{title}</p>
      <p className="mt-2 text-3xl font-bold text-slate-900">{value}</p>
    </div>
  );
}