'use client';

/**
 * 제품검사 입력 모달
 *
 * 양식 기반 전환 (5.2.4):
 * - FQC 모드: documents API template 기반으로 검사항목 렌더링
 *   → 11개 설치 후 최종검사 항목 (template_id: 65)
 *   → 모두 visual/checkbox (적합/부적합)
 *   → saveFqcDocument로 서버에 직접 저장
 * - Legacy 모드: 기존 하드코딩 필드 (fallback)
 */

import { useState, useEffect, useRef, useCallback } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';
import { getFqcTemplate, getFqcDocument, saveFqcDocument } from './fqcActions';
import type { FqcTemplate, FqcTemplateItem, FqcDocumentData } from './fqcActions';
import type { ProductInspectionData } from './types';

type JudgmentValue = '적합' | '부적합' | null;

interface ProductInspectionInputModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  orderItemId: string;
  productName?: string;
  specification?: string;
  initialData?: ProductInspectionData;
  onComplete: (data: ProductInspectionData) => void;
  /** FQC 문서 ID (있으면 양식 기반 모드) */
  fqcDocumentId?: number | null;
}

export function ProductInspectionInputModal({
  open,
  onOpenChange,
  orderItemId,
  productName = '',
  specification = '',
  initialData,
  onComplete,
  fqcDocumentId,
}: ProductInspectionInputModalProps) {
  // FQC 모드 상태
  const [fqcTemplate, setFqcTemplate] = useState<FqcTemplate | null>(null);
  const [fqcDocData, setFqcDocData] = useState<FqcDocumentData[]>([]);
  const [isLoadingFqc, setIsLoadingFqc] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // 판정 상태 (FQC 모드)
  const [judgments, setJudgments] = useState<Record<number, JudgmentValue>>({});

  const useFqcMode = !!fqcDocumentId;

  // FQC 데이터 로드
  useEffect(() => {
    if (!open || !useFqcMode) return;

    setIsLoadingFqc(true);

    Promise.all([
      getFqcTemplate(),
      getFqcDocument(fqcDocumentId!),
    ])
      .then(([templateResult, docResult]) => {
        if (templateResult.success && templateResult.data) {
          setFqcTemplate(templateResult.data);
        }
        if (docResult.success && docResult.data) {
          setFqcDocData(docResult.data.data);
          // 기존 판정 데이터 복원
          const dataSection = docResult.data.template.sections.find(s => s.items.length > 0);
          const judgmentCol = docResult.data.template.columns.find(c => c.label === '판정');
          if (dataSection && judgmentCol) {
            const map: Record<number, JudgmentValue> = {};
            for (const d of docResult.data.data) {
              if (d.sectionId === dataSection.id && d.columnId === judgmentCol.id && d.fieldKey === 'result') {
                map[d.rowIndex] = (d.fieldValue as JudgmentValue) ?? null;
              }
            }
            setJudgments(map);
          }
        }
      })
      .finally(() => setIsLoadingFqc(false));
  }, [open, useFqcMode, fqcDocumentId]);

  // 모달 닫힐 때 상태 초기화
  useEffect(() => {
    if (!open) {
      setJudgments({});
      setFqcDocData([]);
    }
  }, [open]);

  // 판정 토글
  const toggleJudgment = useCallback((rowIndex: number, value: JudgmentValue) => {
    setJudgments(prev => ({
      ...prev,
      [rowIndex]: prev[rowIndex] === value ? null : value,
    }));
  }, []);

  // FQC 종합판정 계산
  const overallJudgment = useCallback((): '합격' | '불합격' | null => {
    if (!fqcTemplate) return null;
    const dataSection = fqcTemplate.sections.find(s => s.items.length > 0);
    if (!dataSection || dataSection.items.length === 0) return null;

    const values = dataSection.items.map((_, idx) => judgments[idx]);
    const hasValue = values.some(v => v !== undefined && v !== null);
    if (!hasValue) return null;
    if (values.some(v => v === '부적합')) return '불합격';
    if (values.every(v => v === '적합')) return '합격';
    return null;
  }, [fqcTemplate, judgments]);

  // FQC 검사 완료 (서버 저장)
  const handleFqcComplete = useCallback(async () => {
    if (!fqcTemplate || !fqcDocumentId) return;

    const dataSection = fqcTemplate.sections.find(s => s.items.length > 0);
    const judgmentCol = fqcTemplate.columns.find(c => c.label === '판정');
    if (!dataSection || !judgmentCol) return;

    setIsSaving(true);
    try {
      // document_data 형식으로 변환
      const records: Array<{
        section_id: number | null;
        column_id: number | null;
        row_index: number;
        field_key: string;
        field_value: string | null;
      }> = [];

      dataSection.items.forEach((_, idx) => {
        const value = judgments[idx];
        if (value) {
          records.push({
            section_id: dataSection.id,
            column_id: judgmentCol.id,
            row_index: idx,
            field_key: 'result',
            field_value: value,
          });
        }
      });

      // 종합판정
      records.push({
        section_id: null,
        column_id: null,
        row_index: 0,
        field_key: 'footer_judgement',
        field_value: overallJudgment(),
      });

      const result = await saveFqcDocument({
        documentId: fqcDocumentId,
        data: records,
      });

      if (result.success) {
        toast.success('검사 데이터가 저장되었습니다.');

        // onComplete callback으로 로컬 상태도 업데이트
        // Legacy 타입 호환: FQC 판정 데이터를 ProductInspectionData 형태로 변환
        const legacyData: ProductInspectionData = {
          productName,
          specification,
          productImages: [],
          // FQC 모드에서는 모든 항목을 적합/부적합으로만 판정
          // 11개 항목을 legacy 필드에 매핑 (가능한 만큼)
          appearanceProcessing: judgments[0] === '적합' ? 'pass' : judgments[0] === '부적합' ? 'fail' : null,
          appearanceSewing: judgments[1] === '적합' ? 'pass' : judgments[1] === '부적합' ? 'fail' : null,
          appearanceAssembly: judgments[2] === '적합' ? 'pass' : judgments[2] === '부적합' ? 'fail' : null,
          appearanceSmokeBarrier: judgments[3] === '적합' ? 'pass' : judgments[3] === '부적합' ? 'fail' : null,
          appearanceBottomFinish: judgments[4] === '적합' ? 'pass' : judgments[4] === '부적합' ? 'fail' : null,
          motor: judgments[5] === '적합' ? 'pass' : judgments[5] === '부적합' ? 'fail' : null,
          material: judgments[6] === '적합' ? 'pass' : judgments[6] === '부적합' ? 'fail' : null,
          lengthValue: null,
          lengthJudgment: judgments[7] === '적합' ? 'pass' : judgments[7] === '부적합' ? 'fail' : null,
          heightValue: null,
          heightJudgment: judgments[8] === '적합' ? 'pass' : judgments[8] === '부적합' ? 'fail' : null,
          guideRailGapValue: null,
          guideRailGap: judgments[9] === '적합' ? 'pass' : judgments[9] === '부적합' ? 'fail' : null,
          bottomFinishGapValue: null,
          bottomFinishGap: judgments[10] === '적합' ? 'pass' : judgments[10] === '부적합' ? 'fail' : null,
          fireResistanceTest: null,
          smokeLeakageTest: null,
          openCloseTest: null,
          impactTest: null,
          hasSpecialNotes: false,
          specialNotes: '',
        };

        onComplete(legacyData);
        onOpenChange(false);
      } else {
        toast.error(result.error || '검사 데이터 저장에 실패했습니다.');
      }
    } finally {
      setIsSaving(false);
    }
  }, [fqcTemplate, fqcDocumentId, judgments, overallJudgment, productName, specification, onComplete, onOpenChange]);

  // Legacy 완료 핸들러
  const handleLegacyComplete = useCallback(() => {
    if (!legacyFormData) return;
    onComplete(legacyFormData);
    onOpenChange(false);
  }, [onComplete, onOpenChange]);

  // ===== Legacy 모드 상태 =====
  const [legacyFormData, setLegacyFormData] = useState<ProductInspectionData | null>(null);

  useEffect(() => {
    if (open && !useFqcMode) {
      setLegacyFormData(initialData || {
        productName,
        specification,
        productImages: [],
        appearanceProcessing: 'pass',
        appearanceSewing: 'pass',
        appearanceAssembly: 'pass',
        appearanceSmokeBarrier: 'pass',
        appearanceBottomFinish: 'pass',
        motor: 'pass',
        material: 'pass',
        lengthValue: null,
        lengthJudgment: 'pass',
        heightValue: null,
        heightJudgment: 'pass',
        guideRailGapValue: null,
        guideRailGap: 'pass',
        bottomFinishGapValue: null,
        bottomFinishGap: 'pass',
        fireResistanceTest: 'pass',
        smokeLeakageTest: 'pass',
        openCloseTest: 'pass',
        impactTest: 'pass',
        hasSpecialNotes: false,
        specialNotes: '',
      });
    }
  }, [open, useFqcMode, initialData, productName, specification]);

  // FQC 데이터 섹션
  const dataSection = fqcTemplate?.sections.find(s => s.items.length > 0);
  const sortedItems = dataSection?.items.sort((a, b) => a.sortOrder - b.sortOrder) || [];
  const currentOverallJudgment = overallJudgment();

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-[95vw] max-w-[600px] max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <DialogTitle className="text-lg font-bold">
            # 제품검사
            {useFqcMode && (
              <span className="ml-2 text-xs font-normal text-blue-600 bg-blue-50 px-2 py-0.5 rounded">
                양식 기반
              </span>
            )}
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6 mt-4 overflow-y-auto flex-1 pr-2">
          {/* 제품명 / 규격 */}
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-1">
              <span className="text-sm text-muted-foreground">제품명</span>
              <div className="font-medium">{productName || '-'}</div>
            </div>
            <div className="space-y-1">
              <span className="text-sm text-muted-foreground">규격</span>
              <div className="font-medium">{specification || '-'}</div>
            </div>
          </div>

          {useFqcMode ? (
            // ===== FQC 양식 기반 모드 =====
            isLoadingFqc ? (
              <div className="flex items-center justify-center py-10">
                <Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
                <span className="ml-2 text-muted-foreground text-sm">양식 로딩 중...</span>
              </div>
            ) : (
              <>
                {/* 검사항목 목록 (template 기반) */}
                <div className="space-y-3">
                  <div className="text-sm font-medium text-blue-600 border-b pb-2">
                    {dataSection?.title || dataSection?.name || '검사항목'}
                    <span className="ml-2 text-xs text-muted-foreground font-normal">
                      ({sortedItems.length}항목)
                    </span>
                  </div>

                  <div className="space-y-2">
                    {sortedItems.map((item, idx) => (
                      <FqcInspectionRow
                        key={item.id}
                        index={idx}
                        item={item}
                        judgment={judgments[idx] ?? null}
                        onToggle={toggleJudgment}
                      />
                    ))}
                  </div>
                </div>

                {/* 종합판정 */}
                <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg border">
                  <span className="font-medium">종합판정</span>
                  <span
                    className={cn(
                      'font-bold text-sm',
                      currentOverallJudgment === '합격'
                        ? 'text-blue-600'
                        : currentOverallJudgment === '불합격'
                          ? 'text-red-600'
                          : 'text-gray-400'
                    )}
                  >
                    {currentOverallJudgment || '미판정'}
                  </span>
                </div>
              </>
            )
          ) : (
            // ===== Legacy 하드코딩 모드 (fallback) =====
            legacyFormData && (
              <LegacyInspectionForm
                data={legacyFormData}
                onChange={setLegacyFormData}
              />
            )
          )}
        </div>

        {/* 버튼 영역 */}
        <div className="flex gap-3 mt-6 pt-4 border-t">
          <Button variant="outline" onClick={() => onOpenChange(false)} className="flex-1">
            취소
          </Button>
          <Button
            onClick={useFqcMode ? handleFqcComplete : handleLegacyComplete}
            disabled={isSaving || isLoadingFqc}
            className="flex-1 bg-blue-600 hover:bg-blue-700 text-white"
          >
            {isSaving ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                저장 중...
              </>
            ) : (
              '검사 완료'
            )}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}

