'use client';

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { WithdrawalManagement } from '@/components/accounting/WithdrawalManagement';
import WithdrawalDetailClientV2 from '@/components/accounting/WithdrawalManagement/WithdrawalDetailClientV2';
import { getWithdrawals } from '@/components/accounting/WithdrawalManagement/actions';

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

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

  const [data, setData] = useState<Awaited<ReturnType<typeof getWithdrawals>>['data']>([]);
  const [pagination, setPagination] = useState(DEFAULT_PAGINATION);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // mode=new일 때는 데이터 로드 불필요
    if (mode === 'new') {
      setIsLoading(false);
      return;
    }

    getWithdrawals({ perPage: 100 })
      .then(result => {
        setData(result.data);
        setPagination(result.pagination);
      })
      .finally(() => setIsLoading(false));
  }, [mode]);

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

  // mode=new일 때 등록 화면 표시
  if (mode === 'new') {
    return <WithdrawalDetailClientV2 initialMode="create" />;
  }

  return (
    <WithdrawalManagement
      initialData={data}
      initialPagination={pagination}
    />
  );
}