'use client';

import { useState } from 'react';
import SidebarModal from '../rightSidebar/page';
import { useGlobalContext } from '@/context/Provider';
import { orderStatus } from '@/constants/data';
import dayjs from 'dayjs';
import { currency, formatOrderStatus } from '@/lib/utils';

interface DataTableProps {
  data: any[];
  page: number;
  totalPages: number;
  onPageChange: (newPage: number) => void;
}

const DataTable: React.FC<DataTableProps> = ({ data, page, totalPages, onPageChange }) => {
  const { setOrderInfo } = useGlobalContext();
  const [activeModal, setActiveModal] = useState<string | null>(null);

  return (
    <div className="w-full flex flex-col rounded-lg bg-white shadow-lg shadow-gray-500/50 overflow-hidden">
      {/* Responsive Scroll Container */}
      <div className="w-full overflow-x-auto flex-1">
        <table className="min-w-[800px] w-full text-sm">
          {/* Table Header */}
          <thead className="sticky top-0 z-10 bg-[#FAFAFA] text-[#828282]">
            <tr>
              <th className="min-w-[120px] px-4 py-3 text-left font-medium">Order ID</th>
              <th className="min-w-[160px] px-4 py-3 text-left font-medium">Customer Name</th>
              <th className="min-w-[200px] px-4 py-3 text-left font-medium">Time</th>
              <th className="min-w-[120px] px-4 py-3 text-left font-medium">Total Bill</th>
              <th className="min-w-[180px] px-4 py-3 text-left font-medium">Driver Assigned To</th>
              <th className="min-w-[140px] px-4 py-3 text-left font-medium">Delivery Type</th>
              <th className="min-w-[140px] px-4 py-3 text-left font-medium">Status</th>
            </tr>
          </thead>

          {/* Table Body */}
          <tbody className="divide-y divide-gray-200">
            {data?.length > 0 ? (
              data.map((item: any) => (
                <tr key={item?._id}>
                  <td className="px-4 py-3 text-[#252525]">#{item?.order_id}</td>
                  <td className="px-4 py-3 text-[#252525]">{item?.customer_id?.name || 'N/A'}</td>
                  <td className="px-4 py-3 text-[#252525]">
                    {dayjs(item?.createdAt).format('DD MMM YYYY hh:mm A')}
                  </td>
                  <td className="px-4 py-3 text-[#252525]">
                    {currency}{(item?.total_amount ?? 0)?.toFixed(2)}
                  </td>
                  <td className="px-4 py-3 text-[#252525]">
                    {item?.deliver_type === 'takeaway' || item?.deliver_type === 'pos' ? 'N/A' : (item?.driver_id?.name ?? 'Assigning Driver soon')}
                  </td>
                  <td className="px-4 py-3 text-[#252525] capitalize">
                    {item?.deliver_type || 'N/A'}
                  </td>
                  <td className="px-4 py-3">
                    <button
                      className={`h-[40px] w-full px-3 py-1 rounded-lg text-[13px] font-semibold transition-colors
                        ${item?.order_status === 'delivered'
                          ? 'bg-green-400 text-white hover:bg-green-500'
                          : item?.order_status === 'cancelled'
                            ? 'bg-red-500 text-white hover:bg-red-600'
                            : item?.order_status
                              ? 'bg-[var(--orange-500)] text-white hover:bg-[var(--primary-brand)]'
                              : 'bg-gray-400 text-white hover:bg-gray-500'}
                      `}
                      onClick={() => {
                        setActiveModal('orderDetail');
                        setOrderInfo(item);
                      }}
                    >
                      {orderStatus?.[item?.order_status] || formatOrderStatus(item?.order_status)}
                    </button>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan={7} className="px-4 py-4 text-center text-[#252525]">
                  No orders found.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      {/* ✅ Pagination Controls */}
      <div className="flex items-center justify-between px-4 py-3 border-t bg-[#FAFAFA]">
        <button
          onClick={() => onPageChange(page - 1)}
          disabled={page <= 1}
          className={`px-3 py-1 rounded-md border ${page <= 1
            ? 'cursor-not-allowed opacity-50'
            : 'hover:bg-gray-200 border-gray-300'
            }`}
        >
          Previous
        </button>

        <span className="text-sm text-gray-600">
          Page {page} of {totalPages}
        </span>

        <button
          onClick={() => onPageChange(page + 1)}
          disabled={page >= totalPages}
          className={`px-3 py-1 rounded-md border ${page >= totalPages
            ? 'cursor-not-allowed opacity-50'
            : 'hover:bg-gray-200 border-gray-300'
            }`}
        >
          Next
        </button>
      </div>

      {/* Sidebar Modal */}
      {activeModal && (
        <SidebarModal type={activeModal} onClose={() => setActiveModal(null)} />
      )}
    </div>
  );
};

export default DataTable;
