'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { VendorManagement } from '@/components/accounting/VendorManagement';
import { VendorDetail } from '@/components/accounting/VendorManagement/VendorDetail';
import { getClients } from '@/components/accounting/VendorManagement/actions';

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

  const [data, setData] = useState<Awaited<ReturnType<typeof getClients>>['data']>([]);
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (mode !== 'new') {
      getClients({ size: 100 })
        .then(result => {
          setData(result.data);
          setTotal(result.total);
        })
        .finally(() => setIsLoading(false));
    } else {
      setIsLoading(false);
    }
  }, [mode]);

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

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-muted-foreground">로딩 중...</div>
      </div>
    );
  }

  return (
    <VendorManagement
      initialData={data}
      initialTotal={total}
    />
  );
}
