import { useState, useEffect } from "react";
import { ResponsiveFormTemplate, FormSection, FormField, FormFieldGrid } from "./templates/ResponsiveFormTemplate";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
import { RadioGroup, RadioGroupItem } from "./ui/radio-group";
import { Switch } from "./ui/switch";
import { 
  ShoppingCart, 
  Save, 
  X, 
  Plus,
  Trash2,
  Search,
  Building,
  Truck,
  CreditCard,
  FileText,
  Package,
  FileSearch,
  Calendar,
  Layers,
  User
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";
import type { Quote, ShippingSchedule } from "./contexts/DataContext";

interface ProductItem {
  id: string;
  no: number;
  itemCode: string;
  itemName: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
  unit: string;
  note: string;
}

interface SalesOrderWriteProps {
  mode: "create" | "edit";
  orderId?: string;
  onBack: () => void;
}

export function SalesOrderWrite({ mode, orderId, onBack }: SalesOrderWriteProps) {
  const { quotes, addSalesOrder, updateSalesOrder, salesOrders, sites } = useData();
  const isEditMode = mode === "edit";

  // 견적 불러오기 다이얼로그
  const [showQuoteDialog, setShowQuoteDialog] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState<Quote | null>(null);
  const [quoteSearchTerm, setQuoteSearchTerm] = useState("");

  // 기본 정보
  const [orderNumber, setOrderNumber] = useState("");
  const [orderDate, setOrderDate] = useState(new Date().toISOString().split('T')[0]);
  const [customerName, setCustomerName] = useState("");
  const [projectName, setProjectName] = useState("");
  const [deliveryDate, setDeliveryDate] = useState("");
  
  // 현장 관리
  const [siteId, setSiteId] = useState("");
  const [siteName, setSiteName] = useState("");

  // 고객사 정보
  const [salesPerson, setSalesPerson] = useState("");
  const [clientPhone, setClientPhone] = useState("");
  const [clientContact, setClientContact] = useState("");

  // 배송지 정보
  const [shippingMethod, setShippingMethod] = useState("직접배송");
  const [shippingAddress, setShippingAddress] = useState("");
  const [receiverName, setReceiverName] = useState("");
  const [receiverPhone, setReceiverPhone] = useState("");

  // 결제 정보
  const [paymentType, setPaymentType] = useState("현금결제(선)");
  const [billingType, setBillingType] = useState("세금계산서");

  // 상태
  const [orderStatus, setOrderStatus] = useState<'pending' | 'confirmed' | 'production' | 'shipping' | 'completed' | 'cancelled'>('pending');

  // 금액 정보
  const [totalAmount, setTotalAmount] = useState(0);

  // 특이사항
  const [internalMemo, setInternalMemo] = useState("");
  const [deliveryMemo, setDeliveryMemo] = useState("");
  const [shippingMemo, setShippingMemo] = useState("");

  // 제품 목록
  const [products, setProducts] = useState<ProductItem[]>([]);

  // 분할 출하 관리
  const [hasMultipleShipping, setHasMultipleShipping] = useState(false);
  const [shippingSchedules, setShippingSchedules] = useState<ShippingSchedule[]>([]);

  // 견적 불러오기
  const handleLoadQuote = (quote: Quote) => {
    setSelectedQuote(quote);
    
    // 기본 정보 매핑
    setCustomerName(quote.customerName || "");
    setProjectName(quote.projectName || "");
    setOrderDate(new Date().toISOString().split('T')[0]);
    setDeliveryDate(quote.completionDate || "");
    
    // 현장 정보 매핑
    if (quote.siteId) {
      setSiteId(quote.siteId);
      const selectedSite = sites.find(s => s.id === quote.siteId);
      if (selectedSite) {
        setSiteName(selectedSite.siteName);
      }
    }
    
    // 고객사 정보 매핑
    setSalesPerson(quote.author || quote.manager || "");
    setClientPhone(quote.contactPhone || quote.contact || "");
    setClientContact(quote.clientContact || "");
    
    // 배송지 정보 매핑
    setShippingAddress(quote.site || "");
    
    // 금액 정보 매핑
    setTotalAmount(quote.totalAmount || quote.amount || 0);
    
    // 특이사항 매핑
    setInternalMemo(quote.memo || quote.notes || "");
    setDeliveryMemo(quote.remarks || "");
    
    // 제품 목록 매핑 - BOM 계산 결과 우선 사용
    let mappedProducts: ProductItem[] = [];
    
    if (quote.bomCalculations && quote.bomCalculations.length > 0) {
      // BOM 계산 결과가 있는 경우 (가장 상세한 정보)
      mappedProducts = quote.bomCalculations.map((bom, index) => ({
        id: bom.id || `bom-${index}`,
        no: index + 1,
        itemCode: bom.itemCode,
        itemName: bom.itemName,
        quantity: bom.calculatedQuantity,
        unitPrice: bom.unitPrice,
        totalPrice: bom.totalPrice,
        unit: bom.unit,
        note: bom.note || bom.formula || ""
      }));
      toast.success(`견적 "${quote.quoteNumber}"의 BOM 계산 결과 ${mappedProducts.length}개 항목을 불러왔습니다`);
    } else if (quote.calculationRows && quote.calculationRows.length > 0) {
      // 계산 행이 있는 경우
      mappedProducts = quote.calculationRows.map((row, index) => ({
        id: row.id,
        no: index + 1,
        itemCode: row.distributionType || "",
        itemName: `${row.distributionType} ${row.width}×${row.thickness}`,
        quantity: row.quantity || 0,
        unitPrice: 0, // 단가는 별도 계산 필요
        totalPrice: 0,
        unit: "EA",
        note: row.notes || ""
      }));
      toast.success(`견적 "${quote.quoteNumber}"의 계산 결과 ${mappedProducts.length}개 항목을 불러왔습니다`);
    } else if (quote.productCode) {
      // 단순 제품 정보만 있는 경우
      mappedProducts = [{
        id: "1",
        no: 1,
        itemCode: quote.productCode,
        itemName: quote.projectName || "",
        quantity: quote.quantity || 1,
        unitPrice: quote.totalAmount || 0,
        totalPrice: quote.totalAmount || 0,
        unit: "EA",
        note: ""
      }];
      toast.success(`견적 "${quote.quoteNumber}"을(를) 불러왔습니다`);
    } else {
      toast.warning(`견적 "${quote.quoteNumber}"에 품목 정보가 없습니다. 품목을 직접 추가해주세요.`);
    }
    
    setProducts(mappedProducts);
    setShowQuoteDialog(false);
  };

  // 분할 출하 일정 추가
  const handleAddShippingSchedule = () => {
    const newSchedule: ShippingSchedule = {
      id: `schedule-${Date.now()}`,
      scheduleNumber: shippingSchedules.length + 1,
      scheduledDate: "",
      quantity: 0,
      remainingQuantity: 0,
      shippingAddress: shippingAddress,
      receiverName: receiverName,
      receiverPhone: receiverPhone,
      status: 'scheduled',
      note: ""
    };
    setShippingSchedules([...shippingSchedules, newSchedule]);
  };

  // 분할 출하 일정 삭제
  const handleRemoveShippingSchedule = (id: string) => {
    setShippingSchedules(shippingSchedules.filter(s => s.id !== id));
  };

  // 분할 출하 일정 업데이트
  const handleUpdateShippingSchedule = (id: string, field: keyof ShippingSchedule, value: any) => {
    setShippingSchedules(shippingSchedules.map(s => 
      s.id === id ? { ...s, [field]: value } : s
    ));
  };

  // 편집 모드일 때 데이터 로드
  useEffect(() => {
    if (isEditMode && orderId) {
      const order = salesOrders.find(o => o.id === orderId);
      if (order) {
        setOrderNumber(order.orderNumber);
        setCustomerName(order.customerName);
        setProjectName(order.projectName);
        setOrderDate(order.orderDate);
        setDeliveryDate(order.deliveryDate);
        setTotalAmount(order.totalAmount);
        setOrderStatus(order.status);
        
        // 제품 목록
        if (order.items) {
          const mappedProducts: ProductItem[] = order.items.map((item, index) => ({
            id: item.id,
            no: index + 1,
            itemCode: "",
            itemName: item.itemName,
            quantity: item.quantity,
            unitPrice: item.unitPrice,
            totalPrice: item.totalPrice,
            unit: "EA",
            note: ""
          }));
          setProducts(mappedProducts);
        }
        
        // 분할 출하 정보
        if (order.shippingSchedules && order.shippingSchedules.length > 0) {
          setHasMultipleShipping(true);
          setShippingSchedules(order.shippingSchedules);
        }
      }
    }
  }, [isEditMode, orderId, salesOrders]);

  // 제품 추가
  const handleAddProduct = () => {
    const newProduct: ProductItem = {
      id: Date.now().toString(),
      no: products.length + 1,
      itemCode: "",
      itemName: "",
      quantity: 0,
      unitPrice: 0,
      totalPrice: 0,
      unit: "EA",
      note: ""
    };
    setProducts([...products, newProduct]);
  };

  // 제품 삭제
  const handleRemoveProduct = (id: string) => {
    setProducts(products.filter(p => p.id !== id));
  };

  // 제품 정보 변경
  const handleProductChange = (id: string, field: keyof ProductItem, value: any) => {
    setProducts(products.map(p => {
      if (p.id === id) {
        const updated = { ...p, [field]: value };
        // 수량 또는 단가 변경 시 총액 자동 계산
        if (field === 'quantity' || field === 'unitPrice') {
          updated.totalPrice = updated.quantity * updated.unitPrice;
        }
        return updated;
      }
      return p;
    }));
  };

  // 총 수량 계산
  const getTotalQuantity = () => {
    return products.reduce((sum, p) => sum + (p.quantity || 0), 0);
  };

  // 총 금액 계산
  const calculateTotalAmount = () => {
    return products.reduce((sum, p) => sum + (p.totalPrice || 0), 0);
  };

  // 저장
  const handleSave = () => {
    // 유효성 검사
    if (!customerName) {
      toast.error("고객사명을 입력해주세요");
      return;
    }

    if (!projectName) {
      toast.error("프로젝트명을 입력해주세요");
      return;
    }

    if (products.length === 0) {
      toast.error("제품을 추가해주세요");
      return;
    }

    if (hasMultipleShipping && shippingSchedules.length === 0) {
      toast.error("출하 일정을 추가해주세요");
      return;
    }

    // 분할 출하 수량 검증
    if (hasMultipleShipping) {
      const totalScheduledQty = shippingSchedules.reduce((sum, s) => sum + s.quantity, 0);
      const totalProductQty = getTotalQuantity();
      
      if (totalScheduledQty > totalProductQty) {
        toast.error("출하 일정의 총 수량이 주문 수량을 초과할 수 없습니다");
        return;
      }
    }

    const totalQty = getTotalQuantity();
    const calculatedTotal = calculateTotalAmount();

    // 수주 데이터 생성
    const salesOrderData = {
      id: isEditMode ? orderId! : `order-${Date.now()}`,
      orderNumber: isEditMode ? orderNumber : `SO-${new Date().toISOString().split('T')[0].replace(/-/g, '')}-${String(salesOrders.length + 1).padStart(3, '0')}`,
      quoteId: selectedQuote?.id,
      quoteNumber: selectedQuote?.quoteNumber,
      customerName,
      projectName,
      siteId: siteId || undefined,
      siteName: siteName || undefined,
      orderDate,
      deliveryDate: hasMultipleShipping && shippingSchedules.length > 0 
        ? shippingSchedules[shippingSchedules.length - 1].scheduledDate 
        : deliveryDate,
      totalAmount: calculatedTotal > 0 ? calculatedTotal : totalAmount,
      totalQuantity: totalQty,
      shippedQuantity: 0,
      remainingQuantity: totalQty,
      status: orderStatus,
      items: products.map(p => ({
        id: p.id,
        itemName: p.itemName,
        quantity: p.quantity,
        unitPrice: p.unitPrice,
        totalPrice: p.totalPrice
      })),
      shippingSchedules: hasMultipleShipping ? shippingSchedules : undefined,
      hasMultipleShipping
    };

    if (isEditMode) {
      updateSalesOrder(salesOrderData);
      toast.success("수주가 수정되었습니다");
    } else {
      addSalesOrder(salesOrderData);
      toast.success("수주가 등록되었습니다");
    }
    
    onBack();
  };

  const handleCancel = () => {
    onBack();
  };

  // 확정된 견적만 필터링 및 검색
  const approvedQuotes = quotes
    .filter(q => q.status === 'finalized')
    .filter(q => {
      if (!quoteSearchTerm) return true;
      const searchLower = quoteSearchTerm.toLowerCase();
      return (
        q.quoteNumber.toLowerCase().includes(searchLower) ||
        q.customerName.toLowerCase().includes(searchLower) ||
        q.projectName?.toLowerCase().includes(searchLower)
      );
    });

  return (
    <ResponsiveFormTemplate
      title="수주 등록"
      description="견적을 기반으로 수주를 등록합니다"
      icon={ShoppingCart}
      onSave={handleSave}
      onCancel={handleCancel}
      saveText={isEditMode ? "수정" : "저장"}
      cancelText="취소"
      maxWidth="2xl"
      showRequiredLegend={true}
      isEditMode={isEditMode}
    >
      {/* 견적 불러오기 섹션 */}
      {!isEditMode && (
        <FormSection title="견적 불러오기" icon={FileSearch}>
          {selectedQuote ? (
            <div className="space-y-4">
              {/* 선택된 견적 정보 카드 */}
              <div className="border rounded-lg p-4 bg-blue-50 dark:bg-blue-950/20 border-blue-200">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <Badge className="bg-blue-600">선택된 견적</Badge>
                      <span className="font-mono text-sm">{selectedQuote.quoteNumber}</span>
                    </div>
                    <div className="text-sm text-muted-foreground">
                      {selectedQuote.quoteDate} 작성
                    </div>
                  </div>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => {
                      setSelectedQuote(null);
                      setProducts([]);
                      toast.info("견적 선택이 해제되었습니다");
                    }}
                  >
                    <X className="h-3.5 w-3.5 mr-1" />
                    선택 해제
                  </Button>
                </div>
                
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3 text-sm">
                  <div>
                    <div className="text-muted-foreground mb-1">고객사</div>
                    <div>{selectedQuote.customerName}</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground mb-1">프로젝트</div>
                    <div>{selectedQuote.projectName}</div>
                  </div>
                  <div>
                    <div className="text-muted-foreground mb-1">견적금액</div>
                    <div>
                      {(selectedQuote.totalAmount || selectedQuote.amount || 0).toLocaleString()}원
                    </div>
                  </div>
                </div>
                
                {selectedQuote.bomCalculations && selectedQuote.bomCalculations.length > 0 && (
                  <div className="mt-3 pt-3 border-t border-blue-200">
                    <div className="text-xs text-blue-700 dark:text-blue-300 flex items-center gap-1">
                      <Package className="h-3.5 w-3.5" />
                      BOM 계산 결과 {selectedQuote.bomCalculations.length}개 품목 자동 반영됨
                    </div>
                  </div>
                )}
              </div>
              
              {/* 다른 견적 선택 버튼 */}
              <Dialog open={showQuoteDialog} onOpenChange={setShowQuoteDialog}>
                <DialogTrigger asChild>
                  <Button variant="outline" className="w-full">
                    <Search className="h-4 w-4 mr-2" />
                    다른 견적 선택
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-5xl max-h-[85vh] overflow-y-auto">
                  <DialogHeader>
                    <DialogTitle className="flex items-center gap-2">
                      <FileSearch className="h-5 w-5" />
                      견적 선택
                    </DialogTitle>
                  </DialogHeader>
                  
                  {/* 검색 영역 */}
                  <div className="mt-4 space-y-4">
                    <div className="flex items-center gap-2">
                      <Search className="h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="견적번호, 고객사명, 프로젝트명으로 검색..."
                        value={quoteSearchTerm}
                        onChange={(e) => setQuoteSearchTerm(e.target.value)}
                        className="flex-1"
                      />
                      {quoteSearchTerm && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => setQuoteSearchTerm("")}
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      )}
                    </div>

                    {/* 견적 목록 */}
                    {approvedQuotes.length === 0 ? (
                      <div className="text-center py-12 text-muted-foreground">
                        <FileSearch className="h-12 w-12 mx-auto mb-4 opacity-50" />
                        <p className="text-lg">
                          {quoteSearchTerm 
                            ? "검색 결과가 없습니다" 
                            : "승인된 견적이 없습니다"}
                        </p>
                        <p className="text-sm mt-2">
                          {quoteSearchTerm 
                            ? "다른 검색어를 입력해보세요" 
                            : "견적관리에서 견적을 승인해주세요"}
                        </p>
                      </div>
                    ) : (
                      <>
                        <div className="text-sm text-muted-foreground mb-2">
                          총 {approvedQuotes.length}개의 견적
                        </div>
                        <div className="border rounded-lg overflow-hidden">
                          <Table>
                            <TableHeader>
                              <TableRow className="bg-muted/50">
                                <TableHead className="w-[140px]">견적번호</TableHead>
                                <TableHead className="w-[150px]">고객사</TableHead>
                                <TableHead>프로젝트명</TableHead>
                                <TableHead className="w-[100px]">견적일</TableHead>
                                <TableHead className="w-[120px] text-right">금액</TableHead>
                                <TableHead className="w-[80px]">품목수</TableHead>
                                <TableHead className="w-[80px]">상태</TableHead>
                                <TableHead className="w-[80px]">선택</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {approvedQuotes.map((quote) => {
                                const itemCount = quote.bomCalculations?.length || 
                                                quote.calculationRows?.length || 
                                                (quote.productCode ? 1 : 0);
                                return (
                                  <TableRow key={quote.id} className="hover:bg-muted/30">
                                    <TableCell className="font-mono text-xs">{quote.quoteNumber}</TableCell>
                                    <TableCell>{quote.customerName}</TableCell>
                                    <TableCell>
                                      <div>
                                        <div>{quote.projectName}</div>
                                        {quote.site && (
                                          <div className="text-xs text-muted-foreground mt-0.5">
                                            📍 {quote.site}
                                          </div>
                                        )}
                                      </div>
                                    </TableCell>
                                    <TableCell className="text-xs">{quote.quoteDate}</TableCell>
                                    <TableCell className="text-right">
                                      {(quote.totalAmount || quote.amount || 0).toLocaleString()}원
                                    </TableCell>
                                    <TableCell className="text-center">
                                      {itemCount > 0 ? (
                                        <Badge variant="outline" className="text-xs">
                                          {itemCount}개
                                        </Badge>
                                      ) : (
                                        <span className="text-xs text-muted-foreground">-</span>
                                      )}
                                    </TableCell>
                                    <TableCell>
                                      <Badge variant={
                                        quote.status === 'finalized' ? 'default' : 
                                        quote.status === 'approved' ? 'default' : 
                                        'secondary'
                                      }>
                                        {quote.status === 'finalized' ? '확정' :
                                         quote.status === 'approved' ? '승인' : 
                                         '발송'}
                                      </Badge>
                                    </TableCell>
                                    <TableCell>
                                      <Button
                                        size="sm"
                                        onClick={() => handleLoadQuote(quote)}
                                        className="h-8"
                                      >
                                        선택
                                      </Button>
                                    </TableCell>
                                  </TableRow>
                                );
                              })}
                            </TableBody>
                          </Table>
                        </div>
                      </>
                    )}
                  </div>
                </DialogContent>
              </Dialog>
            </div>
          ) : (
            <Dialog open={showQuoteDialog} onOpenChange={setShowQuoteDialog}>
              <DialogTrigger asChild>
                <Button variant="outline" size="lg" className="w-full h-20 border-dashed">
                  <div className="flex flex-col items-center gap-2">
                    <div className="flex items-center gap-2">
                      <Search className="h-5 w-5" />
                      <span>견적 선택</span>
                    </div>
                    <span className="text-xs text-muted-foreground">
                      승인된 견적을 불러와서 자동으로 수주서를 작성할 수 있습니다
                    </span>
                  </div>
                </Button>
              </DialogTrigger>
              <DialogContent className="max-w-5xl max-h-[85vh] overflow-y-auto">
                <DialogHeader>
                  <DialogTitle className="flex items-center gap-2">
                    <FileSearch className="h-5 w-5" />
                    견적 선택
                  </DialogTitle>
                </DialogHeader>
                
                {/* 검색 영역 */}
                <div className="mt-4 space-y-4">
                  <div className="flex items-center gap-2">
                    <Search className="h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="견적번호, 고객사명, 프로젝트명으로 검색..."
                      value={quoteSearchTerm}
                      onChange={(e) => setQuoteSearchTerm(e.target.value)}
                      className="flex-1"
                    />
                    {quoteSearchTerm && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setQuoteSearchTerm("")}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    )}
                  </div>

                  {/* 견적 목록 */}
                  {approvedQuotes.length === 0 ? (
                    <div className="text-center py-12 text-muted-foreground">
                      <FileSearch className="h-12 w-12 mx-auto mb-4 opacity-50" />
                      <p className="text-lg">
                        {quoteSearchTerm 
                          ? "검색 결과가 없습니다" 
                          : "승인된 견적이 없습니다"}
                      </p>
                      <p className="text-sm mt-2">
                        {quoteSearchTerm 
                          ? "다른 검색어를 입력해보세요" 
                          : "견적관리에서 견적을 승인해주세요"}
                      </p>
                    </div>
                  ) : (
                    <>
                      <div className="text-sm text-muted-foreground mb-2">
                        총 {approvedQuotes.length}개의 견적
                      </div>
                      <div className="border rounded-lg overflow-hidden">
                        <Table>
                          <TableHeader>
                            <TableRow className="bg-muted/50">
                              <TableHead className="w-[140px]">견적번호</TableHead>
                              <TableHead className="w-[150px]">고객사</TableHead>
                              <TableHead>프로젝트명</TableHead>
                              <TableHead className="w-[100px]">견적일</TableHead>
                              <TableHead className="w-[120px] text-right">금액</TableHead>
                              <TableHead className="w-[80px]">품목수</TableHead>
                              <TableHead className="w-[80px]">상태</TableHead>
                              <TableHead className="w-[80px]">선택</TableHead>
                            </TableRow>
                          </TableHeader>
                          <TableBody>
                            {approvedQuotes.map((quote) => {
                              const itemCount = quote.bomCalculations?.length || 
                                              quote.calculationRows?.length || 
                                              (quote.productCode ? 1 : 0);
                              return (
                                <TableRow key={quote.id} className="hover:bg-muted/30">
                                  <TableCell className="font-mono text-xs">{quote.quoteNumber}</TableCell>
                                  <TableCell>{quote.customerName}</TableCell>
                                  <TableCell>
                                    <div>
                                      <div>{quote.projectName}</div>
                                      {quote.site && (
                                        <div className="text-xs text-muted-foreground mt-0.5">
                                          📍 {quote.site}
                                        </div>
                                      )}
                                    </div>
                                  </TableCell>
                                  <TableCell className="text-xs">{quote.quoteDate}</TableCell>
                                  <TableCell className="text-right">
                                    {(quote.totalAmount || quote.amount || 0).toLocaleString()}원
                                  </TableCell>
                                  <TableCell className="text-center">
                                    {itemCount > 0 ? (
                                      <Badge variant="outline" className="text-xs">
                                        {itemCount}개
                                      </Badge>
                                    ) : (
                                      <span className="text-xs text-muted-foreground">-</span>
                                    )}
                                  </TableCell>
                                  <TableCell>
                                    <Badge variant={
                                      quote.status === 'finalized' ? 'default' : 
                                      quote.status === 'approved' ? 'default' : 
                                      'secondary'
                                    }>
                                      {quote.status === 'finalized' ? '확정' :
                                       quote.status === 'approved' ? '승인' : 
                                       '발송'}
                                    </Badge>
                                  </TableCell>
                                  <TableCell>
                                    <Button
                                      size="sm"
                                      onClick={() => handleLoadQuote(quote)}
                                      className="h-8"
                                    >
                                      선택
                                    </Button>
                                  </TableCell>
                                </TableRow>
                              );
                            })}
                          </TableBody>
                        </Table>
                      </div>
                    </>
                  )}
                </div>
              </DialogContent>
            </Dialog>
          )}
        </FormSection>
      )}

      {/* 기본 정보 섹션 */}
      <FormSection title="기본 정보" icon={Building}>
        <FormFieldGrid columns={2}>
          <FormField label="수주일" required>
            <Input
              type="date"
              value={orderDate}
              onChange={(e) => setOrderDate(e.target.value)}
            />
          </FormField>

          <FormField label="납품 예정일" required>
            <Input
              type="date"
              value={deliveryDate}
              onChange={(e) => setDeliveryDate(e.target.value)}
            />
          </FormField>

          <FormField label="고객사명" required>
            <Input
              value={customerName}
              onChange={(e) => setCustomerName(e.target.value)}
              placeholder="고객사명을 입력하세요"
            />
          </FormField>

          <FormField label="프로젝트명" required>
            <Input
              value={projectName}
              onChange={(e) => setProjectName(e.target.value)}
              placeholder="프로젝트명을 입력하세요"
            />
          </FormField>

          <FormField label="현장">
            <Select value={siteId} onValueChange={(value) => {
              setSiteId(value);
              const selectedSite = sites.find(s => s.id === value);
              if (selectedSite) {
                setSiteName(selectedSite.siteName);
              }
            }}>
              <SelectTrigger>
                <SelectValue placeholder="현장을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="none">선택 안 함</SelectItem>
                {sites.map((site) => (
                  <SelectItem key={site.id} value={site.id}>
                    {site.siteName} ({site.siteCode})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </FormField>

          <FormField label="수주 상태">
            <Select value={orderStatus} onValueChange={(value: any) => setOrderStatus(value)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="pending">대기</SelectItem>
                <SelectItem value="confirmed">확정</SelectItem>
                <SelectItem value="production">생산중</SelectItem>
                <SelectItem value="shipping">출하중</SelectItem>
                <SelectItem value="completed">완료</SelectItem>
                <SelectItem value="cancelled">취소</SelectItem>
              </SelectContent>
            </Select>
          </FormField>
        </FormFieldGrid>
      </FormSection>

      {/* 고객사 정보 섹션 */}
      <FormSection title="고객사 정보" icon={User}>
        <FormFieldGrid columns={3}>
          <FormField label="담당 영업">
            <Input
              value={salesPerson}
              onChange={(e) => setSalesPerson(e.target.value)}
              placeholder="담당 영업을 입력하세요"
            />
          </FormField>

          <FormField label="연락처">
            <Input
              value={clientPhone}
              onChange={(e) => setClientPhone(e.target.value)}
              placeholder="010-0000-0000"
            />
          </FormField>

          <FormField label="고객사 담당자">
            <Input
              value={clientContact}
              onChange={(e) => setClientContact(e.target.value)}
              placeholder="담당자명을 입력하세요"
            />
          </FormField>
        </FormFieldGrid>
      </FormSection>

      {/* 제품 목록 섹션 */}
      <FormSection title="제품 목록" icon={Package}>
        <div className="space-y-4">
          <Button onClick={handleAddProduct} variant="outline" className="w-full">
            <Plus className="h-4 w-4 mr-2" />
            제품 추가
          </Button>

          <div className="border rounded-lg overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow className="bg-muted/50">
                  <TableHead className="w-[60px]">No.</TableHead>
                  <TableHead className="w-[120px]">품목코드</TableHead>
                  <TableHead>품목명</TableHead>
                  <TableHead className="w-[100px]">수량</TableHead>
                  <TableHead className="w-[80px]">단위</TableHead>
                  <TableHead className="w-[120px]">단가</TableHead>
                  <TableHead className="w-[120px]">금액</TableHead>
                  <TableHead className="w-[150px]">비고</TableHead>
                  <TableHead className="w-[80px]">삭제</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {products.map((product) => (
                  <TableRow key={product.id}>
                    <TableCell>{product.no}</TableCell>
                    <TableCell>
                      <Input
                        value={product.itemCode}
                        onChange={(e) => handleProductChange(product.id, 'itemCode', e.target.value)}
                        placeholder="코드"
                        className="h-8"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={product.itemName}
                        onChange={(e) => handleProductChange(product.id, 'itemName', e.target.value)}
                        placeholder="품목명"
                        className="h-8"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        type="number"
                        value={product.quantity}
                        onChange={(e) => handleProductChange(product.id, 'quantity', Number(e.target.value))}
                        className="h-8"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        value={product.unit}
                        onChange={(e) => handleProductChange(product.id, 'unit', e.target.value)}
                        className="h-8"
                      />
                    </TableCell>
                    <TableCell>
                      <Input
                        type="number"
                        value={product.unitPrice}
                        onChange={(e) => handleProductChange(product.id, 'unitPrice', Number(e.target.value))}
                        className="h-8"
                      />
                    </TableCell>
                    <TableCell className="text-right">
                      {product.totalPrice.toLocaleString()}원
                    </TableCell>
                    <TableCell>
                      <Input
                        value={product.note}
                        onChange={(e) => handleProductChange(product.id, 'note', e.target.value)}
                        placeholder="비고"
                        className="h-8"
                      />
                    </TableCell>
                    <TableCell>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleRemoveProduct(product.id)}
                        className="h-8 w-8 p-0"
                      >
                        <Trash2 className="h-4 w-4 text-red-500" />
                      </Button>
                    </TableCell>
                  </TableRow>
                ))}
                {products.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={9} className="text-center py-8 text-muted-foreground">
                      제품을 추가해주세요
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>

          <div className="flex justify-end">
            <div className="space-y-2">
              <div className="flex items-center gap-4">
                <span className="text-sm">총 수량:</span>
                <span>{getTotalQuantity().toLocaleString()}</span>
              </div>
              <div className="flex items-center gap-4">
                <span className="text-sm">총 금액:</span>
                <span className="text-lg">{calculateTotalAmount().toLocaleString()}원</span>
              </div>
            </div>
          </div>
        </div>
      </FormSection>

      {/* 분할 출하 관리 섹션 */}
      <FormSection 
        title="분할 출하 관리" 
        icon={Layers}
      >
        <div className="space-y-4">
          <div className="flex items-center gap-2">
            <Switch
              checked={hasMultipleShipping}
              onCheckedChange={(checked) => {
                setHasMultipleShipping(checked);
                if (!checked) {
                  setShippingSchedules([]);
                }
              }}
            />
            <Label>분할 출하</Label>
          </div>

          {hasMultipleShipping && (
            <>
              <Button onClick={handleAddShippingSchedule} variant="outline" className="w-full">
                <Plus className="h-4 w-4 mr-2" />
                출하 일정 추가
              </Button>

              <div className="border rounded-lg overflow-hidden">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-muted/50">
                      <TableHead className="w-[60px]">차수</TableHead>
                      <TableHead className="w-[150px]">출하 예정일</TableHead>
                      <TableHead className="w-[100px]">수량</TableHead>
                      <TableHead>배송지</TableHead>
                      <TableHead className="w-[120px]">수신자</TableHead>
                      <TableHead className="w-[120px]">연락처</TableHead>
                      <TableHead className="w-[150px]">비고</TableHead>
                      <TableHead className="w-[80px]">삭제</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {shippingSchedules.map((schedule) => (
                      <TableRow key={schedule.id}>
                        <TableCell>{schedule.scheduleNumber}차</TableCell>
                        <TableCell>
                          <Input
                            type="date"
                            value={schedule.scheduledDate}
                            onChange={(e) => handleUpdateShippingSchedule(schedule.id, 'scheduledDate', e.target.value)}
                            className="h-8"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            type="number"
                            value={schedule.quantity}
                            onChange={(e) => handleUpdateShippingSchedule(schedule.id, 'quantity', Number(e.target.value))}
                            className="h-8"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.shippingAddress}
                            onChange={(e) => handleUpdateShippingSchedule(schedule.id, 'shippingAddress', e.target.value)}
                            placeholder="배송지"
                            className="h-8"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.receiverName}
                            onChange={(e) => handleUpdateShippingSchedule(schedule.id, 'receiverName', e.target.value)}
                            placeholder="수신자"
                            className="h-8"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.receiverPhone}
                            onChange={(e) => handleUpdateShippingSchedule(schedule.id, 'receiverPhone', e.target.value)}
                            placeholder="연락처"
                            className="h-8"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={schedule.note}
                            onChange={(e) => handleUpdateShippingSchedule(schedule.id, 'note', e.target.value)}
                            placeholder="비고"
                            className="h-8"
                          />
                        </TableCell>
                        <TableCell>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleRemoveShippingSchedule(schedule.id)}
                            className="h-8 w-8 p-0"
                          >
                            <Trash2 className="h-4 w-4 text-red-500" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                    {shippingSchedules.length === 0 && (
                      <TableRow>
                        <TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
                          출하 일정을 추가해주세요
                        </TableCell>
                      </TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </>
          )}
        </div>
      </FormSection>

      {/* 배송지 정보 섹션 */}
      <FormSection title="배송지 정보" icon={Truck}>
        <div className="space-y-4">
          <FormField label="배달 방법">
            <RadioGroup value={shippingMethod} onValueChange={setShippingMethod}>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="직접배송" id="direct" />
                <Label htmlFor="direct">직접배송</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="택배" id="parcel" />
                <Label htmlFor="parcel">택배배송</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="수거" id="pickup" />
                <Label htmlFor="pickup">수거배송</Label>
              </div>
            </RadioGroup>
          </FormField>

          {!hasMultipleShipping && (
            <>
              <FormFieldGrid columns={2}>
                <FormField label="수신자명">
                  <Input
                    value={receiverName}
                    onChange={(e) => setReceiverName(e.target.value)}
                    placeholder="수신자명"
                  />
                </FormField>
                <FormField label="전화번호">
                  <Input
                    value={receiverPhone}
                    onChange={(e) => setReceiverPhone(e.target.value)}
                    placeholder="010-0000-0000"
                  />
                </FormField>
              </FormFieldGrid>

              <FormField label="배송지 주소">
                <Input
                  value={shippingAddress}
                  onChange={(e) => setShippingAddress(e.target.value)}
                  placeholder="주소를 입력하세요"
                />
              </FormField>
            </>
          )}
        </div>
      </FormSection>

      {/* 결제 정보 섹션 */}
      <FormSection title="결제 정보" icon={CreditCard}>
        <FormFieldGrid columns={2}>
          <FormField label="판매 방법">
            <RadioGroup value={paymentType} onValueChange={setPaymentType}>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="현금결제(선)" id="cash-pre" />
                <Label htmlFor="cash-pre">현금결제(선)</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="카드결제" id="card" />
                <Label htmlFor="card">카드결제</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="외상결제" id="credit" />
                <Label htmlFor="credit">외상결제(후)</Label>
              </div>
            </RadioGroup>
          </FormField>

          <FormField label="세금계산서 발행">
            <RadioGroup value={billingType} onValueChange={setBillingType}>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="세금계산서" id="tax-invoice" />
                <Label htmlFor="tax-invoice">세금계산서</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="현금영수증" id="cash-receipt" />
                <Label htmlFor="cash-receipt">현금영수증</Label>
              </div>
              <div className="flex items-center space-x-2">
                <RadioGroupItem value="미발행" id="none" />
                <Label htmlFor="none">미발행</Label>
              </div>
            </RadioGroup>
          </FormField>
        </FormFieldGrid>
      </FormSection>

      {/* 특이사항 섹션 */}
      <FormSection title="특이사항" icon={FileText}>
        <div className="space-y-4">
          <FormField label="내부 특이사항">
            <Textarea
              value={internalMemo}
              onChange={(e) => setInternalMemo(e.target.value)}
              placeholder="내부 특이사항을 입력하세요"
              rows={3}
            />
          </FormField>
          <FormField label="발주자 관련 메모">
            <Textarea
              value={deliveryMemo}
              onChange={(e) => setDeliveryMemo(e.target.value)}
              placeholder="발주자 관련 메모를 입력하세요"
              rows={2}
            />
          </FormField>
          <FormField label="배송 관련 특이사항">
            <Textarea
              value={shippingMemo}
              onChange={(e) => setShippingMemo(e.target.value)}
              placeholder="배송 관련 특이사항을 입력하세요"
              rows={2}
            />
          </FormField>
        </div>
      </FormSection>
    </ResponsiveFormTemplate>
  );
}
