'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { BillManagementClient } from '@/components/accounting/BillManagement/BillManagementClient';
// V2 테스트: 새 훅 적용 버전
import { BillDetail } from '@/components/accounting/BillManagement/BillDetail';
import { getBills } from '@/components/accounting/BillManagement/actions';
import type { BillRecord } from '@/components/accounting/BillManagement/types';
import { ListPageSkeleton } from '@/components/ui/skeleton';

const DEFAULT_PAGINATION = {
  currentPage: 1,
  lastPage: 1,
  perPage: 20,
  total: 0,
};

export default function BillsPage() {
  const searchParams = useSearchParams();
  const mode = searchParams.get('mode');
  const vendorId = searchParams.get('vendorId') || undefined;
  const billType = searchParams.get('type') || 'received';
  const page = searchParams.get('page') ? parseInt(searchParams.get('page')!) : 1;

  const [data, setData] = useState<BillRecord[]>([]);
  const [pagination, setPagination] = useState(DEFAULT_PAGINATION);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (mode !== 'new') {
      getBills({ billType, page, perPage: 20 })
        .then(result => {
          if (result.success) {
            setData(result.data);
            setPagination(result.pagination);
          }
        })
        .finally(() => setIsLoading(false));
    } else {
      setIsLoading(false);
    }
  }, [mode, billType, page]);

  if (mode === 'new') {
    return <BillDetail billId="new" mode="new" />;
  }

  if (isLoading) return <ListPageSkeleton tableColumns={9} />;

  return (
    <BillManagementClient
      initialData={data}
      initialPagination={pagination}
      initialVendorId={vendorId}
      initialBillType={billType}
    />
  );
}
