"use client";

import { createPortal } from "react-dom";
import { useEffect, useState } from "react";
import instance from "@/src/utils/axios-instance";

interface TatItem {
  id: number;
  status: string;
  assignedBy: string;
  fromDateToDate:string;
  time: number;
}

interface TatModalProps {
  open: boolean;
  onClose: () => void;
  applicationId?: string | number;
}

export default function TatModal({ open, onClose, applicationId }: TatModalProps) {
  const [mounted, setMounted] = useState(false);
  const [tatData, setTatData] = useState<TatItem[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setMounted(true);
    if (open) document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "unset";
    };
  }, [open]);

  useEffect(() => {
    if (open && applicationId) {
      setLoading(true);
      
      // Fetch TAT data from Express backend using axios instance
      instance.get(`/admin/application/tat/${applicationId}`)
        .then(response => {
          if (response.data.success) {
            setTatData(response.data.tatData || []);
          } else {
            setTatData([]);
          }
          setLoading(false);
        })
        .catch(() => {
          setTatData([]);
          setLoading(false);
        });
    }
  }, [open, applicationId]);

  if (!open || !mounted) return null;

  const totalTatTime = tatData.reduce((acc, curr) => acc + curr.time, 0);

  return createPortal(
    <div className="fixed inset-0 z-[99999] flex items-center justify-center p-4">
      <div
        className="fixed inset-0 bg-black/50 backdrop-blur-sm"
        onClick={onClose}
      />

      <div className="relative bg-white rounded-2xl shadow-2xl max-w-2xl w-full overflow-hidden animate-in zoom-in duration-200">
        {/* Header */}
        <div className="p-5 border-b flex justify-between items-center bg-gray-50">
          <h3 className="text-lg font-bold text-gray-800">
            Turnaround Time (TAT)
          </h3>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-700"
          >
            ✕
          </button>
        </div>

        {/* Table */}
        <div className="p-6 overflow-x-auto">
          {loading ? (
            <div className="flex justify-center items-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-teal-600"></div>
            </div>
          ) : tatData.length === 0 ? (
            <div className="text-center py-8 text-gray-500">
              No TAT data available
            </div>
          ) : (
          <table className="w-full text-sm border-collapse">
  {/* Header */}
  <thead className="bg-gray-100 text-gray-700">
    <tr>
      <th className="px-4 py-3 border border-gray-300 text-center w-16 whitespace-nowrap">
        Sr No
      </th>
      <th className="px-4 py-3 border border-gray-300 text-left whitespace-nowrap">
        Status
      </th>
      <th className="px-4 py-3 border border-gray-300 text-center whitespace-nowrap">
        Assigned By
      </th>
      <th className="px-4 py-3 border border-gray-300 text-center whitespace-nowrap">
        From Date To Date
      </th>
      <th className="px-4 py-3 border border-gray-300 text-center whitespace-nowrap">
        TAT Time
      </th>
    </tr>
  </thead>

  {/* Body */}
  <tbody>
    {tatData.map((item, index) => (
      <tr key={item.id} className="hover:bg-gray-50 transition">
        <td className="px-4 py-3 border border-gray-300 text-center font-semibold">
          {index + 1}
        </td>

        <td className="px-4 py-3 border border-gray-300">
          {item.status}
        </td>

        <td className="px-4 py-3 border border-gray-300 text-center">
          {item.assignedBy}
        </td>

        <td className="px-4 py-3 border border-gray-300 text-center">
          {item.fromDateToDate}
        </td>

        <td className="px-4 py-3 border border-gray-300 text-center font-bold text-teal-600">
          {item.time} Hrs
        </td>
      </tr>
    ))}
  </tbody>

  {/* Footer */}
  <tfoot>
    <tr className="bg-teal-50">
      <td
        colSpan={4}
        className="px-4 py-3 border border-gray-300 font-bold text-right"
      >
        Total TAT
      </td>
      <td className="px-4 py-3 border border-gray-300 text-center font-extrabold text-teal-700">
        {totalTatTime} Hrs
      </td>
    </tr>
  </tfoot>
</table>
          )}
        </div>
      </div>
    </div>,
    document.body
  );
}
