/**
 * 수주 등록/수정 페이지
 * 
 * ResponsiveFormTemplate 적용
 * - 견적 기반 수주 등록
 * - 수주LOT 자동 생성
 * - 인정내용 확인
 * - 분할 설정 지원
 */

import { useState, useEffect, useMemo } from "react";
import { ShoppingCart, FileText, Package, Truck, DollarSign, User, MapPin, Info, Split, CheckCircle, AlertCircle, Receipt } from "lucide-react";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Textarea } from "./ui/textarea";
import { Checkbox } from "./ui/checkbox";
import { Badge } from "./ui/badge";
import { Card, CardContent } from "./ui/card";
import { Alert, AlertDescription } from "./ui/alert";
import { Button } from "./ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { toast } from "sonner@2.0.3";
import { validateForm, hasErrors } from "./utils/validation";
import { 
  ResponsiveFormTemplate, 
  FormSection, 
  FormField, 
  FormFieldGrid,
  ValidationError 
} from "./templates/ResponsiveFormTemplate";

interface QuoteItem {
  id: string;
  itemName: string;
  specification: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
}

interface QuoteData {
  id: string;
  quoteNo: string;
  quoteDate: string;
  buyer: string;
  buyerCode: string;
  site: string;
  siteAbbr: string;
  manager: string;
  items: QuoteItem[];
  totalAmount: number;
  deliveryDate?: string;
  certification?: {
    productName: string;
    modelName: string;
    certificationNo: string;
  };
}

interface SalesOrderData {
  id?: string;
  orderNo?: string;           // 수주번호 (자동)
  orderLot?: string;          // 수주LOT (자동생성)
  orderDate?: string;         // 수주일 (자동)
  quoteId: string;            // 견적선택
  quoteName?: string;
  customerPO?: string;        // 고객PO번호
  certificationProductName?: string;  // 인정내용-상품명
  certificationModelName?: string;    // 인정내용-모델명
  certificationNo?: string;           // 인정내용-인정번호
  deliveryDate: string;       // 납품예정일
  deliveryAddress: string;    // 수신처주소
  deliveryContact: string;    // 수신처담당자
  deliveryPhone: string;      // 수신처연락처
  deliveryMethod: string;     // 배송방식
  paymentTerms: string;       // 결제조건
  paymentStatus?: 'pending' | 'partial' | 'completed'; // 입금상태
  taxInvoiceIssued?: boolean; // 세금계산서 발행여부
  remarks?: string;           // 특이사항
  assignedManager?: string;   // 담당자배정
}

interface SplitSchedule {
  id: string;
  splitNo: number;
  quantity: number;
  deliveryDate: string;
  remarks?: string;
}

interface SalesOrderRegistrationProps {
  editingOrder?: SalesOrderData | null;
  onSave: (data: SalesOrderData) => void;
  onCancel: () => void;
}

