'use client';

import { useRouter, useSearchParams } from 'next/navigation';
import useSWR from 'swr';
import SalesReportTable from '@/components/pages/closing/sale/SalesReportTable';
import { ClosingApi } from '@/services/api/closing';
import { isResponseSuccess } from '@/lib/api-helper';
import SapronakCalculationTable from '@/components/pages/closing/sapronak/SapronakCalculationTable';
import Tabs from '@/components/Tabs';
import { useState } from 'react';

const ClosingDetailPage = () => {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [activeTab, setActiveTab] = useState<string>('perhitungan_sapronak');

  const closingId = searchParams.get('closingId');

  const { data: closing, isLoading: isLoadingClosing } = useSWR(
    closingId,
    (id: string) => {
      const numericId = parseInt(id, 10);
      if (isNaN(numericId) || numericId <= 0) {
        throw new Error('Invalid closing ID');
      }
      return ClosingApi.getPenjualan(numericId);
    }
  );

  const { data: sapronakCalculation, isLoading: isLoadingSapronakCalculation } =
    useSWR(`/closing/${closingId}/perhitungan_sapronak`, () => {
      const numericId = parseInt(closingId ?? '', 10);
      if (isNaN(numericId) || numericId <= 0) {
        throw new Error('Invalid closing ID');
      }
      const res = ClosingApi.getPerhitunganSapronak(numericId);
      console.log(res);
      return res;
    });

  if (!closingId) {
    router.back();

    return (
      <div className='w-full flex flex-row justify-center items-center p-4'>
        <span className='loading loading-spinner loading-xl' />
      </div>
    );
  }

  return (
    <div className='w-full p-4'>
      <Tabs
        activeTabId={activeTab}
        onTabChange={setActiveTab}
        variant='lifted'
        className={{
          wrapper: 'mx-auto mt-4',
        }}
        tabs={[
          {
            id: 'perhitungan_sapronak',
            label: 'Perhitungan Sapronak',
            content: isResponseSuccess(sapronakCalculation) && (
              <SapronakCalculationTable
                initialValues={sapronakCalculation.data}
              />
            ),
          },
          {
            id: 'penjualan',
            label: 'Penjualan',
            content: isResponseSuccess(closing) && (
              <SalesReportTable type='detail' initialValues={closing.data} />
            ),
          },
        ]}
      />
    </div>
  );
};

export default ClosingDetailPage;
