'use client';

/**
 * 중간검사 설정 모달
 *
 * 기획서 Page 9 기준:
 * - 왼쪽: 기준서명, 도해 이미지, 검사기준 이미지, 겉모양 항목들 ON/OFF
 * - 오른쪽: 치수 항목들 (포인트, 방법, ON/OFF), 판정, 부적합 내용
 */

import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { ImageUpload } from '@/components/ui/image-upload';
import type {
  InspectionSetting,
  InspectionPointType,
  InspectionMethodType,
} from '@/types/process';
import {
  INSPECTION_POINT_OPTIONS,
  INSPECTION_METHOD_OPTIONS,
  DEFAULT_INSPECTION_SETTING,
} from '@/types/process';

interface InspectionSettingModalProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  initialData?: InspectionSetting;
  onSave: (data: InspectionSetting) => void;
}

export function InspectionSettingModal({
  open,
  onOpenChange,
  initialData,
  onSave,
}: InspectionSettingModalProps) {
  const [formData, setFormData] = useState<InspectionSetting>(
    initialData || DEFAULT_INSPECTION_SETTING
  );

  useEffect(() => {
    if (open) {
      setFormData(initialData || DEFAULT_INSPECTION_SETTING);
    }
  }, [open, initialData]);

  const handleSave = () => {
    onSave(formData);
    onOpenChange(false);
  };

  const handleCancel = () => {
    onOpenChange(false);
  };

  // 겉모양 항목 토글
  const toggleAppearance = (key: keyof typeof formData.appearance) => {
    setFormData((prev) => ({
      ...prev,
      appearance: {
        ...prev.appearance,
        [key]: { ...prev.appearance[key], enabled: !prev.appearance[key].enabled },
      },
    }));
  };

  // 치수 항목 토글
  const toggleDimension = (key: keyof typeof formData.dimension) => {
    setFormData((prev) => ({
      ...prev,
      dimension: {
        ...prev.dimension,
        [key]: { ...prev.dimension[key], enabled: !prev.dimension[key].enabled },
      },
    }));
  };

  // 치수 포인트 변경
  const setDimensionPoint = (
    key: keyof typeof formData.dimension,
    point: InspectionPointType
  ) => {
    setFormData((prev) => ({
      ...prev,
      dimension: {
        ...prev.dimension,
        [key]: { ...prev.dimension[key], point },
      },
    }));
  };

  // 치수 방법 변경
  const setDimensionMethod = (
    key: keyof typeof formData.dimension,
    method: InspectionMethodType
  ) => {
    setFormData((prev) => ({
      ...prev,
      dimension: {
        ...prev.dimension,
        [key]: { ...prev.dimension[key], method },
      },
    }));
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="w-[95vw] max-w-[1200px] sm:max-w-[1200px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>중간검사 설정</DialogTitle>
        </DialogHeader>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-4">
          {/* 왼쪽 패널 - 기본 정보 및 겉모양 */}
          <div className="space-y-6 border rounded-lg p-4 bg-muted/30">
            <h3 className="font-semibold text-sm border-b pb-2">중간검사 설정</h3>

            {/* 기준서명 */}
            <div className="space-y-2">
              <Label>기준서명</Label>
              <Input
                value={formData.standardName}
                onChange={(e) =>
                  setFormData((prev) => ({ ...prev, standardName: e.target.value }))
                }
                placeholder="예: KDPS-20"
              />
            </div>

            {/* 중간검사 기준서 이미지 (통합) */}
            <div className="space-y-2">
              <Label>중간검사 기준서 이미지</Label>
              <ImageUpload
                value={formData.schematicImage}
                onChange={(file) => {
                  const url = URL.createObjectURL(file);
                  // 두 필드 모두 동일 이미지로 설정 (호환성)
                  setFormData((prev) => ({
                    ...prev,
                    schematicImage: url,
                    inspectionStandardImage: url,
                  }));
                }}
                onRemove={() => {
                  setFormData((prev) => ({
                    ...prev,
                    schematicImage: undefined,
                    inspectionStandardImage: undefined,
                  }));
                }}
                aspectRatio="wide"
                size="lg"
                className="w-full"
                hint="도해 및 검사기준이 포함된 통합 이미지를 업로드하세요"
              />
            </div>

            {/* 겉모양 항목들 */}
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <Label>겉모양 절곡상태</Label>
                <Switch
                  checked={formData.appearance.bendingStatus.enabled}
                  onCheckedChange={() => toggleAppearance('bendingStatus')}
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>겉모양 가공상태</Label>
                <Switch
                  checked={formData.appearance.processingStatus.enabled}
                  onCheckedChange={() => toggleAppearance('processingStatus')}
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>겉모양 재봉상태</Label>
                <Switch
                  checked={formData.appearance.sewingStatus.enabled}
                  onCheckedChange={() => toggleAppearance('sewingStatus')}
                />
              </div>
              <div className="flex items-center justify-between">
                <Label>겉모양 조립상태</Label>
                <Switch
                  checked={formData.appearance.assemblyStatus.enabled}
                  onCheckedChange={() => toggleAppearance('assemblyStatus')}
                />
              </div>
            </div>
          </div>

          {/* 오른쪽 패널 - 치수 및 기타 */}
          <div className="space-y-6 border rounded-lg p-4 bg-muted/30">
            <h3 className="font-semibold text-sm border-b pb-2">중간검사</h3>

            {/* 치수 항목들 */}
            {[
              { key: 'length' as const, label: '길이' },
              { key: 'width' as const, label: '너비' },
              { key: 'height1' as const, label: '1 높이' },
              { key: 'height2' as const, label: '2 높이' },
              { key: 'gap' as const, label: '간격' },
            ].map(({ key, label }) => (
              <div key={key} className="grid grid-cols-[60px_1fr_100px_50px] items-center gap-3">
                <Label className="shrink-0">{label}</Label>
                <Select
                  value={formData.dimension[key].point}
                  onValueChange={(v) => setDimensionPoint(key, v as InspectionPointType)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {INSPECTION_POINT_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Select
                  value={formData.dimension[key].method}
                  onValueChange={(v) => setDimensionMethod(key, v as InspectionMethodType)}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {INSPECTION_METHOD_OPTIONS.map((opt) => (
                      <SelectItem key={opt.value} value={opt.value}>
                        {opt.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Switch
                  checked={formData.dimension[key].enabled}
                  onCheckedChange={() => toggleDimension(key)}
                />
              </div>
            ))}

            {/* 판정 */}
            <div className="flex items-center justify-between pt-4 border-t">
              <Label>판정</Label>
              <Switch
                checked={formData.judgment}
                onCheckedChange={(checked) =>
                  setFormData((prev) => ({ ...prev, judgment: checked }))
                }
              />
            </div>

            {/* 부적합 내용 */}
            <div className="flex items-center justify-between">
              <Label>부적합 내용</Label>
              <Switch
                checked={formData.nonConformingContent}
                onCheckedChange={(checked) =>
                  setFormData((prev) => ({ ...prev, nonConformingContent: checked }))
                }
              />
            </div>
          </div>
        </div>

        {/* 버튼 영역 */}
        <div className="flex justify-end gap-2 mt-6">
          <Button variant="outline" onClick={handleCancel}>
            취소
          </Button>
          <Button onClick={handleSave}>저장</Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