export function SalesOrderRegistration({ editingOrder, onSave, onCancel }: SalesOrderRegistrationProps) {
  const [formData, setFormData] = useState<SalesOrderData>({
    quoteId: "",
    deliveryDate: "",
    deliveryAddress: "",
    deliveryContact: "",
    deliveryPhone: "",
    deliveryMethod: "",
    paymentTerms: "",
  });

  const [errors, setErrors] = useState<Record<string, string>>({});
  const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);
  const [selectedQuote, setSelectedQuote] = useState<QuoteData | null>(null);
  const [splitDialogOpen, setSplitDialogOpen] = useState(false);
  const [splitSchedules, setSplitSchedules] = useState<SplitSchedule[]>([]);

  // Mock 견적 데이터
  const quotes: QuoteData[] = [
    {
      id: "1",
      quoteNo: "QT-2025-001",
      quoteDate: "2025-11-15",
      buyer: "한빛에스티",
      buyerCode: "KD",
      site: "반포3지구2공구(117동)",
      siteAbbr: "TS",
      manager: "김영희",
      items: [
        { id: "1", itemName: "KQTS01", specification: "1500x2000", quantity: 100, unitPrice: 500000, totalPrice: 50000000 }
      ],
      totalAmount: 50000000,
      deliveryDate: "2025-12-15",
      certification: {
        productName: "방화문 KFD-001",
        modelName: "KQTS01",
        certificationNo: "KFI-2024-0001"
      }
    },
    {
      id: "2",
      quoteNo: "QT-2025-002",
      quoteDate: "2025-11-20",
      buyer: "주일기업",
      buyerCode: "JI",
      site: "플라이크은평",
      siteAbbr: "FL",
      manager: "이철수",
      items: [
        { id: "2", itemName: "KSS02", specification: "1800x2100", quantity: 150, unitPrice: 600000, totalPrice: 90000000 }
      ],
      totalAmount: 90000000,
      deliveryDate: "2025-12-20",
      certification: {
        productName: "자동문 KAD-002",
        modelName: "KSS02",
        certificationNo: "KFI-2024-0002"
      }
    },
    {
      id: "3",
      quoteNo: "QT-2025-003",
      quoteDate: "2025-11-22",
      buyer: "성지금속",
      buyerCode: "SJ",
      site: "한국체대부산경기장",
      siteAbbr: "KC",
      manager: "박민수",
      items: [
        { id: "3", itemName: "KSS02", specification: "1600x2000", quantity: 80, unitPrice: 550000, totalPrice: 44000000 }
      ],
      totalAmount: 44000000,
      deliveryDate: "2025-12-25"
    }
  ];

  // 담당자 목록
  const managers = ["김영희", "이철수", "박민수", "최지원", "정수현"];

  // 배송방식 목록
  const deliveryMethods = [
    "택배(직불)",
    "택배(착불)",
    "직접수령(선불)",
    "직접수령(착불)",
    "상차(선불)",
    "상차(착불)",
    "경동화물(선불)",
    "경동화물(착불)",
    "부불출고"
  ];

  // 결제조건 목록
  const paymentTermsList = [
    "월말결제",
    "현금",
    "선급 50% / 잔금 50%",
    "선급 30% / 중도 40% / 잔금 30%",
    "익월 15일",
    "익월 말일",
    "60일 어음",
    "90일 어음"
  ];

  // 수주LOT 자동 생성
  const generateOrderLot = (quote: QuoteData): string => {
    const today = new Date();
    const yy = today.getFullYear().toString().slice(-2);
    const mm = String(today.getMonth() + 1).padStart(2, '0');
    const dd = String(today.getDate()).padStart(2, '0');
    const seq = "01"; // 실제로는 DB에서 순번 조회
    
    return `${quote.buyerCode}-${quote.siteAbbr}-${yy}${mm}${dd}-${seq}`;
  };

  // 수주번호 자동 생성
  const generateOrderNo = (): string => {
    const today = new Date();
    const year = today.getFullYear();
    const seq = "001"; // 실제로는 DB에서 순번 조회
    
    return `SO-${year}-${seq}`;
  };

  // 수주일 자동 생성
  const generateOrderDate = (): string => {
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
  };

  // 견적 선택 시
  const handleQuoteChange = (quoteId: string) => {
    const quote = quotes.find(q => q.id === quoteId);
    if (quote) {
      setSelectedQuote(quote);
      
      const orderLot = generateOrderLot(quote);
      const orderNo = generateOrderNo();
      const orderDate = generateOrderDate();
      
      setFormData(prev => ({
        ...prev,
        quoteId: quote.id,
        quoteName: `${quote.quoteNo} - ${quote.buyer}`,
        orderNo: orderNo,
        orderLot: orderLot,
        orderDate: orderDate,
        deliveryDate: quote.deliveryDate || "",
        certificationProductName: quote.certification?.productName || "",
        certificationModelName: quote.certification?.modelName || "",
        certificationNo: quote.certification?.certificationNo || "",
        assignedManager: quote.manager
      }));
      
      setErrors(prev => ({ ...prev, quoteId: "" }));
      
      toast.success(`수주LOT가 생성되었습니다: ${orderLot}`);
    }
  };

  // 필드 변경 핸들러
  const handleFieldChange = (field: keyof SalesOrderData, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: "" }));
    }
  };

  // 유효성 검사 규칙
  const validationRules = {
    quoteId: { required: true, label: "견적선택" },
    deliveryDate: { required: true, label: "납품예정일" },
    deliveryAddress: { required: true, label: "수신처주소" },
    deliveryContact: { required: true, label: "수신처담당자" },
    deliveryPhone: { required: true, label: "수신처연락처" },
    deliveryMethod: { required: true, label: "배송방식" },
    paymentTerms: { required: true, label: "결제조건" }
  };

  // 분할설정 추가
  const handleAddSplit = () => {
    if (!selectedQuote) return;
    
    const newSplit: SplitSchedule = {
      id: Date.now().toString(),
      splitNo: splitSchedules.length + 1,
      quantity: 0,
      deliveryDate: "",
      remarks: ""
    };
    
    setSplitSchedules([...splitSchedules, newSplit]);
  };

  // 분할설정 삭제
  const handleRemoveSplit = (id: string) => {
    setSplitSchedules(splitSchedules.filter(s => s.id !== id));
  };

  // 분할설정 변경
  const handleSplitChange = (id: string, field: keyof SplitSchedule, value: any) => {
    setSplitSchedules(splitSchedules.map(s => 
      s.id === id ? { ...s, [field]: value } : s
    ));
  };

  // 저장
  const handleSubmit = () => {
    const validation = validateForm(formData, validationRules);
    
    if (hasErrors(validation.errors)) {
      setErrors(validation.errors);
      const errorList: ValidationError[] = Object.entries(validation.errors).map(([field, message]) => ({
        field,
        message,
        fieldLabel: validationRules[field as keyof typeof validationRules]?.label
      }));
      setValidationErrors(errorList);
      toast.error("필수 항목을 입력해주세요");
      return;
    }

    // 분할설정 검증
    if (splitSchedules.length > 0) {
      const totalQuantity = selectedQuote?.items.reduce((sum, item) => sum + item.quantity, 0) || 0;
      const splitTotalQuantity = splitSchedules.reduce((sum, split) => sum + split.quantity, 0);
      
      if (splitTotalQuantity !== totalQuantity) {
        toast.error(`분할 수량의 합계(${splitTotalQuantity})가 총 수량(${totalQuantity})과 일치하지 않습니다`);
        return;
      }
      
      const invalidSplit = splitSchedules.find(s => !s.deliveryDate || s.quantity <= 0);
      if (invalidSplit) {
        toast.error("모든 분할 항목의 수량과 납품일을 입력해주세요");
        return;
      }
    }

    onSave(formData);
    toast.success("수주가 등록되었습니다");
  };

  // 에러 클릭 핸들러
  const handleErrorClick = (field: string) => {
    const element = document.getElementById(field);
    if (element) {
      element.focus();
      element.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
  };

  // 견적 정보 표시
  const QuoteInfo = () => {
    if (!selectedQuote) return null;

    return (
      <Card className="mt-4 border-blue-200 bg-blue-50/30">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center justify-between pb-2 border-b">
            <span className="font-semibold flex items-center gap-2">
              <FileText className="h-4 w-4" />
              견적 정보
            </span>
            <Badge variant="outline" className="bg-blue-100">
              {selectedQuote.quoteNo}
            </Badge>
          </div>
          
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div>
              <span className="text-muted-foreground">발주처:</span>
              <span className="ml-2 font-medium">{selectedQuote.buyer}</span>
            </div>
            <div>
              <span className="text-muted-foreground">현장:</span>
              <span className="ml-2 font-medium">{selectedQuote.site}</span>
            </div>
            <div>
              <span className="text-muted-foreground">견적일:</span>
              <span className="ml-2 font-medium">{selectedQuote.quoteDate}</span>
            </div>
            <div>
              <span className="text-muted-foreground">견적금액:</span>
              <span className="ml-2 font-semibold text-blue-600">
                {selectedQuote.totalAmount.toLocaleString()}원
              </span>
            </div>
            <div>
              <span className="text-muted-foreground">담당자:</span>
              <span className="ml-2 font-medium">{selectedQuote.manager}</span>
            </div>
            <div>
              <span className="text-muted-foreground">품목수:</span>
              <span className="ml-2 font-medium">{selectedQuote.items.length}개</span>
            </div>
          </div>

          {/* 견적 품목 */}
          <div className="pt-2 border-t">
            <div className="text-xs text-muted-foreground mb-2">견적 품목</div>
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow className="bg-muted/50">
                    <TableHead className="text-center">품목명</TableHead>
                    <TableHead className="text-center">규격</TableHead>
                    <TableHead className="text-center">수량</TableHead>
                    <TableHead className="text-center">단가</TableHead>
                    <TableHead className="text-center">금액</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {selectedQuote.items.map(item => (
                    <TableRow key={item.id}>
                      <TableCell className="text-center">{item.itemName}</TableCell>
                      <TableCell className="text-center">{item.specification}</TableCell>
                      <TableCell className="text-center">{item.quantity}</TableCell>
                      <TableCell className="text-center">{item.unitPrice.toLocaleString()}원</TableCell>
                      <TableCell className="text-center font-semibold">{item.totalPrice.toLocaleString()}원</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  };

  // 수주LOT 정보 표시
  const OrderLotInfo = () => {
    if (!formData.orderLot) return null;

    return (
      <Card className="mt-4 border-green-200 bg-green-50/30">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <Package className="h-5 w-5 text-green-600" />
              <span className="font-semibold">수주LOT 자동 생성</span>
            </div>
            <Badge className="bg-green-100 text-green-700 border-green-200">
              <CheckCircle className="h-3 w-3 mr-1" />
              생성완료
            </Badge>
          </div>

          <div className="space-y-2">
            <div className="flex items-center justify-between p-3 bg-white rounded-lg border">
              <span className="text-sm text-muted-foreground">수주번호:</span>
              <span className="font-mono font-bold text-lg">{formData.orderNo}</span>
            </div>
            <div className="flex items-center justify-between p-3 bg-white rounded-lg border">
              <span className="text-sm text-muted-foreground">수주LOT:</span>
              <span className="font-mono font-bold text-lg text-green-600">{formData.orderLot}</span>
            </div>
          </div>

          <Alert className="border-green-200 bg-green-50">
            <Info className="h-4 w-4 text-green-600" />
            <AlertDescription className="text-green-800 text-sm">
              <div className="space-y-1">
                <div>수주LOT 형식: 발주처코드-현장약어-YYMMDD-순번</div>
                <div className="text-xs text-green-600">
                  예시: KD-TS-251201-01 = 한빛에스티-반포3지구-2025년12월01일-01번
                </div>
              </div>
            </AlertDescription>
          </Alert>
        </CardContent>
      </Card>
    );
  };

  // 인정내용 정보
  const CertificationInfo = () => {
    if (!selectedQuote || !selectedQuote.certification) return null;

    return (
      <Card className="mt-4 border-purple-200 bg-purple-50/30">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center gap-2 pb-2 border-b">
            <CheckCircle className="h-4 w-4 text-purple-600" />
            <span className="font-semibold">인정내용</span>
          </div>
          
          <div className="grid grid-cols-3 gap-3 text-sm">
            <div className="p-2 bg-white rounded border">
              <div className="text-xs text-muted-foreground mb-1">상품명</div>
              <div className="font-medium">{selectedQuote.certification.productName}</div>
            </div>
            <div className="p-2 bg-white rounded border">
              <div className="text-xs text-muted-foreground mb-1">모델명</div>
              <div className="font-medium">{selectedQuote.certification.modelName}</div>
            </div>
            <div className="p-2 bg-white rounded border">
              <div className="text-xs text-muted-foreground mb-1">인정번호</div>
              <div className="font-medium">{selectedQuote.certification.certificationNo}</div>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  };

  // 결제계획 정보
  const PaymentPlanInfo = () => {
    if (!selectedQuote || !formData.paymentTerms) return null;

    return (
      <Card className="mt-4 border-orange-200 bg-orange-50/30">
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center gap-2 pb-2 border-b">
            <DollarSign className="h-4 w-4 text-orange-600" />
            <span className="font-semibold">결제계획</span>
          </div>
          
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">총 수주금액:</span>
              <span className="font-bold text-lg">{selectedQuote.totalAmount.toLocaleString()}원</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">결제조건:</span>
              <span className="font-semibold">{formData.paymentTerms}</span>
            </div>
            <div className="flex justify-between text-sm">
              <span className="text-muted-foreground">납품예정일:</span>
              <span className="font-semibold">{formData.deliveryDate}</span>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  };

  useEffect(() => {
    if (editingOrder) {
      setFormData(editingOrder);
      // 견적 정보 로드
      const quote = quotes.find(q => q.id === editingOrder.quoteId);
      if (quote) {
        setSelectedQuote(quote);
      }
    }
  }, [editingOrder]);

  return (
    <>
      <ResponsiveFormTemplate
        title={editingOrder ? "수주 수정" : "수주 등록"}
        description="견적을 선택하여 수주를 등록하세요"
        icon={ShoppingCart}
        onSave={handleSubmit}
        onCancel={onCancel}
        saveText="저장"
        cancelText="취소"
        validationErrors={validationErrors}
        onErrorClick={handleErrorClick}
        maxWidth="3xl"
        additionalActions={
          selectedQuote && (
            <Button 
              variant="outline" 
              onClick={() => setSplitDialogOpen(true)}
              type="button"
            >
              <Split className="h-4 w-4 mr-2" />
              분할설정
              {splitSchedules.length > 0 && (
                <Badge className="ml-2 bg-purple-600">
                  {splitSchedules.length}차
                </Badge>
              )}
            </Button>
          )
        }
      >
        {/* 1. 견적 선택 */}
        <FormSection
          title="견적 선택"
          description="수주로 전환할 견적을 선택하세요"
          icon={FileText}
        >
          <FormField
            label="견적선택"
            required
            error={errors.quoteId}
            htmlFor="quoteId"
            helpText="견적 선택 시 정보가 자동으로 불러와집니다"
          >
            <Select 
              value={formData.quoteId} 
              onValueChange={handleQuoteChange}
            >
              <SelectTrigger id="quoteId">
                <SelectValue placeholder="견적을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                {quotes.length === 0 ? (
                  <div className="p-4 text-sm text-muted-foreground text-center">
                    선택 가능한 견적이 없습니다
                  </div>
                ) : (
                  quotes.map(quote => (
                    <SelectItem key={quote.id} value={quote.id}>
                      <div className="flex items-center justify-between w-full">
                        <div>
                          <div className="font-medium">{quote.quoteNo}</div>
                          <div className="text-xs text-muted-foreground">
                            {quote.buyer} - {quote.site} ({quote.totalAmount.toLocaleString()}원)
                          </div>
                        </div>
                      </div>
                    </SelectItem>
                  ))
                )}
              </SelectContent>
            </Select>
          </FormField>

          <QuoteInfo />
          <OrderLotInfo />
          <CertificationInfo />
        </FormSection>

        {/* 2. 수주 기본정보 */}
        <FormSection
          title="수주 기본정보"
          description="수주 정보를 입력하세요"
          icon={ShoppingCart}
        >
          <FormFieldGrid columns={2}>
            <FormField
              label="고객PO번호"
              htmlFor="customerPO"
              helpText="고객사에서 발행한 PO번호"
            >
              <Input
                id="customerPO"
                placeholder="PO번호 입력"
                value={formData.customerPO || ""}
                onChange={(e) => handleFieldChange("customerPO", e.target.value)}
              />
            </FormField>

            <FormField
              label="납품예정일"
              required
              error={errors.deliveryDate}
              htmlFor="deliveryDate"
            >
              <Input
                id="deliveryDate"
                type="date"
                value={formData.deliveryDate}
                onChange={(e) => handleFieldChange("deliveryDate", e.target.value)}
              />
            </FormField>
          </FormFieldGrid>

          <FormFieldGrid columns={2}>
            <FormField
              label="결제조건"
              required
              error={errors.paymentTerms}
              htmlFor="paymentTerms"
            >
              <Select 
                value={formData.paymentTerms} 
                onValueChange={(value) => handleFieldChange("paymentTerms", value)}
              >
                <SelectTrigger id="paymentTerms">
                  <SelectValue placeholder="결제조건 선택" />
                </SelectTrigger>
                <SelectContent>
                  {paymentTermsList.map(term => (
                    <SelectItem key={term} value={term}>{term}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </FormField>

            <FormField
              label="담당자배정"
              htmlFor="assignedManager"
              helpText="견적 담당자가 기본 배정됩니다"
            >
              <Select 
                value={formData.assignedManager || ""} 
                onValueChange={(value) => handleFieldChange("assignedManager", value)}
              >
                <SelectTrigger id="assignedManager">
                  <SelectValue placeholder="담당자 선택" />
                </SelectTrigger>
                <SelectContent>
                  {managers.map(manager => (
                    <SelectItem key={manager} value={manager}>{manager}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </FormField>
          </FormFieldGrid>

          <FormFieldGrid columns={2}>
            <FormField
              label="입금상태"
              htmlFor="paymentStatus"
              helpText="입금 현황을 선택하세요"
            >
              <Select 
                value={formData.paymentStatus || "pending"} 
                onValueChange={(value: 'pending' | 'partial' | 'completed') => handleFieldChange("paymentStatus", value)}
              >
                <SelectTrigger id="paymentStatus">
                  <SelectValue placeholder="입금상태 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">미입금</SelectItem>
                  <SelectItem value="partial">부분입금</SelectItem>
                  <SelectItem value="completed">입금완료</SelectItem>
                </SelectContent>
              </Select>
            </FormField>

            <FormField
              label="세금계산서 발행"
              htmlFor="taxInvoiceIssued"
              helpText="세금계산서 발행 여부"
            >
              <div className="flex items-center space-x-2 h-10">
                <Checkbox
                  id="taxInvoiceIssued"
                  checked={formData.taxInvoiceIssued || false}
                  onCheckedChange={(checked) => handleFieldChange("taxInvoiceIssued", checked)}
                />
                <Label htmlFor="taxInvoiceIssued" className="cursor-pointer flex items-center gap-2">
                  <Receipt className="h-4 w-4" />
                  <span>{formData.taxInvoiceIssued ? "발행완료" : "미발행"}</span>
                </Label>
              </div>
            </FormField>
          </FormFieldGrid>

          <PaymentPlanInfo />
        </FormSection>

        {/* 3. 수신처 정보 */}
        <FormSection
          title="수신처 정보"
          description="제품을 배송받을 정보를 입력하세요"
          icon={MapPin}
        >
          <FormField
            label="수신처주소"
            required
            error={errors.deliveryAddress}
            htmlFor="deliveryAddress"
          >
            <Input
              id="deliveryAddress"
              placeholder="배송받을 주소 입력"
              value={formData.deliveryAddress}
              onChange={(e) => handleFieldChange("deliveryAddress", e.target.value)}
            />
          </FormField>

          <FormFieldGrid columns={2}>
            <FormField
              label="수신처담당자"
              required
              error={errors.deliveryContact}
              htmlFor="deliveryContact"
            >
              <Input
                id="deliveryContact"
                placeholder="담당자명 입력"
                value={formData.deliveryContact}
                onChange={(e) => handleFieldChange("deliveryContact", e.target.value)}
              />
            </FormField>

            <FormField
              label="수신처연락처"
              required
              error={errors.deliveryPhone}
              htmlFor="deliveryPhone"
            >
              <Input
                id="deliveryPhone"
                type="tel"
                placeholder="010-0000-0000"
                value={formData.deliveryPhone}
                onChange={(e) => handleFieldChange("deliveryPhone", e.target.value)}
              />
            </FormField>
          </FormFieldGrid>
        </FormSection>

        {/* 4. 배송 정보 */}
        <FormSection
          title="배송 정보"
          description="배송 방식을 선택하세요"
          icon={Truck}
        >
          <FormField
            label="배송방식"
            required
            error={errors.deliveryMethod}
            htmlFor="deliveryMethod"
          >
            <Select 
              value={formData.deliveryMethod} 
              onValueChange={(value) => handleFieldChange("deliveryMethod", value)}
            >
              <SelectTrigger id="deliveryMethod">
                <SelectValue placeholder="배송방식 선택" />
              </SelectTrigger>
              <SelectContent>
                {deliveryMethods.map(method => (
                  <SelectItem key={method} value={method}>{method}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </FormField>

          <FormField
            label="특이사항"
            htmlFor="remarks"
          >
            <Textarea
              id="remarks"
              placeholder="배송 시 특이사항이나 요청사항을 입력하세요"
              rows={4}
              value={formData.remarks || ""}
              onChange={(e) => handleFieldChange("remarks", e.target.value)}
            />
          </FormField>
        </FormSection>
      </ResponsiveFormTemplate>

      {/* 분할설정 다이얼로그 */}
      <Dialog open={splitDialogOpen} onOpenChange={setSplitDialogOpen}>
        <DialogContent className="max-w-4xl">
          <DialogHeader>
            <DialogTitle>분할 출고 설정</DialogTitle>
            <DialogDescription>
              {selectedQuote && `총 수량: ${selectedQuote.items.reduce((sum, item) => sum + item.quantity, 0)}개`}
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            {splitSchedules.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                분할 출고 일정을 추가하세요
              </div>
            ) : (
              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead className="text-center w-[80px]">차수</TableHead>
                      <TableHead className="text-center w-[120px]">수량</TableHead>
                      <TableHead className="text-center w-[150px]">납품일</TableHead>
                      <TableHead className="text-center">비고</TableHead>
                      <TableHead className="text-center w-[80px]">삭제</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {splitSchedules.map((split, index) => (
                      <TableRow key={split.id}>
                        <TableCell className="text-center">
                          <Badge variant="outline">{split.splitNo}차</Badge>
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            min="0"
                            placeholder="수량"
                            value={split.quantity || ""}
                            onChange={(e) => handleSplitChange(split.id, "quantity", parseInt(e.target.value) || 0)}
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="date"
                            value={split.deliveryDate}
                            onChange={(e) => handleSplitChange(split.id, "deliveryDate", e.target.value)}
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            placeholder="비고"
                            value={split.remarks || ""}
                            onChange={(e) => handleSplitChange(split.id, "remarks", e.target.value)}
                          />
                        </TableCell>
                        <TableCell className="text-center">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRemoveSplit(split.id)}
                            className="text-red-600 hover:text-red-700"
                          >
                            삭제
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            )}

            <div className="flex justify-between items-center pt-2 border-t">
              <div className="text-sm text-muted-foreground">
                {splitSchedules.length > 0 && (
                  <>
                    분할 수량 합계: <span className="font-semibold">
                      {splitSchedules.reduce((sum, split) => sum + split.quantity, 0)}
                    </span>
                    {selectedQuote && ` / ${selectedQuote.items.reduce((sum, item) => sum + item.quantity, 0)}`}
                  </>
                )}
              </div>
              <Button onClick={handleAddSplit} variant="outline">
                <Split className="h-4 w-4 mr-2" />
                분할 추가
              </Button>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setSplitDialogOpen(false)}>
              취소
            </Button>
            <Button onClick={() => {
              setSplitDialogOpen(false);
              toast.success(`${splitSchedules.length}차 분할 출고가 설정되었습니다`);
            }}>
              적용
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}