import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { api } from '@/lib/api';
import Swal from 'sweetalert2';
import Input from './Input';
import Pagination from './Pagination';
import { useAuth } from '@/lib/auth';
import { Search } from 'lucide-react';

enum CylinderStatus {
  NEW = 'NEW',
  INSIDE = 'INSIDE',
  OUTSIDE = 'OUTSIDE',
}

interface ClaimedCylinder {
  id: string;
  item_id: string;
  rfid?: string;
  manufacturerName?: string;
  status: CylinderStatus;
  claimedById?: string;
  claimedBy?: {
    name: string;
    email: string;
  };
  createdAt: string;
  updatedAt: string;
}

const ClaimedCylindersTable: React.FC = () => {
  const { isAdmin, user } = useAuth();
  const [claimedCylinders, setClaimedCylinders] = useState<ClaimedCylinder[]>([]);
  const [loading, setLoading] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalItems, setTotalItems] = useState(0);
  const itemsPerPage = 10;

  useEffect(() => {
    const handler = setTimeout(() => {
      setSearchTerm(inputValue);
      setCurrentPage(1);
    }, 500);
    return () => clearTimeout(handler);
  }, [inputValue]);


  const fetchClaimedCylinders = async () => {
    setLoading(true);
    try {
      const params: any = {
        page: currentPage,
        perPage: itemsPerPage,
      };

      if (searchTerm) params.search = searchTerm;

      const response = await api.getListPaginated<any>('/cylinders/getclaims', params);
      setClaimedCylinders(response.data?.items || []);
      setTotalItems(response?.data?.pagination?.total || 0);


    } catch (error: any) {
      // Swal.fire({
      //   title: 'Error',
      //   text: error.message || 'Failed to fetch claimed cylinders',
      //   icon: 'error',
      // });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchClaimedCylinders();
  }, [currentPage, searchTerm, isAdmin, user]);


  const totalPages = Math.ceil(totalItems / itemsPerPage);

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  return (
    <div className="bg-white p-6 rounded-xl shadow-2xl">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xl font-semibold text-gray-800">Claimed Cylinders</h2>
        <p className="text-sm text-gray-500">
          {totalItems} record{totalItems !== 1 ? 's' : ''} found
        </p>
      </div>

      {/* SEARCH */}
      <div className="flex flex-col sm:flex-row items-center justify-between mb-6 gap-4">
        <div className="relative w-full">
          <Search className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
          <input
            type="text"
            placeholder="Search by RFID Tag or Serial Number..."
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            className="appearance-none w-full pl-12 pr-6 py-3 border border-gray-200 rounded-xl shadow-inner bg-white
                       focus:outline-none focus:ring-2 focus:ring-[#dd3a3f]/40 focus:border-[#dd3a3f] cursor-pointer transition duration-150 text-gray-800 font-medium"
          />
        </div>
      </div>

      {/* ---------- DESKTOP TABLE ---------- */}
      <div className="hidden md:block overflow-x-auto border border-gray-200 rounded-xl">
        <table className="min-w-full divide-y divide-gray-200">
          <thead className="bg-gray-50 sticky top-0 z-10">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-bold text-gray-600 uppercase tracking-wider">Sr No</th>
              <th className="px-6 py-3 text-left text-xs font-bold text-gray-600 uppercase tracking-wider">RFID</th>
              <th className="px-6 py-3 text-left text-xs font-bold text-gray-600 uppercase tracking-wider">Serial No.</th>
              <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Status
              </th>
              <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                Created At
              </th>
            </tr>
          </thead>

          <tbody className="bg-white divide-y divide-gray-100">
            {loading ? (
              <tr><td colSpan={8} className="text-center py-10">Loading...</td></tr>
            ) : claimedCylinders.length === 0 ? (
              <tr><td colSpan={8} className="text-center py-10">No claimed cylinders found.</td></tr>
            ) : (
              claimedCylinders.map((cylinder, index) => (
                <tr key={cylinder.id} className="hover:bg-[#fff1f1]">
                  <td className="px-6 py-4">{(currentPage - 1) * itemsPerPage + index + 1}</td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
                    <span className="bg-gray-100 px-2 py-1 rounded font-mono">
                      {cylinder.rfid || 'N/A'}
                    </span>
                  </td>
                  <td className="px-6 py-4">{cylinder.item_id}</td>
                  <td className="px-6 py-4">
                    <span className={`px-3 py-1 rounded-full text-xs font-semibold border
                      ${cylinder.status === 'INSIDE' ? 'bg-emerald-100 text-emerald-800 border-emerald-300' :
                        cylinder.status === 'OUTSIDE' ? 'bg-amber-100 text-amber-800 border-amber-300' :
                          cylinder.status === 'NEW' ? 'bg-indigo-100 text-indigo-800 border-indigo-300' :
                            'bg-gray-100 text-gray-700 border-gray-300'}`}>
                      {cylinder.status}
                    </span>
                  </td>
                  <td className="px-6 py-4">{new Date(cylinder.createdAt).toLocaleDateString()}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* ---------- MOBILE CARDS ---------- */}
      <div className="md:hidden space-y-4">
        {loading ? (
          <p className="text-center py-10 text-gray-500">Loading...</p>
        ) : claimedCylinders.length === 0 ? (
          <p className="text-center py-10 text-gray-500">No claimed cylinders found.</p>
        ) : (
          claimedCylinders.map((cylinder) => (
            <div key={cylinder.id} className=" rounded-xl p-4 shadow-sm bg-gray-50">
              <p><span className="font-semibold">Serial No.:</span> {cylinder.item_id}</p>
              <p><span className="font-semibold">RFID:</span> {cylinder.rfid || 'N/A'}</p>
              <p>
                <span className="font-semibold">Status:</span>{" "}
                <span className={`px-2 py-1 rounded-full text-xs font-semibold border
                  ${cylinder.status === 'INSIDE' ? 'bg-emerald-100 text-emerald-800 border-emerald-300' :
                    cylinder.status === 'OUTSIDE' ? 'bg-amber-100 text-amber-800 border-amber-300' :
                      cylinder.status === 'NEW' ? 'bg-indigo-100 text-indigo-800 border-indigo-300' :
                        'bg-gray-100 text-gray-700 border-gray-300'}`}>
                  {cylinder.status}
                </span>
              </p>
              <p><span className="font-semibold">Claimed By:</span> {cylinder.claimedBy?.name || cylinder.claimedBy?.email || 'N/A'}</p>
              <p><span className="font-semibold">Claim Status:</span> {cylinder.claimedById ? 'Claimed' : 'Not Claimed'}</p>
              <p><span className="font-semibold">Created At:</span> {new Date(cylinder.createdAt).toLocaleDateString()}</p>
            </div>
          ))
        )}
      </div>

      {/* PAGINATION */}
      {claimedCylinders.length > 0 && !loading && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={handlePageChange}
          itemsPerPage={itemsPerPage}
          totalItems={totalItems}
        />
      )}
    </div>
  );
};

export default ClaimedCylindersTable;
