"use client";

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

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

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

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

interface ServiceCall {
  id: number;
  serviceCallCode: string;
  serviceType: string;
  customer: Customer;
  machine: Machine;
  issueTitle: string;
  priority: string;
  status: string;
  assignedEngineer: Employee;
  scheduledDate: string;
}

export default function ServiceCallsPage() {
  const [serviceCalls, setServiceCalls] = useState<ServiceCall[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [statusFilter, setStatusFilter] = useState("ALL");
  const [priorityFilter, setPriorityFilter] = useState("ALL");
  const [typeFilter, setTypeFilter] = useState("ALL");
  const [search, setSearch] = useState("");
  const [todayOnly, setTodayOnly] = useState(false);
  const [selectedIds, setSelectedIds] = useState<number[]>([]);
  const [bulkUpdating, setBulkUpdating] = useState(false);

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

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

  const openCalls = serviceCalls.filter((call) => call.status === "OPEN").length;
  const inProgressCalls = serviceCalls.filter(
    (call) => call.status === "IN_PROGRESS"
  ).length;
  const closedCalls = serviceCalls.filter(
    (call) => call.status === "CLOSED"
  ).length;

  function formatDate(date?: string) {
    if (!date) return "-";

    return new Date(date).toLocaleDateString("en-GB", {
      day: "2-digit",
      month: "short",
      year: "numeric",
    });
  }

  const todayStr = new Date().toISOString().slice(0, 10);

  const filteredCalls = serviceCalls.filter((call) => {
    if (statusFilter !== "ALL" && call.status !== statusFilter) return false;
    if (priorityFilter !== "ALL" && call.priority !== priorityFilter) return false;
    if (typeFilter !== "ALL" && call.serviceType !== typeFilter) return false;
    if (todayOnly && call.scheduledDate !== todayStr) return false;

    if (search.trim()) {
      const term = search.toLowerCase();
      const haystack = [
        call.serviceCallCode,
        call.issueTitle,
        call.customer?.clinicName,
        call.machine?.machineCode,
        call.assignedEngineer?.fullName,
      ]
        .filter(Boolean)
        .join(" ")
        .toLowerCase();

      if (!haystack.includes(term)) return false;
    }

    return true;
  });

  function toggleSelected(id: number) {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((sid) => sid !== id) : [...prev, id]
    );
  }

  function toggleSelectAll() {
    if (selectedIds.length === filteredCalls.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(filteredCalls.map((call) => call.id));
    }
  }

  async function bulkUpdateStatus(status: string) {
    if (selectedIds.length === 0) return;

    setBulkUpdating(true);
    try {
      await Promise.all(
        selectedIds.map((id) =>
          fetch(`${API_URL}/api/service-calls/${id}/status`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ status }),
          })
        )
      );
      setSelectedIds([]);
      loadServiceCalls();
    } finally {
      setBulkUpdating(false);
    }
  }

  return (
    <DashboardLayout>
      {showModal && (
        <AddServiceCallModal
          onClose={() => setShowModal(false)}
          onServiceCallAdded={loadServiceCalls}
        />
      )}

      <div className="mb-8 flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold">Service Calls</h2>
          <p className="mt-1 text-slate-500">
            Track customer complaints, machine issues, engineer assignments, and
            service reports
          </p>
        </div>

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

      <div className="mb-8 grid grid-cols-4 gap-6">
        <StatCard title="Total Calls" value={String(serviceCalls.length)} />
        <StatCard title="Open Calls" value={String(openCalls)} />
        <StatCard title="In Progress" value={String(inProgressCalls)} />
        <StatCard title="Closed Calls" value={String(closedCalls)} />
      </div>

      <div className="mb-5 flex flex-wrap items-center gap-3">
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search by code, issue, customer, machine, engineer..."
          className="min-w-[280px] flex-1 rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
        />

        <select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
        >
          {["ALL", "OPEN", "IN_PROGRESS", "COMPLETED", "CLOSED"].map((s) => (
            <option key={s} value={s}>
              {s === "ALL" ? "All Statuses" : s}
            </option>
          ))}
        </select>

        <select
          value={priorityFilter}
          onChange={(e) => setPriorityFilter(e.target.value)}
          className="rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
        >
          {["ALL", "LOW", "NORMAL", "HIGH", "CRITICAL"].map((p) => (
            <option key={p} value={p}>
              {p === "ALL" ? "All Priorities" : p}
            </option>
          ))}
        </select>

        <select
          value={typeFilter}
          onChange={(e) => setTypeFilter(e.target.value)}
          className="rounded-xl border border-slate-200 px-4 py-3 text-sm outline-none focus:ring-2 focus:ring-[#1296E8]"
        >
          {[
            { key: "ALL", label: "All Types" },
            { key: "FIELD_SERVICE", label: "Field Service" },
            { key: "WORKSHOP_SERVICE", label: "Workshop Service" },
            { key: "DEMONSTRATION", label: "Demonstration" },
          ].map((t) => (
            <option key={t.key} value={t.key}>
              {t.label}
            </option>
          ))}
        </select>

        <button
          onClick={() => setTodayOnly((prev) => !prev)}
          className={`rounded-xl border px-4 py-3 text-sm font-semibold transition ${
            todayOnly
              ? "border-[#1296E8] bg-[#1296E8]/5 text-[#1296E8]"
              : "border-slate-200 text-slate-700 hover:border-[#1296E8] hover:text-[#1296E8]"
          }`}
        >
          Today&apos;s Queue
        </button>
      </div>

      {selectedIds.length > 0 && (
        <div className="mb-5 flex items-center justify-between rounded-xl border border-[#1296E8]/30 bg-[#1296E8]/5 px-5 py-3">
          <span className="text-sm font-semibold text-[#1296E8]">
            {selectedIds.length} selected
          </span>
          <div className="flex gap-2">
            <button
              disabled={bulkUpdating}
              onClick={() => bulkUpdateStatus("IN_PROGRESS")}
              className="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:opacity-50"
            >
              Mark In Progress
            </button>
            <button
              disabled={bulkUpdating}
              onClick={() => bulkUpdateStatus("COMPLETED")}
              className="rounded-lg border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 disabled:opacity-50"
            >
              Mark Completed
            </button>
            <button
              disabled={bulkUpdating}
              onClick={() => bulkUpdateStatus("CLOSED")}
              className="rounded-lg bg-[#EE302B] px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
            >
              Close Calls
            </button>
          </div>
        </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">
                <input
                  type="checkbox"
                  checked={
                    filteredCalls.length > 0 &&
                    selectedIds.length === filteredCalls.length
                  }
                  onChange={toggleSelectAll}
                />
              </th>
              <th className="px-5 py-4 text-left">Code</th>
              <th className="px-5 py-4 text-left">Type</th>
              <th className="px-5 py-4 text-left">Issue</th>
              <th className="px-5 py-4 text-left">Customer</th>
              <th className="px-5 py-4 text-left">Machine</th>
              <th className="px-5 py-4 text-left">Engineer</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>
            {filteredCalls.length === 0 ? (
              <tr>
                <td
                  colSpan={10}
                  className="px-5 py-16 text-center text-slate-500"
                >
                  No service calls found.
                </td>
              </tr>
            ) : (
              filteredCalls.map((call) => (
                <tr
                  key={call.id}
                  className="border-t border-slate-100 hover:bg-slate-50/50"
                >
                  <td className="px-5 py-4">
                    <input
                      type="checkbox"
                      checked={selectedIds.includes(call.id)}
                      onChange={() => toggleSelected(call.id)}
                    />
                  </td>

                  <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">
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-semibold whitespace-nowrap ${
                        call.serviceType === "WORKSHOP_SERVICE"
                          ? "bg-indigo-100 text-indigo-700"
                          : call.serviceType === "DEMONSTRATION"
                          ? "bg-teal-100 text-teal-700"
                          : "bg-[#1296E8]/10 text-[#1296E8]"
                      }`}
                    >
                      {call.serviceType === "WORKSHOP_SERVICE"
                        ? "Workshop"
                        : call.serviceType === "DEMONSTRATION"
                        ? "Demo"
                        : "Field"}
                    </span>
                  </td>

                  <td className="px-5 py-4">
                    <div className="font-medium text-slate-900">
                      {call.issueTitle}
                    </div>
                    <div className="text-xs text-slate-500">
                      Service request
                    </div>
                  </td>

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

                  <td className="px-5 py-4">
                    <div className="whitespace-nowrap font-medium text-slate-900">
                      {call.machine
                        ? `${call.machine.manufacturer} ${call.machine.model}`
                        : "-"}
                    </div>
                    <div className="text-xs text-slate-500">
                      {call.machine?.machineCode || "-"}
                    </div>
                  </td>

                  <td className="px-5 py-4">
                    <div className="font-medium text-slate-900">
                      {call.assignedEngineer?.fullName || "-"}
                    </div>
                    <div className="text-xs text-slate-500">
                      {call.assignedEngineer?.employeeCode || "-"}
                    </div>
                  </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 whitespace-nowrap">
                    {formatDate(call.scheduledDate)}
                  </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>
  );
}