"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 RepairApproval {
  id: number;
  estimatedCost: number;
  reason: string;
  status: string;
  requestedAt: string;
  serviceCall: { id: number; serviceCallCode: string; issueTitle: string };
  requestedBy: { fullName: string };
}

export default function ApprovalsPage() {
  const [approvals, setApprovals] = useState<RepairApproval[]>([]);
  const [statusFilter, setStatusFilter] = useState("ALL");

  function loadApprovals() {
    const url =
      statusFilter === "ALL"
        ? `${API_URL}/api/approvals`
        : `${API_URL}/api/approvals?status=${statusFilter}`;

    fetch(url)
      .then((res) => res.json())
      .then((data) => setApprovals(data))
      .catch((err) => console.error(err));
  }

  useEffect(() => {
    loadApprovals();
  }, [statusFilter]);

  async function decide(id: number, status: string) {
    await fetch(`${API_URL}/api/approvals/${id}/decision`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    loadApprovals();
  }

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

  const pendingCount = approvals.filter((a) => a.status === "PENDING").length;

  return (
    <DashboardLayout>
      <div className="mb-8 flex items-center justify-between">
        <div>
          <h2 className="text-3xl font-bold">Out-of-Warranty Repair Approvals</h2>
          <p className="mt-1 text-slate-500">
            Review and decide on repairs requested for machines without active
            warranty/AMC coverage
          </p>
        </div>

        <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", "PENDING", "APPROVED", "REJECTED"].map((s) => (
            <option key={s} value={s}>
              {s === "ALL" ? "All Statuses" : s}
            </option>
          ))}
        </select>
      </div>

      {statusFilter === "ALL" && pendingCount > 0 && (
        <div className="mb-6 rounded-xl border border-yellow-200 bg-yellow-50 px-5 py-3 text-sm font-semibold text-yellow-800">
          {pendingCount} approval{pendingCount > 1 ? "s" : ""} awaiting decision
        </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">Service Call</th>
              <th className="px-5 py-4 text-left">Requested By</th>
              <th className="px-5 py-4 text-left">Estimated Cost</th>
              <th className="px-5 py-4 text-left">Status</th>
              <th className="px-5 py-4 text-left">Requested</th>
              <th className="px-5 py-4 text-left">Decision</th>
            </tr>
          </thead>
          <tbody>
            {approvals.length === 0 ? (
              <tr>
                <td colSpan={6} className="px-5 py-16 text-center text-slate-500">
                  No approval requests found.
                </td>
              </tr>
            ) : (
              approvals.map((approval) => (
                <tr key={approval.id} className="border-t border-slate-100 hover:bg-slate-50/50">
                  <td className="px-5 py-4">
                    <Link
                      href={`/service-calls/${approval.serviceCall?.id}`}
                      className="font-semibold text-[#1296E8]"
                    >
                      {approval.serviceCall?.serviceCallCode}
                    </Link>
                    <div className="text-xs text-slate-500">
                      {approval.serviceCall?.issueTitle}
                    </div>
                  </td>
                  <td className="px-5 py-4 text-sm">
                    {approval.requestedBy?.fullName || "-"}
                  </td>
                  <td className="px-5 py-4 text-sm">
                    {approval.estimatedCost != null ? `AED ${approval.estimatedCost}` : "-"}
                  </td>
                  <td className="px-5 py-4">
                    <span
                      className={`rounded-full px-3 py-1 text-xs font-semibold ${
                        approval.status === "APPROVED"
                          ? "bg-green-100 text-green-700"
                          : approval.status === "REJECTED"
                          ? "bg-red-100 text-red-700"
                          : "bg-yellow-100 text-yellow-700"
                      }`}
                    >
                      {approval.status}
                    </span>
                  </td>
                  <td className="px-5 py-4 text-sm">{formatDate(approval.requestedAt)}</td>
                  <td className="px-5 py-4">
                    {approval.status === "PENDING" ? (
                      <div className="flex gap-2">
                        <button
                          onClick={() => decide(approval.id, "APPROVED")}
                          className="rounded-lg bg-green-600 px-3 py-1.5 text-xs font-semibold text-white"
                        >
                          Approve
                        </button>
                        <button
                          onClick={() => decide(approval.id, "REJECTED")}
                          className="rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-semibold text-slate-700"
                        >
                          Reject
                        </button>
                      </div>
                    ) : (
                      <span className="text-xs text-slate-400">-</span>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </DashboardLayout>
  );
}
