'use client';

/**
 * 악성채권 추심관리 목록/등록 페이지
 *
 * 경로: /accounting/bad-debt-collection
 * 경로: /accounting/bad-debt-collection?mode=new
 */

import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { BadDebtCollection, BadDebtDetailClientV2 } from '@/components/accounting/BadDebtCollection';
import { getBadDebts, getBadDebtSummary } from '@/components/accounting/BadDebtCollection/actions';
import type { BadDebtSummary } from '@/components/accounting/BadDebtCollection/types';
import { ListPageSkeleton } from '@/components/ui/skeleton';

const DEFAULT_SUMMARY: BadDebtSummary = {
  totalCount: 0,
  totalAmount: 0,
  collectedAmount: 0,
  pendingAmount: 0,
  collectionRate: 0,
};

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

  const [data, setData] = useState<Awaited<ReturnType<typeof getBadDebts>>>([]);
  const [summary, setSummary] = useState<BadDebtSummary | Awaited<ReturnType<typeof getBadDebtSummary>> | null>(DEFAULT_SUMMARY);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (mode !== 'new') {
      Promise.all([
        getBadDebts({ size: 100 }),
        getBadDebtSummary(),
      ])
        .then(([badDebts, summaryResult]) => {
          setData(badDebts);
          setSummary(summaryResult);
        })
        .finally(() => setIsLoading(false));
    } else {
      setIsLoading(false);
    }
  }, [mode]);

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

  if (isLoading) return <ListPageSkeleton showDateRange={false} showCreateButton={false} showStats statsCount={4} tableColumns={8} />;

  return (
    <BadDebtCollection
      initialData={data}
      initialSummary={summary as { total_amount: number; collecting_amount: number; legal_action_amount: number; collection_end_amount: number; } | null}
    />
  );
}