// ===== FQC 검사항목 행 =====

function FqcInspectionRow({
  index,
  item,
  judgment,
  onToggle,
}: {
  index: number;
  item: FqcTemplateItem;
  judgment: JudgmentValue;
  onToggle: (rowIndex: number, value: JudgmentValue) => void;
}) {
  return (
    <div className="flex items-center justify-between py-2 px-3 rounded-lg hover:bg-gray-50">
      <div className="flex items-center gap-3">
        <span className="text-xs text-muted-foreground w-5 text-right">{index + 1}</span>
        <span className="text-sm">{item.itemName}</span>
      </div>
      <div className="flex gap-2">
        <button
          type="button"
          onClick={() => onToggle(index, '적합')}
          className={cn(
            'px-3 py-1.5 rounded text-xs font-medium transition-colors',
            judgment === '적합'
              ? 'bg-blue-600 text-white'
              : 'bg-gray-100 text-gray-600 hover:bg-blue-50 hover:text-blue-600'
          )}
        >
          적합
        </button>
        <button
          type="button"
          onClick={() => onToggle(index, '부적합')}
          className={cn(
            'px-3 py-1.5 rounded text-xs font-medium transition-colors',
            judgment === '부적합'
              ? 'bg-red-600 text-white'
              : 'bg-gray-100 text-gray-600 hover:bg-red-50 hover:text-red-600'
          )}
        >
          부적합
        </button>
      </div>
    </div>
  );
}

