'use client';

/**
 * 견적관리 목록 페이지
 *
 * V2 URL 패턴:
 * - 목록: /sales/quote-management
 * - 등록: /sales/quote-management/new
 * - 상세: /sales/quote-management/[id]
 * - 수정: /sales/quote-management/[id]?mode=edit
 */

import { useEffect, useState } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import { QuoteManagementClient } from '@/components/quotes/QuoteManagementClient';
import { getQuotes } from '@/components/quotes';
import { GenericPageSkeleton } from '@/components/ui/skeleton';

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

export default function QuoteManagementPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const mode = searchParams.get('mode');

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

  // V1 호환: ?mode=new → /new 리다이렉트
  useEffect(() => {
    if (mode === 'new') {
      router.replace('/sales/quote-management/new');
      return;
    }

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

  // 리다이렉트 중이면 로딩 표시
  if (mode === 'new') {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="text-muted-foreground">리다이렉트 중...</div>
      </div>
    );
  }

  if (isLoading) return <GenericPageSkeleton />;

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