'use client';

/**
 * 재고생산관리 페이지
 *
 * - 기본: 목록 (StockProductionList)
 * - ?mode=new: 등록 (BendingLotForm — 절곡품 LOT 방식)
 * - ?mode=new&copyFrom={id}: 복사 등록 (기존 데이터 기반)
 */

import { useState, useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { StockProductionList } from '@/components/stocks/StockProductionList';
import { BendingLotForm } from '@/components/stocks/BendingLotForm';
import { getStockOrderById, type StockOrder } from '@/components/stocks/actions';

function CopyStockContent({ copyFromId }: { copyFromId: string }) {
  const [order, setOrder] = useState<StockOrder | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function load() {
      try {
        const result = await getStockOrderById(copyFromId);
        if (result.__authError) {
          toast.error('인증이 만료되었습니다.');
          return;
        }
        if (result.success && result.data) {
          setOrder(result.data);
        } else {
          toast.error(result.error || '복사할 데이터를 불러오는데 실패했습니다.');
        }
      } finally {
        setLoading(false);
      }
    }
    load();
  }, [copyFromId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="h-8 w-8 animate-spin text-blue-600" />
          <p className="text-muted-foreground">데이터를 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return <BendingLotForm initialData={order ?? undefined} />;
}

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

  if (mode === 'new') {
    if (copyFrom) {
      return <CopyStockContent copyFromId={copyFrom} />;
    }
    return <BendingLotForm />;
  }

  return <StockProductionList />;
}
