'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { TaxInvoiceIssuancePage } from '@/components/accounting/TaxInvoiceIssuance';
import { TaxInvoiceDetail } from '@/components/accounting/TaxInvoiceIssuance/TaxInvoiceDetail';
import {
  getTaxInvoices,
  getSupplierSettings,
  getTaxInvoiceById,
} from '@/components/accounting/TaxInvoiceIssuance/actions';
import type { TaxInvoiceRecord, TaxInvoiceFormData, SupplierSettings } from '@/components/accounting/TaxInvoiceIssuance/types';
import { createEmptyBusinessEntity } from '@/components/accounting/TaxInvoiceIssuance/types';
import { ListPageSkeleton } from '@/components/ui/skeleton';

type TaxInvoiceDetailData = TaxInvoiceFormData & {
  id: string;
  invoiceNumber: string;
  status: TaxInvoiceRecord['status'];
};

export default function TaxInvoiceIssuanceRoute() {
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode');
  const id = searchParams.get('id');

  const [data, setData] = useState<TaxInvoiceRecord[]>([]);
  const [supplierSettings, setSupplierSettings] = useState<SupplierSettings>(createEmptyBusinessEntity());
  const [editData, setEditData] = useState<TaxInvoiceDetailData | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (mode === 'edit' && id) {
      getTaxInvoiceById(id)
        .then((result) => {
          if (result.success && result.data) {
            setEditData(result.data);
          }
        })
        .finally(() => setIsLoading(false));
      return;
    }

    Promise.all([getTaxInvoices(), getSupplierSettings()])
      .then(([invoicesResult, settingsResult]) => {
        if (invoicesResult.success && invoicesResult.data) {
          setData(invoicesResult.data);
        }
        if (settingsResult.success && settingsResult.data) {
          setSupplierSettings(settingsResult.data);
        }
      })
      .finally(() => setIsLoading(false));
  }, [mode, id]);

  if (isLoading) return <ListPageSkeleton showStats statsCount={4} tableColumns={10} />;

  if (mode === 'edit' && id) {
    return (
      <TaxInvoiceDetail
        id={id}
        initialData={editData ?? undefined}
      />
    );
  }

  return (
    <TaxInvoiceIssuancePage
      initialData={data}
      initialSupplierSettings={supplierSettings}
    />
  );
}
