'use client';

/**
 * 재고생산 상세/수정 페이지
 *
 * - 기본: 상세 보기 (StockProductionDetail)
 * - ?mode=edit: 수정 (BendingLotForm — 등록과 동일 레이아웃)
 */

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

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

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

  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>
    );
  }

  if (!order) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-muted-foreground">데이터를 찾을 수 없습니다.</p>
      </div>
    );
  }

  return <BendingLotForm initialData={order} isEditMode />;
}

export default function StockDetailPage() {
  const params = useParams();
  const searchParams = useSearchParams();
  const id = params.id as string;
  const mode = searchParams.get('mode');

  if (mode === 'edit') {
    return <EditStockContent id={id} />;
  }

  return <StockProductionDetail orderId={id} />;
}