// ===== Legacy 폼 (기존 하드코딩 검사항목) =====

function LegacyInspectionForm({
  data,
  onChange,
}: {
  data: ProductInspectionData;
  onChange: (data: ProductInspectionData) => void;
}) {
  const update = <K extends keyof ProductInspectionData>(key: K, value: ProductInspectionData[K]) => {
    onChange({ ...data, [key]: value });
  };

  return (
    <>
      {/* 겉모양 검사 */}
      <LegacyGroup title="겉모양 검사">
        <LegacyRow label="가공상태" value={data.appearanceProcessing} onChange={v => update('appearanceProcessing', v)} />
        <LegacyRow label="재봉상태" value={data.appearanceSewing} onChange={v => update('appearanceSewing', v)} />
        <LegacyRow label="조립상태" value={data.appearanceAssembly} onChange={v => update('appearanceAssembly', v)} />
        <LegacyRow label="연기차단재" value={data.appearanceSmokeBarrier} onChange={v => update('appearanceSmokeBarrier', v)} />
        <LegacyRow label="하단마감재" value={data.appearanceBottomFinish} onChange={v => update('appearanceBottomFinish', v)} />
        <LegacyRow label="모터" value={data.motor} onChange={v => update('motor', v)} />
      </LegacyGroup>
      {/* 재질/치수 검사 */}
      <LegacyGroup title="재질/치수 검사">
        <LegacyRow label="재질" value={data.material} onChange={v => update('material', v)} />
        <LegacyRow label="길이" value={data.lengthJudgment} onChange={v => update('lengthJudgment', v)} />
        <LegacyRow label="높이" value={data.heightJudgment} onChange={v => update('heightJudgment', v)} />
        <LegacyRow label="가이드레일 홈간격" value={data.guideRailGap} onChange={v => update('guideRailGap', v)} />
        <LegacyRow label="하단마감재 간격" value={data.bottomFinishGap} onChange={v => update('bottomFinishGap', v)} />
      </LegacyGroup>
      {/* 시험 검사 */}
      <LegacyGroup title="시험 검사">
        <LegacyRow label="내화시험" value={data.fireResistanceTest} onChange={v => update('fireResistanceTest', v)} />
        <LegacyRow label="차연시험" value={data.smokeLeakageTest} onChange={v => update('smokeLeakageTest', v)} />
        <LegacyRow label="개폐시험" value={data.openCloseTest} onChange={v => update('openCloseTest', v)} />
        <LegacyRow label="내충격시험" value={data.impactTest} onChange={v => update('impactTest', v)} />
      </LegacyGroup>
    </>
  );
}

function LegacyGroup({ title, children }: { title: string; children: React.ReactNode }) {
  return (
    <div className="space-y-3">
      <div className="text-sm font-medium text-orange-500 border-b pb-2">{title}</div>
      <div className="space-y-4 pl-2">{children}</div>
    </div>
  );
}

function LegacyRow({
  label,
  value,
  onChange,
}: {
  label: string;
  value: 'pass' | 'fail' | null;
  onChange: (v: 'pass' | 'fail') => void;
}) {
  return (
    <div className="flex items-center justify-between">
      <span className="text-sm text-muted-foreground">{label}</span>
      <div className="flex gap-2">
        <button
          type="button"
          onClick={() => onChange('pass')}
          className={cn(
            'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            value === 'pass' ? 'bg-orange-500 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
          )}
        >
          적합
        </button>
        <button
          type="button"
          onClick={() => onChange('fail')}
          className={cn(
            'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
            value === 'fail' ? 'bg-gray-700 text-white' : 'bg-gray-200 text-gray-700 hover:bg-gray-300'
          )}
        >
          부적합
        </button>
      </div>
    </div>
  );
}
