'use client';

import { orderStatus } from "@/constants/data";
import { useGlobalContext } from "@/context/Provider";
import { useState } from "react";
import SidebarModal from "../rightSidebar/page";

const EarningTable = ({ data }: any) => {
  const { setOrderInfo } = useGlobalContext();
  const [activeModal, setActiveModal] = useState<string | null>(null);

  const handleDate = (date: any) => {
    if (!date) return "N/A";
    const timestamp = date > 9999999999 ? date : date * 1000;
    const dateObj = new Date(timestamp);

    const options: Intl.DateTimeFormatOptions = {
      day: '2-digit',
      month: 'short',
      year: 'numeric',
    };

    return dateObj.toLocaleDateString('en-US', options);
  };
  const handleTime = (date: any) => {
    if (!date) return "N/A";
    const timestamp = date > 9999999999 ? date : date * 1000;
    const dateObj = new Date(timestamp);

    const timeString = dateObj.toLocaleTimeString('en-US', {
      hour: 'numeric',
      minute: '2-digit',
      hour12: true,
    });

    return timeString;
  };

  const formatEarningType = (type: string) => {
    if (!type) return "N/A";
    if (type === "pos") return "POS";
    return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  };

  return (
    <div className="w-full max-h-[50vh] flex flex-col bg-white rounded-lg shadow-lg shadow-gray-500/50 overflow-hidden">
      {/* Single horizontal scroll container wrapping entire table */}
      <div className="overflow-x-auto flex-1">
        {/* Single table for header + body */}
        <table className="min-w-[600px] w-full table-auto">
          <thead className="bg-[#FAFAFA] text-[#828282] sticky top-0 z-10">
            <tr>
              <th className="px-4 py-3 text-left text-xs sm:text-sm font-medium w-[15%] whitespace-nowrap">
                Orders ID
              </th>
              {/* <th className="px-4 py-3 text-left text-xs sm:text-sm font-medium w-[17%] whitespace-nowrap">
                Users
              </th> */}
              <th className="px-4 py-3 text-left text-xs sm:text-sm font-medium w-[17%] whitespace-nowrap">
                Date
              </th>
              <th className="px-4 py-3 text-left text-xs sm:text-sm font-medium w-[17%] whitespace-nowrap">
                Earning
              </th>
              <th className="px-4 py-3 text-left text-xs sm:text-sm font-medium w-[17%] whitespace-nowrap">
                Status
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200 overflow-y-auto">
            {data?.length > 0 &&
              data?.map((item: any, index: number) => (
                <tr
                  key={index}
                  className={`hover:bg-gray-50 ${item?.earning_type !== "current" ? "cursor-default" : "cursor-pointer"}`}
                  onClick={() => {
                    if (item?.earning_type !== "current") return;
                    setActiveModal("orderDetail");
                    setOrderInfo(item);
                  }}
                >
                  <td className="px-4 py-4 text-xs sm:text-sm text-[#252525] w-[15%] whitespace-nowrap">
                    #{item?.order?.order_id || item?.reference_id}
                  </td>
                  {/* <td className="px-4 py-3 text-xs sm:text-sm w-[17%] whitespace-nowrap">
                    <div className="text-[#252525]">Ralph Edwards</div>
                  </td> */}
                  <td className="px-4 py-4 text-xs sm:text-sm text-[#252525] w-[17%] whitespace-nowrap">
                    {handleDate(item?.order_placed_at || item?.created_at)}
                  </td>
                  <td className="px-4 py-4 text-xs sm:text-sm text-[#188A42] w-[17%] whitespace-nowrap">
                    +₹{(item?.restaurant_earning).toFixed(2)}
                  </td>

                  <td
                    className="px-4 py-4 text-xs sm:text-sm text-[#188A42] w-[17%] whitespace-nowrap"
                    onClick={(e) => {
                      e.stopPropagation();
                      if (item?.earning_type !== "current") return;
                      setActiveModal("orderDetail");
                      setOrderInfo(item);
                    }}
                  >
                    {item?.earning_type === "current" ? (orderStatus?.[item?.order?.order_status] || "N/A") : formatEarningType(item?.earning_type)}
                  </td>
                </tr>
              ))}
          </tbody>
        </table>
      </div>

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

export default EarningTable;
