/**
 * 검사기준 등록/수정 폼
 * ResponsiveFormTemplate 기반
 */

import { useState } from "react";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Label } from "./ui/label";
import { FileText, FileCheck, Plus, Trash2, Settings } from "lucide-react";
import { toast } from "sonner@2.0.3";
import { useData } from "./contexts/DataContext";
import type { InspectionStandard } from "./contexts/DataContext";
import {
  ResponsiveFormTemplate,
  FormSection,
  FormField,
  FormFieldGrid
} from "./templates/ResponsiveFormTemplate";
import { InspectionDocumentEditor } from "./InspectionDocumentEditor";

interface InspectionStandardFormProps {
  standard: InspectionStandard | null;
  onBack: () => void;
}

export function InspectionStandardForm({ standard, onBack }: InspectionStandardFormProps) {
  const { addInspectionStandard, updateInspectionStandard, itemMasters } = useData();
  const [showDocumentEditor, setShowDocumentEditor] = useState(false);
  
  const isEdit = !!standard;

  // 기본 문서 템플릿
  const getDefaultTemplate = (inspectionType: string) => ({
    title: inspectionType === 'incoming' ? '수입검사 성적서' : 
           inspectionType === 'process' ? '중간검사 성적서' : '제품검사 성적서',
    companyName: '경동기업',
    companyAddress: '',
    companyPhone: '',
    approvalLines: [
      { id: '1', position: '작성', name: '전진', department: '품질관리' },
      { id: '2', position: '검토', name: '', department: '생산관리' },
      { id: '3', position: '승인', name: '', department: '공장장' }
    ],
    basicInfoFields: [
      { id: '1', label: '품명', value: '', type: 'text' as const, required: true },
      { id: '2', label: '규격', value: '', type: 'text' as const, required: false },
      { id: '3', label: '납품업체', value: '', type: 'text' as const, required: false },
      { id: '4', label: '검사일자', value: '', type: 'date' as const, required: true },
      { id: '5', label: 'LOT NO', value: '', type: 'text' as const, required: false }
    ],
    inspectionColumns: [
      { id: '1', name: 'NO', type: 'text' as const, width: '60px' },
      { id: '2', name: '검사항목', type: 'text' as const, width: '200px' },
      { id: '3', name: '검사기준', type: 'text' as const, width: '200px' },
      { id: '4', name: '검사방법', type: 'text' as const, width: '150px' },
      { id: '5', name: '측정값', type: 'text' as const, width: '100px' },
      { id: '6', name: '판정', type: 'select' as const, width: '80px', options: ['합격', '불합격'] }
    ],
    inspectionItems: [
      { id: '1', no: 1, values: { '1': '1', '2': '외관검사', '3': '육안검사', '4': '목시', '5': '', '6': '' } },
      { id: '2', no: 2, values: { '1': '2', '2': '치수검사', '3': '도면 기준', '4': '버니어캘리퍼스', '5': '', '6': '' } },
      { id: '3', no: 3, values: { '1': '3', '2': '재질검사', '3': '성적서 확인', '4': '서류확인', '5': '', '6': '' } }
    ],
    notesLabel: '비고',
    judgmentLabel: '종합판정',
    judgmentOptions: ['합격', '불합격', '조건부합격']
  });

  const [formData, setFormData] = useState({
    inspectionType: standard?.inspectionType || 'incoming',
    inspectionName: standard?.inspectionName || '',
    itemCode: standard?.itemCode || '',
    itemName: standard?.itemName || '',
    description: standard?.description || '',
    status: standard?.status || 'active',
    documentTemplate: standard?.documentTemplate || getDefaultTemplate('incoming')
  });

  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    
    // 검사유형 변경 시 기본 템플릿도 변경
    if (field === 'inspectionType' && !standard) {
      setFormData(prev => ({ 
        ...prev, 
        documentTemplate: getDefaultTemplate(value),
        inspectionName: value === 'incoming' ? '수입검사' : 
                       value === 'process' ? '중간검사' : '제품검사'
      }));
    }
  };

  const handleSubmit = () => {
    // 유효성 검사
    if (!formData.inspectionName) {
      toast.error('검사명칭을 입력해주세요.');
      return;
    }

    const now = new Date().toISOString();
    
    console.log('💾 검사기준 저장 시작');
    console.log('💾 저장될 formData:', formData);
    console.log('💾 저장될 결재라인:', formData.documentTemplate.approvalLines);
    
    if (isEdit && standard) {
      // 수정
      const updatedData = {
        ...formData,
        updatedAt: now,
        updatedBy: '관리자'
      };
      console.log('✏️ 수정 데이터:', updatedData);
      updateInspectionStandard(standard.id, updatedData);
      onBack();
    } else {
      // 신규 등록
      const newStandard: InspectionStandard = {
        id: `IS-${Date.now()}`,
        standardNumber: generateStandardNumber(formData.inspectionType),
        inspectionType: formData.inspectionType as 'incoming' | 'process' | 'final',
        inspectionName: formData.inspectionName,
        itemCode: formData.itemCode,
        itemName: formData.itemName,
        description: formData.description,
        documentTemplate: formData.documentTemplate,
        currentRevision: 0,
        isFinal: false,
        status: formData.status as 'active' | 'inactive',
        createdAt: now,
        createdBy: '관리자'
      };
      
      console.log('✅ 신규 등록 데이터:', newStandard);
      console.log('✅ 등록될 결재라인:', newStandard.documentTemplate.approvalLines);
      addInspectionStandard(newStandard);
      onBack();
    }
  };

  const generateStandardNumber = (type: string) => {
    const prefix = type === 'incoming' ? 'IS-IN' : 
                   type === 'process' ? 'IS-PR' : 'IS-FN';
    const date = new Date();
    const year = date.getFullYear().toString().slice(-2);
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const seq = String(Math.floor(Math.random() * 999) + 1).padStart(3, '0');
    return `${prefix}-${year}${month}-${seq}`;
  };

  // 품목 선택 시
  const handleItemSelect = (itemCode: string) => {
    const item = itemMasters.find(i => i.itemCode === itemCode);
    if (item) {
      setFormData(prev => ({
        ...prev,
        itemCode: item.itemCode,
        itemName: item.itemName
      }));
    }
  };

  // 문서 편집기 화면
  if (showDocumentEditor) {
    return (
      <InspectionDocumentEditor
        template={formData.documentTemplate}
        onSave={(newTemplate) => {
          console.log('📝 InspectionStandardForm에서 템플릿 수신:', newTemplate);
          console.log('📝 수신된 결재라인:', newTemplate.approvalLines);
          setFormData(prev => ({ ...prev, documentTemplate: newTemplate }));
          setShowDocumentEditor(false);
          toast.success('문서 템플릿이 저장되었습니다.');
        }}
        onBack={() => setShowDocumentEditor(false)}
        inspectionType={formData.inspectionType}
      />
    );
  }

  // 폼 렌더링
  return (
    <ResponsiveFormTemplate
      title="검사기준 등록"
      description={isEdit ? '검사기준 정보를 수정합니다' : '새로운 검사기준을 등록합니다'}
      icon={FileCheck}
      onSave={handleSubmit}
      onCancel={onBack}
      saveText={isEdit ? '수정 완료' : '등록 완료'}
      isEditMode={isEdit}
    >
      {/* 기본 정보 섹션 */}
      <FormSection title="기본 정보" icon={FileText}>
        <FormFieldGrid columns={2}>
          <FormField label="검사유형" required>
            <Select
              value={formData.inspectionType}
              onValueChange={(value) => handleInputChange('inspectionType', value)}
              disabled={isEdit}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="incoming">수입검사</SelectItem>
                <SelectItem value="process">중간검사</SelectItem>
                <SelectItem value="final">제품검사</SelectItem>
              </SelectContent>
            </Select>
          </FormField>

          <FormField label="검사명칭" required>
            <Input
              value={formData.inspectionName}
              onChange={(e) => handleInputChange('inspectionName', e.target.value)}
              placeholder="예: 철재 부자재 수입검사"
            />
          </FormField>

          <FormField label="품목코드">
            <Select
              value={formData.itemCode}
              onValueChange={handleItemSelect}
            >
              <SelectTrigger>
                <SelectValue placeholder="품목 선택 (선택사항)" />
              </SelectTrigger>
              <SelectContent>
                {itemMasters.map(item => (
                  <SelectItem key={item.id} value={item.itemCode}>
                    {item.itemCode} - {item.itemName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </FormField>

          <FormField label="품목명">
            <Input
              value={formData.itemName}
              onChange={(e) => handleInputChange('itemName', e.target.value)}
              placeholder="품목명 직접 입력 또는 자동 입력"
            />
          </FormField>
        </FormFieldGrid>

        <FormField label="설명">
          <Textarea
            value={formData.description}
            onChange={(e) => handleInputChange('description', e.target.value)}
            placeholder="검사기준에 대한 상세 설명"
            rows={3}
          />
        </FormField>

        <FormFieldGrid columns={2}>
          <FormField label="사용여부">
            <Select
              value={formData.status}
              onValueChange={(value) => handleInputChange('status', value)}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="active">사용중</SelectItem>
                <SelectItem value="inactive">미사용</SelectItem>
              </SelectContent>
            </Select>
          </FormField>
        </FormFieldGrid>
      </FormSection>

      {/* 문서 템플릿 섹션 */}
      <FormSection 
        title="문서 템플릿" 
        icon={Settings}
        description="검사 성적서 양식을 커스터마이징할 수 있습니다"
      >
        <div className="border rounded-lg p-6 bg-muted/30">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h4 className="font-medium mb-1">
                {formData.documentTemplate.title}
              </h4>
              <p className="text-sm text-muted-foreground">
                검사항목 {formData.documentTemplate.inspectionItems.length}개 / 
                기본정보 필드 {formData.documentTemplate.basicInfoFields.length}개
              </p>
            </div>
            <Button
              type="button"
              onClick={() => setShowDocumentEditor(true)}
              variant="outline"
            >
              <Settings className="h-4 w-4 mr-2" />
              문서 편집
            </Button>
          </div>
          
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
            <div>
              <Label className="text-muted-foreground">결재라인</Label>
              <div className="mt-1">
                {formData.documentTemplate.approvalLines.map(line => (
                  <div key={line.id} className="text-sm">
                    {line.position}: {line.name || '미지정'}
                  </div>
                ))}
              </div>
            </div>
            <div>
              <Label className="text-muted-foreground">검사항목 칼럼</Label>
              <div className="mt-1">
                {formData.documentTemplate.inspectionColumns.slice(0, 3).map(col => (
                  <div key={col.id} className="text-sm">• {col.name}</div>
                ))}
                {formData.documentTemplate.inspectionColumns.length > 3 && (
                  <div className="text-xs text-muted-foreground">
                    외 {formData.documentTemplate.inspectionColumns.length - 3}개
                  </div>
                )}
              </div>
            </div>
            <div>
              <Label className="text-muted-foreground">판정 옵션</Label>
              <div className="mt-1">
                {formData.documentTemplate.judgmentOptions?.map((opt, idx) => (
                  <div key={idx} className="text-sm">• {opt}</div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </FormSection>
    </ResponsiveFormTemplate>
  );
}