import { useState } from "react";
import { Card, CardContent } from "./ui/card";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { toast } from "sonner@2.0.3";
import { Plus, Trash2, Calculator, ArrowLeft, Save } from "lucide-react";
import { useData } from "./contexts/DataContext";
import type { ProductBOMTemplate, BOMCalculationRule } from "./contexts/DataContext";
import { PageLayout } from "./organisms/PageLayout";
import { PageHeader } from "./organisms/PageHeader";

interface BOMTemplateRegistrationProps {
  onBack?: () => void;
}

export function BOMTemplateRegistration({ onBack }: BOMTemplateRegistrationProps) {
  const { bomTemplates = [], addBOMTemplate } = useData();
  
  // Form state
  const [formData, setFormData] = useState({
    templateCode: generateTemplateCode(),
    templateName: "",
    productType: "SCREEN" as "SCREEN" | "STEEL",
    productModel: "",
    status: "active" as const
  });
  
  const [bomRules, setBomRules] = useState<BOMCalculationRule[]>([]);
  const [errors, setErrors] = useState<{[key: string]: string}>({});

  // 템플릿 코드 자동 생성
  function generateTemplateCode() {
    const maxNumber = (bomTemplates || [])
      .map(t => {
        const match = (t.templateCode || '').match(/\d+$/);
        return match ? parseInt(match[0]) : 0;
      })
      .reduce((max, num) => Math.max(max, num), 0);
    return `BOM-TEMPLATE-${String(maxNumber + 1).padStart(3, '0')}`;
  }

  // BOM 규칙 추가
  const handleAddBOMRule = () => {
    setBomRules([...bomRules, {
      partName: "",
      partCode: "",
      quantityFormula: "",
      unit: "EA",
      description: "",
      roundingRule: "ceil"
    }]);
  };

  // BOM 규칙 삭제
  const handleRemoveBOMRule = (index: number) => {
    setBomRules(bomRules.filter((_, i) => i !== index));
  };

  // BOM 규칙 업데이트
  const handleUpdateBOMRule = (index: number, field: keyof BOMCalculationRule, value: any) => {
    const updated = [...bomRules];
    updated[index] = { ...updated[index], [field]: value };
    setBomRules(updated);
    
    // 필드 에러 제거
    const newErrors = { ...errors };
    delete newErrors[`bomRule_${index}_${field}`];
    setErrors(newErrors);
  };

  // 수식 검증 함수
  const validateFormula = (formula: string) => {
    try {
      // W, H를 임시값으로 대체하여 계산 가능한지 확인
      const testFormula = formula
        .replace(/W/g, '1000')
        .replace(/H/g, '2000');
      eval(testFormula);
      return true;
    } catch {
      return false;
    }
  };

  // 유효성 검사
  const validate = () => {
    const newErrors: {[key: string]: string} = {};

    if (!formData.templateName.trim()) {
      newErrors.templateName = "템플릿명은 필수 입력 항목입니다.";
    }

    if (bomRules.length === 0) {
      newErrors.bomRules = "최소 1개 이상의 BOM 규칙을 추가해주세요.";
    }

    // 모든 BOM 규칙의 필수 필드 확인
    bomRules.forEach((rule, index) => {
      if (!rule.partName.trim()) {
        newErrors[`bomRule_${index}_partName`] = "부품명은 필수 입력 항목입니다.";
      }
      if (!rule.quantityFormula.trim()) {
        newErrors[`bomRule_${index}_quantityFormula`] = "수량 계산식은 필수 입력 항목입니다.";
      } else if (!validateFormula(rule.quantityFormula)) {
        newErrors[`bomRule_${index}_quantityFormula`] = "올바르지 않은 계산식입니다.";
      }
    });

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

  // 템플릿 등록
  const handleCreate = () => {
    if (!validate()) {
      toast.error("필수 입력 항목을 확인해주세요.");
      return;
    }

    const newTemplate: ProductBOMTemplate = {
      id: `BOM-TEMPLATE-${Date.now()}`,
      templateCode: formData.templateCode,
      templateName: formData.templateName,
      productType: formData.productType,
      productModel: formData.productModel,
      bomRules: bomRules,
      currentRevision: 0,
      isFinal: false,
      status: formData.status,
      createdAt: new Date().toISOString().split('T')[0],
      createdBy: '시스템'
    };

    addBOMTemplate(newTemplate);
    toast.success(`BOM 템플릿 "${formData.templateName}"이 등록되었습니다.`);
    if (onBack) {
      onBack(); // 목록으로 돌아가기
    }
  };

  const handleBack = () => {
    if (onBack) {
      onBack();
    }
  };

  return (
    <PageLayout>
      <PageHeader
        title="제품 BOM 템플릿 등록"
        subtitle="오픈사이즈 기반 부품별 수량 자동 계산 수식 등록"
        icon={Calculator}
        actions={
          <div className="flex gap-2">
            <Button variant="outline" onClick={handleBack}>
              <ArrowLeft className="h-5 w-5 mr-2" />
              목록으로
            </Button>
            <Button onClick={handleCreate}>
              <Save className="h-5 w-5 mr-2" />
              등록
            </Button>
          </div>
        }
      />

      {/* 기본 정보 */}
      <Card>
        <CardContent className="pt-6">
          <div className="grid gap-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>
                  템플릿 코드 <span className="text-red-500">*</span>
                </Label>
                <Input
                  value={formData.templateCode}
                  onChange={(e) => setFormData({ ...formData, templateCode: e.target.value })}
                  placeholder="BOM-TEMPLATE-001"
                />
              </div>
              <div className="space-y-2">
                <Label>
                  제품 타입 <span className="text-red-500">*</span>
                </Label>
                <Select
                  value={formData.productType}
                  onValueChange={(value: "SCREEN" | "STEEL") => setFormData({ ...formData, productType: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="SCREEN">스크린</SelectItem>
                    <SelectItem value="STEEL">철재</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label>
                  템플릿명 <span className="text-red-500">*</span>
                </Label>
                <Input
                  value={formData.templateName}
                  onChange={(e) => {
                    setFormData({ ...formData, templateName: e.target.value });
                    const newErrors = { ...errors };
                    delete newErrors.templateName;
                    setErrors(newErrors);
                  }}
                  placeholder="예: 스크린 셔터 표준형 BOM"
                  className={errors.templateName ? "border-red-500" : ""}
                />
                {errors.templateName && (
                  <p className="text-red-500 text-sm">{errors.templateName}</p>
                )}
              </div>
              <div className="space-y-2">
                <Label>제품 모델</Label>
                <Input
                  value={formData.productModel}
                  onChange={(e) => setFormData({ ...formData, productModel: e.target.value })}
                  placeholder="예: 스크린 셔터-표준형"
                />
              </div>
            </div>

            <div className="space-y-2">
              <Label>상태</Label>
              <Select
                value={formData.status}
                onValueChange={(value: 'active' | 'inactive' | 'draft') => setFormData({ ...formData, status: value })}
              >
                <SelectTrigger className="w-48">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="active">활성</SelectItem>
                  <SelectItem value="inactive">비활성</SelectItem>
                  <SelectItem value="draft">초안</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* BOM 계산 규칙 */}
      <Card>
        <CardContent className="pt-6">
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="font-medium">BOM 계산 규칙 <span className="text-red-500">*</span></h3>
                <p className="text-sm text-gray-500 mt-1">
                  오픈사이즈(폭, 높이)를 기준으로 각 부품의 수량을 자동 계산하는 수식을 등록합니다.
                </p>
              </div>
              <Button type="button" onClick={handleAddBOMRule} size="sm">
                <Plus className="h-4 w-4 mr-2" />
                규칙 추가
              </Button>
            </div>

            {errors.bomRules && (
              <div className="bg-red-50 border border-red-200 rounded-lg p-3">
                <p className="text-red-600 text-sm">{errors.bomRules}</p>
              </div>
            )}

            {bomRules.map((rule, index) => (
              <Card key={index} className="border-2">
                <CardContent className="pt-6">
                  <div className="grid gap-4">
                    <div className="flex items-center justify-between">
                      <span className="text-sm font-medium text-gray-500">규칙 #{index + 1}</span>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() => handleRemoveBOMRule(index)}
                        className="text-red-600"
                      >
                        <Trash2 className="h-4 w-4 mr-2" />
                        삭제
                      </Button>
                    </div>

                    <div className="grid grid-cols-3 gap-4">
                      <div className="space-y-2">
                        <Label>
                          부품명 <span className="text-red-500">*</span>
                        </Label>
                        <Input
                          value={rule.partName}
                          onChange={(e) => handleUpdateBOMRule(index, 'partName', e.target.value)}
                          placeholder="예: 모터"
                          className={errors[`bomRule_${index}_partName`] ? "border-red-500" : ""}
                        />
                        {errors[`bomRule_${index}_partName`] && (
                          <p className="text-red-500 text-sm">{errors[`bomRule_${index}_partName`]}</p>
                        )}
                      </div>
                      <div className="space-y-2">
                        <Label>부품코드</Label>
                        <Input
                          value={rule.partCode || ""}
                          onChange={(e) => handleUpdateBOMRule(index, 'partCode', e.target.value)}
                          placeholder="예: 모터-1HP 220V"
                        />
                      </div>
                      <div className="space-y-2">
                        <Label>
                          단위 <span className="text-red-500">*</span>
                        </Label>
                        <Select
                          value={rule.unit}
                          onValueChange={(value) => handleUpdateBOMRule(index, 'unit', value)}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="EA">EA</SelectItem>
                            <SelectItem value="M">M</SelectItem>
                            <SelectItem value="KG">KG</SelectItem>
                            <SelectItem value="M2">M2</SelectItem>
                            <SelectItem value="SET">SET</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <Label>
                          수량 계산식 <span className="text-red-500">*</span>
                        </Label>
                        <Input
                          value={rule.quantityFormula}
                          onChange={(e) => handleUpdateBOMRule(index, 'quantityFormula', e.target.value)}
                          placeholder="예: (W + H) * 2 / 1000"
                          className={`font-mono ${errors[`bomRule_${index}_quantityFormula`] ? "border-red-500" : ""}`}
                        />
                        {errors[`bomRule_${index}_quantityFormula`] && (
                          <p className="text-red-500 text-sm">{errors[`bomRule_${index}_quantityFormula`]}</p>
                        )}
                        <p className="text-xs text-gray-500">
                          변수: W (폭, mm), H (높이, mm). 예: W * 2, (W + H) / 1000
                        </p>
                      </div>
                      <div className="space-y-2">
                        <Label>반올림 규칙</Label>
                        <Select
                          value={rule.roundingRule || 'ceil'}
                          onValueChange={(value: 'ceil' | 'floor' | 'round') => handleUpdateBOMRule(index, 'roundingRule', value)}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="ceil">올림</SelectItem>
                            <SelectItem value="floor">내림</SelectItem>
                            <SelectItem value="round">반올림</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    <div className="space-y-2">
                      <Label>설명</Label>
                      <Input
                        value={rule.description || ""}
                        onChange={(e) => handleUpdateBOMRule(index, 'description', e.target.value)}
                        placeholder="수식에 대한 설명"
                      />
                    </div>

                    {/* 수식 검증 결과 표시 */}
                    {rule.quantityFormula && (
                      <div className={`p-3 rounded-lg border ${validateFormula(rule.quantityFormula) ? 'bg-green-50 border-green-200' : 'bg-red-50 border-red-200'}`}>
                        <p className={`text-sm ${validateFormula(rule.quantityFormula) ? 'text-green-700' : 'text-red-700'}`}>
                          {validateFormula(rule.quantityFormula) 
                            ? '✓ 유효한 계산식입니다.' 
                            : '✗ 올바르지 않은 계산식입니다. 수식을 확인해주세요.'}
                        </p>
                        {validateFormula(rule.quantityFormula) && (
                          <p className="text-xs text-gray-600 mt-1">
                            테스트: W=1000mm, H=2000mm 기준 → 결과: {Math[rule.roundingRule || 'ceil'](eval(rule.quantityFormula.replace(/W/g, '1000').replace(/H/g, '2000')))} {rule.unit}
                          </p>
                        )}
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}

            {bomRules.length === 0 && (
              <div className="text-center py-12 text-gray-500 border-2 border-dashed rounded-lg">
                <Calculator className="h-12 w-12 mx-auto mb-3 text-gray-400" />
                <p>BOM 계산 규칙을 추가해주세요</p>
                <p className="text-sm mt-1">오픈사이즈 기반으로 각 부품의 수량을 자동 계산합니다</p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 하단 버튼 */}
      <div className="flex justify-end gap-3">
        <Button variant="outline" onClick={handleBack}>
          취소
        </Button>
        <Button onClick={handleCreate}>
          <Save className="h-4 w-4 mr-2" />
          등록
        </Button>
      </div>
    </PageLayout>
  );
}
