'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';
import { ListPageSkeleton } from '@/components/ui/skeleton';

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: 1000 })
        .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 <ListPageSkeleton showDateRange showStats statsCount={3} tableColumns={11} />;

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