"use client"
import React, { useEffect, useState } from 'react';
import DashboardLayout from '@/app/dashboard/layout';
import { useSearchParams, useRouter } from 'next/navigation';
import EarningTable from '@/components/earningTable/table';
import { useGlobalContext } from '@/context/Provider';
import apis from '@/utils/apis';
import { currency } from '@/lib/utils';
import PaginationCompo from '@/components/common/pagination';

interface EarningCardProps {
  data: number;
  type: string;
  className?: string;
}

const EarningCard: React.FC<EarningCardProps> = ({ data, type, className }) => {
  return (
    <div
      className={`flex flex-col justify-between rounded-xl bg-white p-5 border border-[#F0F0F0] shadow-sm ${className}`}
    >
      <div className="flex items-center justify-between w-full">
        <span className="text-sm font-bold text-[#121212]">Earnings</span>
        <span className="text-2xl font-bold text-[#121212]">{currency}{data.toFixed(2)}</span>
      </div>
      <div className="mt-1">
        <span className="text-xs font-medium text-[var(--orange-400)]">{type}</span>
      </div>
    </div>
  );
};



const JobAutomation = () => {
  const { userInfo } = useGlobalContext();
  const searchParams = useSearchParams();
  const router = useRouter();

  const [earningList, setEarningList] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [earnings, setEarnings] = useState({
    todayOrders: 0,
    weekOrders: 0,
    monthOrders: 0,
    totalTodayEarning: 0,
    totalWeekEarning: 0,
    totalMonthEarning: 0,
  });

  const currentPage = Number(searchParams.get("page")) || 1;
  const itemsPerPage = Number(searchParams.get("limit")) || 10;
  const type = searchParams.get("type") || "today";

  useEffect(() => {
    if (userInfo?._id) {
      getCount();
    }
  }, [userInfo]);


  const getCount = async () => {
    try {
      const apiRes = await apis.Count.get(userInfo?._id ? userInfo.restaurant_id?._id : '');
      setEarnings(apiRes);
    } catch (error) {

    }
  };

  const getEarnings = async () => {
    try {
      const params = new URLSearchParams({
        status: type,
        page: currentPage.toString(),
        limit: itemsPerPage.toString(),
        restaurant_id: userInfo?.restaurant_id?._id || "",
      });
      const apiRes = await apis.Earning.getList(params.toString());
      setEarningList(apiRes?.data || []);
      setTotalCount(apiRes?.count || apiRes?.total || 0);
    } catch (error) {

    }
  };

  useEffect(() => {
    if (userInfo?._id) {
      getEarnings();
    }
  }, [userInfo?._id, searchParams]);

  const handlePageChange = (newPage: number) => {
    const params = new URLSearchParams(searchParams.toString());
    params.set("page", newPage.toString());
    router.push(`/earning?${params.toString()}`);
  };

  return (
    <div className="w-full min-h-full bg-gray-100 flex flex-col p-4 space-y-4 overflow-y-auto">
      {/* Feature Cards Section */}

      <div className="w-full flex flex-row flex-nowrap gap-4 flex-shrink-0 overflow-x-auto md:overflow-visible">
        <EarningCard className="flex-1 min-w-[280px] sm:min-w-[300px] md:min-w-[320px]" data={earnings?.totalTodayEarning ?? 0} type={"Today"} />
        <EarningCard className="flex-1 min-w-[280px] sm:min-w-[300px] md:min-w-[320px]" data={earnings?.totalWeekEarning ?? 0} type={"This Week"} />
        <EarningCard className="flex-1 min-w-[280px] sm:min-w-[300px] md:min-w-[320px]" data={earnings?.totalMonthEarning ?? 0} type={"This Month"} />
      </div>


      {/* DataTable Container (Auto-fits Content) */}
      <div className="w-full">
        <div className="bg-white rounded-xl shadow-sm border border-gray-100 flex flex-col overflow-hidden">
          <div className="text-[18px] font-[600] text-[#121212] w-full text-start bg-white p-4 border-b border-gray-100 flex items-center justify-between">
            <span>Recent Orders</span>
            {totalCount > 0 && (
              <span className="text-xs text-gray-500 font-normal">
                Total Orders: <span className="font-semibold text-gray-800">{totalCount}</span>
              </span>
            )}
          </div>
          <div className="overflow-x-auto">
            <EarningTable data={earningList} />
          </div>
          {totalCount > itemsPerPage && (
            <div className="p-3 bg-white border-t border-gray-100 flex items-center justify-center">
              <PaginationCompo
                totalDataCount={totalCount}
                currentPage={currentPage}
                itemsPerPage={itemsPerPage}
                onPageChange={handlePageChange}
              />
            </div>
          )}
        </div>
      </div>
    </div>

  );
};

export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <JobAutomation />
    </DashboardLayout>
  );
}