import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Textarea } from "./ui/textarea";
import { Badge } from "./ui/badge";
import { Separator } from "./ui/separator";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "./ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { 
  DollarSign, 
  ArrowLeft, 
  Save,
  Package,
  Calendar,
  TrendingUp,
  AlertCircle,
  Calculator,
  History,
  CheckCircle2,
  Edit2,
  Lock
} from "lucide-react";
import { toast } from "sonner@2.0.3";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";
import { FormActions } from "./organisms/FormActions";
import { RevisionHistoryDialog, RevisionBadge, RevisionDisplayConfig } from "./RevisionHistoryViewer";

// 단가 관리 데이터 인터페이스
export interface PricingRevision {
  revisionNumber: number;
  revisionDate: string;
  revisionBy: string;
  revisionReason?: string;
  previousData: PricingData;
}

export interface PricingData {
  id: string;
  itemId: string;
  itemCode: string;
  itemName: string;
  itemType: string;
  specification?: string;
  unit: string;
  effectiveDate: string;
  receiveDate?: string; // 입고일
  author?: string; // 작성자
  purchasePrice?: number;
  processingCost?: number;
  loss?: number; // LOSS(%)
  roundingRule?: 'round' | 'ceil' | 'floor'; // 반올림 규칙
  roundingUnit?: number; // 반올림 단위 (예: 1, 10, 100, 1000)
  marginRate?: number;
  salesPrice?: number;
  supplier?: string;
  note?: string;
  
  currentRevision: number;
  isFinal: boolean;
  revisions?: PricingRevision[];
  finalizedDate?: string;
  finalizedBy?: string;
  status: 'draft' | 'active' | 'inactive' | 'finalized';
  
  createdAt: string;
  createdBy: string;
  updatedAt?: string;
  updatedBy?: string;
}

interface PricingWriteProps {
  onSave: (data: PricingData, isRevision?: boolean, revisionReason?: string) => void;
  onCancel: () => void;
  editingPricing?: PricingData | null;
  itemData?: {
    id: string;
    itemCode: string;
    itemName: string;
    itemType: string;
    specification?: string;
    unit: string;
  };
}

export function PricingWrite({ onSave, onCancel, editingPricing, itemData }: PricingWriteProps) {
  const isEditMode = !!editingPricing;
  const currentData = editingPricing;

  // 폼 상태
  const [effectiveDate, setEffectiveDate] = useState(currentData?.effectiveDate || new Date().toISOString().split('T')[0]);
  const [receiveDate, setReceiveDate] = useState(currentData?.receiveDate || "");
  const [author, setAuthor] = useState(currentData?.author || "");
  const [purchasePrice, setPurchasePrice] = useState(currentData?.purchasePrice || 0);
  const [processingCost, setProcessingCost] = useState(currentData?.processingCost || 0);
  const [loss, setLoss] = useState(currentData?.loss || 0);
  const [roundingRule, setRoundingRule] = useState(currentData?.roundingRule || 'round');
  const [roundingUnit, setRoundingUnit] = useState(currentData?.roundingUnit || 1);
  const [marginRate, setMarginRate] = useState(currentData?.marginRate || 0);
  const [salesPrice, setSalesPrice] = useState(currentData?.salesPrice || 0);
  const [supplier, setSupplier] = useState(currentData?.supplier || "");
  const [note, setNote] = useState(currentData?.note || "");
  const [unit, setUnit] = useState(currentData?.unit || itemData?.unit || "EA");

  // 필드 에러 상태
  const [errors, setErrors] = useState<Record<string, boolean>>({});

  // 이력 관리 상태
  const [showHistoryDialog, setShowHistoryDialog] = useState(false);
  const [showRevisionDialog, setShowRevisionDialog] = useState(false);
  const [revisionReason, setRevisionReason] = useState("");
  const [showFinalizeDialog, setShowFinalizeDialog] = useState(false);

  // 품목 정보 (신규 등록 시 itemData 사용, 수정 시 currentData 사용)
  const displayItemCode = currentData?.itemCode || itemData?.itemCode || "";
  const displayItemName = currentData?.itemName || itemData?.itemName || "";
  const displayItemType = currentData?.itemType || itemData?.itemType || "";
  const displaySpecification = currentData?.specification || itemData?.specification || "";
  const displayUnit = currentData?.unit || itemData?.unit || "";

  // 품목 타입 라벨
  const getItemTypeLabel = (type: string) => {
    switch (type) {
      case 'RM': return '원자재';
      case 'PT': return '부품';
      case 'FG': return '제품';
      case 'SM': return '부자재';
      case 'CS': return '소모품';
      case 'BENDING': return '절곡물';
      default: return type;
    }
  };

  // 반올림 규칙 적용 함수
  const applyRounding = (value: number, rule: 'round' | 'ceil' | 'floor', unit: number): number => {
    if (unit <= 0) return Math.round(value); // 단위가 없으면 정수로 반올림
    
    switch (rule) {
      case 'ceil':
        return Math.ceil(value / unit) * unit;
      case 'floor':
        return Math.floor(value / unit) * unit;
      case 'round':
      default:
        return Math.round(value / unit) * unit;
    }
  };

  // LOSS율 적용한 원가 계산 (정수로 반올림)
  const calculateCostWithLoss = (): number => {
    const basePrice = (purchasePrice || 0) + (processingCost || 0);
    const lossRate = (loss || 0) / 100;
    const costWithLoss = basePrice * (1 + lossRate);
    return Math.round(costWithLoss); // 소수점 제거
  };

  // 마진율 변경 시 판매가 자동 계산 (LOSS와 반올림 적용)
  const handleMarginRateChange = (rate: number) => {
    setMarginRate(rate);
    const costWithLoss = calculateCostWithLoss();
    if (costWithLoss > 0) {
      const calculatedPrice = costWithLoss * (1 + rate / 100);
      const roundedPrice = applyRounding(calculatedPrice, roundingRule, roundingUnit);
      setSalesPrice(Math.round(roundedPrice)); // 최종 정수로 변환
    } else {
      setSalesPrice(0);
    }
  };

  // 판매가 변경 시 마진율 자동 계산 (LOSS 고려)
  const handleSalesPriceChange = (price: number) => {
    setSalesPrice(price);
    const costWithLoss = calculateCostWithLoss();
    if (costWithLoss > 0) {
      const calculatedMarginRate = ((price - costWithLoss) / costWithLoss) * 100;
      setMarginRate(parseFloat(calculatedMarginRate.toFixed(1)));
    } else {
      setMarginRate(0);
    }
  };

  // 매입단가, 가공비, LOSS율, 반올림 규칙 변경 시 판매가 자동 재계산
  useEffect(() => {
    // 무한 루프 방지: marginRate가 있고, 실제로 값이 변경되었을 때만 재계산
    if (marginRate > 0 && (purchasePrice > 0 || processingCost > 0)) {
      const costWithLoss = calculateCostWithLoss();
      if (costWithLoss > 0) {
        const calculatedPrice = costWithLoss * (1 + marginRate / 100);
        const roundedPrice = applyRounding(calculatedPrice, roundingRule, roundingUnit);
        const finalPrice = Math.round(roundedPrice);
        
        // 현재 판매가와 다를 때만 업데이트 (무한 루프 방지)
        if (finalPrice !== salesPrice) {
          setSalesPrice(finalPrice);
        }
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [purchasePrice, processingCost, loss, roundingRule, roundingUnit]);

  // 유효성 검사
  const validateForm = () => {
    const newErrors: Record<string, boolean> = {};

    if (!effectiveDate) newErrors.effectiveDate = true;
    if (purchasePrice <= 0 && salesPrice <= 0) {
      newErrors.purchasePrice = true;
      newErrors.salesPrice = true;
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 저장 처리 (신규 또는 일반 수정)
  const handleSave = () => {
    if (!validateForm()) {
      toast.error("필수 항목을 입력해주세요.");
      return;
    }

    // 수정 모드이고 이미 리비전이 있는 경우 → 수정 이력 생성 확인
    if (isEditMode && currentData && (currentData.currentRevision > 0 || currentData.isFinal)) {
      setShowRevisionDialog(true);
      return;
    }

    const pricingData: PricingData = {
      id: currentData?.id || `PR-${Date.now()}`,
      itemId: currentData?.itemId || itemData?.id || "",
      itemCode: displayItemCode,
      itemName: displayItemName,
      itemType: displayItemType,
      specification: displaySpecification,
      unit: displayUnit,
      effectiveDate,
      receiveDate,
      author,
      purchasePrice: purchasePrice || undefined,
      processingCost: processingCost || undefined,
      loss: loss || undefined,
      roundingRule: roundingRule || undefined,
      roundingUnit: roundingUnit || undefined,
      marginRate: marginRate || undefined,
      salesPrice: salesPrice || undefined,
      supplier,
      note,
      
      currentRevision: currentData?.currentRevision || 0,
      isFinal: currentData?.isFinal || false,
      revisions: currentData?.revisions || [],
      status: currentData?.status || 'draft',
      
      createdAt: currentData?.createdAt || new Date().toISOString(),
      createdBy: currentData?.createdBy || "관리자",
      updatedAt: new Date().toISOString(),
      updatedBy: "관리자"
    };

    onSave(pricingData);
  };

  // 수정 이력 저장
  const handleSaveAsRevision = () => {
    if (!revisionReason.trim()) {
      toast.error("수정 사유를 입력해주세요.");
      return;
    }

    const pricingData: PricingData = {
      id: currentData?.id || `PR-${Date.now()}`,
      itemId: currentData?.itemId || itemData?.id || "",
      itemCode: displayItemCode,
      itemName: displayItemName,
      itemType: displayItemType,
      specification: displaySpecification,
      unit: displayUnit,
      effectiveDate,
      receiveDate,
      author,
      purchasePrice: purchasePrice || undefined,
      processingCost: processingCost || undefined,
      loss: loss || undefined,
      roundingRule: roundingRule || undefined,
      roundingUnit: roundingUnit || undefined,
      marginRate: marginRate || undefined,
      salesPrice: salesPrice || undefined,
      supplier,
      note,
      
      currentRevision: (currentData?.currentRevision || 0) + 1,
      isFinal: false,
      revisions: currentData?.revisions || [],
      status: 'active',
      
      createdAt: currentData?.createdAt || new Date().toISOString(),
      createdBy: currentData?.createdBy || "관리자",
      updatedAt: new Date().toISOString(),
      updatedBy: "관리자"
    };

    onSave(pricingData, true, revisionReason);
    setShowRevisionDialog(false);
    setRevisionReason("");
  };

  // 최종 확정
  const handleFinalize = () => {
    if (!currentData) return;

    const finalizedData: PricingData = {
      ...currentData,
      effectiveDate,
      receiveDate,
      author,
      purchasePrice: purchasePrice || undefined,
      processingCost: processingCost || undefined,
      loss: loss || undefined,
      roundingRule: roundingRule || undefined,
      roundingUnit: roundingUnit || undefined,
      marginRate: marginRate || undefined,
      salesPrice: salesPrice || undefined,
      supplier,
      note,
      isFinal: true,
      finalizedDate: new Date().toISOString(),
      finalizedBy: "관리자",
      status: 'finalized',
      updatedAt: new Date().toISOString(),
      updatedBy: "관리자"
    };

    onSave(finalizedData);
    setShowFinalizeDialog(false);
    toast.success("단가가 최종 확정되었습니다.");
  };

  return (
    <PageLayout>
      {/* 헤더 */}
      <PageHeader 
        title="단가 등록"
        description={isEditMode ? "품목의 단가 정보를 수정합니다" : "새로운 품목의 단가 정보를 등록합니다"}
        icon={DollarSign}
        isEditMode={isEditMode}
      />

      {/* 이력 조회 다이얼로그 */}
      <Dialog open={showHistoryDialog} onOpenChange={setShowHistoryDialog}>
        <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <History className="h-5 w-5" />
              단가 수정 이력
            </DialogTitle>
            <DialogDescription>
              {displayItemName} ({displayItemCode})의 단가 변경 이력입니다.
            </DialogDescription>
          </DialogHeader>
          
          {currentData?.revisions && currentData.revisions.length > 0 ? (
            <div className="space-y-4">
              {/* 현재 버전 */}
              <div className="border-2 border-blue-200 rounded-lg p-4 bg-blue-50">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Badge className="bg-blue-600">현재 버전</Badge>
                    <span className="font-semibold">수정 {currentData.currentRevision}차</span>
                  </div>
                  <span className="text-sm text-muted-foreground">
                    {new Date(currentData.updatedAt || currentData.createdAt).toLocaleString('ko-KR')}
                  </span>
                </div>
                <div className="grid grid-cols-4 gap-3 text-sm">
                  <div>
                    <span className="text-muted-foreground">매입단가:</span>
                    <div className="font-semibold">{currentData.purchasePrice?.toLocaleString() || '-'}원</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">가공비:</span>
                    <div className="font-semibold">{currentData.processingCost?.toLocaleString() || '-'}원</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">판매단가:</span>
                    <div className="font-semibold">{currentData.salesPrice?.toLocaleString() || '-'}원</div>
                  </div>
                  <div>
                    <span className="text-muted-foreground">마진율:</span>
                    <div className="font-semibold">{currentData.marginRate?.toFixed(1) || '-'}%</div>
                  </div>
                </div>
              </div>

              {/* 이전 버전들 */}
              {[...currentData.revisions].reverse().map((revision, index) => (
                <div key={revision.revisionNumber} className="border rounded-lg p-4">
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-2">
                      <Badge variant="outline">이전 버전</Badge>
                      <span className="font-semibold">수정 {revision.revisionNumber}차</span>
                      {revision.revisionReason && (
                        <span className="text-sm text-muted-foreground">
                          ({revision.revisionReason})
                        </span>
                      )}
                    </div>
                    <div className="text-right">
                      <div className="text-sm text-muted-foreground">
                        {new Date(revision.revisionDate).toLocaleString('ko-KR')}
                      </div>
                      <div className="text-xs text-muted-foreground">
                        by {revision.revisionBy}
                      </div>
                    </div>
                  </div>
                  <div className="grid grid-cols-4 gap-3 text-sm">
                    <div>
                      <span className="text-muted-foreground">매입단가:</span>
                      <div>{revision.previousData.purchasePrice?.toLocaleString() || '-'}원</div>
                    </div>
                    <div>
                      <span className="text-muted-foreground">가공비:</span>
                      <div>{revision.previousData.processingCost?.toLocaleString() || '-'}원</div>
                    </div>
                    <div>
                      <span className="text-muted-foreground">판매단가:</span>
                      <div>{revision.previousData.salesPrice?.toLocaleString() || '-'}원</div>
                    </div>
                    <div>
                      <span className="text-muted-foreground">마진율:</span>
                      <div>{revision.previousData.marginRate?.toFixed(1) || '-'}%</div>
                    </div>
                  </div>
                </div>
              ))}

              {/* 최초 버전 */}
              <div className="border rounded-lg p-4 bg-gray-50">
                <div className="flex items-center justify-between mb-3">
                  <div className="flex items-center gap-2">
                    <Badge variant="outline">최초 버전</Badge>
                    <span className="font-semibold">초기 등록</span>
                  </div>
                  <span className="text-sm text-muted-foreground">
                    {new Date(currentData.createdAt).toLocaleString('ko-KR')}
                  </span>
                </div>
              </div>
            </div>
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              수정 이력이 없습니다.
            </div>
          )}
        </DialogContent>
      </Dialog>

      {/* 수정 이력 생성 다이얼로그 */}
      <Dialog open={showRevisionDialog} onOpenChange={setShowRevisionDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Edit2 className="h-5 w-5" />
              수정 이력 생성
            </DialogTitle>
            <DialogDescription>
              단가 정보를 수정하시겠습니까? 수정 사유를 입력해주세요.
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div>
              <Label>수정 사유 <span className="text-red-500">*</span></Label>
              <Textarea
                value={revisionReason}
                onChange={(e) => setRevisionReason(e.target.value)}
                placeholder="예: 공급업체 단가 인상으로 인한 조정"
                rows={3}
              />
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowRevisionDialog(false)}>
              취소
            </Button>
            <Button onClick={handleSaveAsRevision} className="bg-blue-600 hover:bg-blue-700">
              <Save className="h-4 w-4 mr-2" />
              수정 이력 저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 최종 확정 다이얼로그 */}
      <Dialog open={showFinalizeDialog} onOpenChange={setShowFinalizeDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Lock className="h-5 w-5 text-purple-600" />
              최종 확정
            </DialogTitle>
            <DialogDescription>
              단가를 최종 확정하시겠습니까? 확정 후에는 수정할 수 없습니다.
            </DialogDescription>
          </DialogHeader>
          
          <div className="py-4">
            <div className="bg-purple-50 border border-purple-200 rounded-lg p-4 space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-muted-foreground">품목:</span>
                <span className="font-semibold">{displayItemName}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">매입단가:</span>
                <span className="font-semibold">{purchasePrice?.toLocaleString() || '-'}원</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">판매단가:</span>
                <span className="font-semibold">{salesPrice?.toLocaleString() || '-'}원</span>
              </div>
              <div className="flex justify-between">
                <span className="text-muted-foreground">마진율:</span>
                <span className="font-semibold">{marginRate?.toFixed(1) || '-'}%</span>
              </div>
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setShowFinalizeDialog(false)}>
              취소
            </Button>
            <Button onClick={handleFinalize} className="bg-purple-600 hover:bg-purple-700">
              <CheckCircle2 className="h-4 w-4 mr-2" />
              최종 확정
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <div className="container mx-auto px-4 py-6 max-w-5xl">
        {/* 상태 표시 */}
        {isEditMode && currentData && (
          <div className="mb-4 flex gap-2 justify-end">
            {currentData.isFinal && (
              <Badge className="bg-purple-600">
                <Lock className="h-3 w-3 mr-1" />
                최종 확정됨
              </Badge>
            )}
            {currentData.currentRevision > 0 && (
              <Badge variant="outline" className="bg-blue-50 text-blue-700">
                <History className="h-3 w-3 mr-1" />
                수정 {currentData.currentRevision}차
              </Badge>
            )}
            {currentData.status === 'active' && !currentData.isFinal && (
              <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">
                활성
              </Badge>
            )}
          </div>
        )}

        {/* 품목 정보 */}
        <Card className="mb-6 border-2 border-blue-200">
          <CardHeader className="bg-blue-50">
            <CardTitle className="flex items-center gap-2">
              <Package className="h-5 w-5 text-blue-600" />
              품목 정보
            </CardTitle>
          </CardHeader>
          <CardContent className="pt-6">
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div>
                <Label className="text-sm text-muted-foreground">품목 코드</Label>
                <div className="mt-1 font-semibold">{displayItemCode}</div>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground">품목명</Label>
                <div className="mt-1 font-semibold">{displayItemName}</div>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground">품목 유형</Label>
                <div className="mt-1">
                  <Badge variant="outline">
                    {getItemTypeLabel(displayItemType)}
                  </Badge>
                </div>
              </div>
              <div>
                <Label className="text-sm text-muted-foreground">단위</Label>
                <div className="mt-1 font-semibold">{displayUnit}</div>
              </div>
              {displaySpecification && (
                <div className="col-span-2 md:col-span-4">
                  <Label className="text-sm text-muted-foreground">규격</Label>
                  <div className="mt-1">{displaySpecification}</div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 단가 정보 */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <DollarSign className="h-5 w-5" />
              단가 정보
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 적용일 */}
            <div>
              <Label>
                적용일 <span className="text-red-500">*</span>
              </Label>
              <Input
                type="date"
                value={effectiveDate}
                onChange={(e) => {
                  setEffectiveDate(e.target.value);
                  setErrors(prev => ({ ...prev, effectiveDate: false }));
                }}
                className={errors.effectiveDate ? "border-red-500" : ""}
              />
              {errors.effectiveDate && (
                <p className="text-sm text-red-500 mt-1 flex items-center gap-1">
                  <AlertCircle className="h-3 w-3" />
                  적용일을 선택해주세요
                </p>
              )}
            </div>

            <Separator />

            {/* 공급업체 및 기본 정보 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>공급업체</Label>
                <Input
                  value={supplier}
                  onChange={(e) => setSupplier(e.target.value)}
                  placeholder="공급업체명을 입력하세요"
                />
              </div>

              <div>
                <Label>입고일</Label>
                <Input
                  type="date"
                  value={receiveDate}
                  onChange={(e) => setReceiveDate(e.target.value)}
                  placeholder="입고일 선택"
                />
              </div>

              <div>
                <Label>작성자</Label>
                <Input
                  value={author}
                  onChange={(e) => setAuthor(e.target.value)}
                  placeholder="작성자명을 입력하세요"
                />
              </div>
            </div>

            <Separator />

            {/* 입고가 및 단위 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>
                  입고가 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <Input
                    type="number"
                    value={purchasePrice || ""}
                    onChange={(e) => {
                      const value = parseInt(e.target.value) || 0;
                      setPurchasePrice(value);
                      setErrors(prev => ({ ...prev, purchasePrice: false, salesPrice: false }));
                    }}
                    placeholder="0"
                    className={errors.purchasePrice ? "border-red-500 pr-12" : "pr-12"}
                  />
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                    원
                  </span>
                </div>
              </div>

              <div>
                <Label>단위</Label>
                <Select value={unit} onValueChange={setUnit}>
                  <SelectTrigger>
                    <SelectValue placeholder="단위 선택" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="EA">EA (개)</SelectItem>
                    <SelectItem value="SET">SET (세트)</SelectItem>
                    <SelectItem value="KG">KG (킬로그램)</SelectItem>
                    <SelectItem value="G">G (그램)</SelectItem>
                    <SelectItem value="M">M (미터)</SelectItem>
                    <SelectItem value="CM">CM (센티미터)</SelectItem>
                    <SelectItem value="MM">MM (밀리미터)</SelectItem>
                    <SelectItem value="L">L (리터)</SelectItem>
                    <SelectItem value="ML">ML (밀리리터)</SelectItem>
                    <SelectItem value="BOX">BOX (박스)</SelectItem>
                    <SelectItem value="ROLL">ROLL (롤)</SelectItem>
                    <SelectItem value="SHEET">SHEET (장)</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground mt-1">
                  단가 적용 시 사용될 단위
                </p>
              </div>

              <div>
                <Label>LOSS (%)</Label>
                <div className="relative">
                  <Input
                    type="number"
                    step="0.1"
                    value={loss || ""}
                    onChange={(e) => {
                      const value = parseFloat(e.target.value) || 0;
                      setLoss(value);
                    }}
                    placeholder="0"
                    className="pr-12"
                  />
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                    %
                  </span>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  제조 과정에서 발생하는 손실율
                </p>
              </div>

              <div>
                <Label>가공비</Label>
                <div className="relative">
                  <Input
                    type="number"
                    value={processingCost || ""}
                    onChange={(e) => {
                      const value = parseInt(e.target.value) || 0;
                      setProcessingCost(value);
                    }}
                    placeholder="0"
                    className="pr-12"
                  />
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                    원
                  </span>
                </div>
              </div>
            </div>

            {/* 원가 계산 */}
            {(purchasePrice > 0 || processingCost > 0) && (
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <div className="flex items-center gap-2 mb-2">
                  <Calculator className="h-4 w-4 text-blue-600" />
                  <Label className="text-blue-900">원가 계산</Label>
                </div>
                <div className="space-y-1 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">입고가:</span>
                    <span>{(purchasePrice || 0).toLocaleString()}원</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">가공비:</span>
                    <span>{(processingCost || 0).toLocaleString()}원</span>
                  </div>
                  <Separator className="my-2" />
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">소계:</span>
                    <span>{((purchasePrice || 0) + (processingCost || 0)).toLocaleString()}원</span>
                  </div>
                  {loss && loss > 0 && (
                    <div className="flex justify-between text-orange-600">
                      <span>LOSS ({loss}%):</span>
                      <span>+{(((purchasePrice || 0) + (processingCost || 0)) * (loss / 100)).toLocaleString()}원</span>
                    </div>
                  )}
                  <Separator className="my-2" />
                  <div className="flex justify-between font-semibold text-base">
                    <span className="text-blue-900">LOSS 적용 원가:</span>
                    <span className="text-blue-600">{calculateCostWithLoss().toLocaleString()}원</span>
                  </div>
                </div>
              </div>
            )}

            <Separator />

            {/* 반올림 설정 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>반올림 규칙</Label>
                <Select value={roundingRule} onValueChange={(value: any) => setRoundingRule(value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="round">반올림</SelectItem>
                    <SelectItem value="ceil">올림</SelectItem>
                    <SelectItem value="floor">내림</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div>
                <Label>반올림 단위</Label>
                <Select value={roundingUnit?.toString()} onValueChange={(value) => setRoundingUnit(parseInt(value))}>
                  <SelectTrigger>
                    <SelectValue placeholder="선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="1">1원 단위</SelectItem>
                    <SelectItem value="10">10원 단위</SelectItem>
                    <SelectItem value="100">100원 단위</SelectItem>
                    <SelectItem value="1000">1,000원 단위</SelectItem>
                    <SelectItem value="10000">10,000원 단위</SelectItem>
                  </SelectContent>
                </Select>
                <p className="text-xs text-muted-foreground mt-1">
                  단가 계산 시 적용될 반올림 단위
                </p>
              </div>
            </div>

            <Separator />

            {/* 판매 정보 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <Label>
                  마진율 (%)
                </Label>
                <div className="relative">
                  <Input
                    type="number"
                    value={marginRate || ""}
                    onChange={(e) => {
                      const value = parseFloat(e.target.value) || 0;
                      handleMarginRateChange(value);
                    }}
                    placeholder="0"
                    className="pr-12"
                  />
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                    %
                  </span>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  마진율을 입력하면 판매단가가 자동 계산됩니다
                </p>
              </div>

              <div>
                <Label>
                  판매단가 <span className="text-red-500">*</span>
                </Label>
                <div className="relative">
                  <Input
                    type="number"
                    value={salesPrice || ""}
                    onChange={(e) => {
                      const value = parseInt(e.target.value) || 0;
                      handleSalesPriceChange(value);
                      setErrors(prev => ({ ...prev, purchasePrice: false, salesPrice: false }));
                    }}
                    placeholder="0"
                    className={errors.salesPrice ? "border-red-500 pr-12" : "pr-12"}
                  />
                  <span className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                    원
                  </span>
                </div>
                <p className="text-xs text-muted-foreground mt-1">
                  판매단가를 직접 입력하면 마진율이 자동 계산됩니다
                </p>
              </div>
            </div>

            {(errors.purchasePrice || errors.salesPrice) && (
              <p className="text-sm text-red-500 flex items-center gap-1">
                <AlertCircle className="h-3 w-3" />
                입고가 또는 판매단가 중 최소 하나를 입력해주세요
              </p>
            )}

            {/* 마진 계산 결과 */}
            {salesPrice > 0 && (purchasePrice > 0 || processingCost > 0) && (
              <div className="bg-green-50 border border-green-200 rounded-lg p-4">
                <div className="flex items-center gap-2 mb-2">
                  <TrendingUp className="h-4 w-4 text-green-600" />
                  <Label className="text-green-900">마진 계산</Label>
                </div>
                <div className="space-y-1 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">LOSS 적용 원가:</span>
                    <span>{calculateCostWithLoss().toLocaleString()}원</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">판매단가:</span>
                    <span>{salesPrice.toLocaleString()}원</span>
                  </div>
                  <Separator className="my-2" />
                  <div className="flex justify-between font-semibold text-base">
                    <span className="text-green-900">마진:</span>
                    <span className="text-green-600">
                      {(salesPrice - calculateCostWithLoss()).toLocaleString()}원 ({marginRate.toFixed(1)}%)
                    </span>
                  </div>
                </div>
              </div>
            )}

            <Separator />

            {/* 비고 */}
            <div>
              <Label>비고</Label>
              <Textarea
                value={note}
                onChange={(e) => setNote(e.target.value)}
                placeholder="비고사항을 입력하세요"
                rows={3}
              />
            </div>
          </CardContent>
        </Card>

        {/* 버튼 영역 */}
        <div className="flex gap-2 justify-between">
          <div className="flex gap-2">
            {isEditMode && currentData && currentData.revisions && currentData.revisions.length > 0 && (
              <Button
                variant="outline"
                onClick={() => setShowHistoryDialog(true)}
              >
                <History className="h-4 w-4 mr-2" />
                이력 조회 ({currentData.currentRevision}차)
              </Button>
            )}
          </div>
          <div className="flex gap-2">
            <Button
              variant="outline"
              onClick={onCancel}
              className="min-w-[100px]"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              취소
            </Button>
            {isEditMode && currentData && !currentData.isFinal && (
              <Button
                onClick={() => setShowFinalizeDialog(true)}
                className="min-w-[100px] bg-purple-600 hover:bg-purple-700"
              >
                <CheckCircle2 className="h-4 w-4 mr-2" />
                최종 확정
              </Button>
            )}
            <Button
              onClick={handleSave}
              className="min-w-[100px] bg-blue-600 hover:bg-blue-700"
              disabled={currentData?.isFinal}
            >
              <Save className="h-4 w-4 mr-2" />
              {currentData?.isFinal ? '확정됨' : '저장'}
            </Button>
          </div>
        </div>
      </div>
    </PageLayout>
  );
}