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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Checkbox } from "./ui/checkbox";
import { Badge } from "./ui/badge";
import { RadioGroup, RadioGroupItem } from "./ui/radio-group";
import { toast } from "sonner@2.0.3";
import { 
  ArrowLeft, 
  ArrowRight, 
  Package, 
  FileText, 
  Settings, 
  Box,
  Layers,
  Cog,
  Scissors,
  CheckCircle2,
  Grid3x3,
  Zap,
  Save
} from "lucide-react";

interface ModelFormData {
  // 1. 모델명/모델 이름
  code?: string;
  name?: string;
  
  // 2. 본체 선택
  bodyType?: '스크린' | '철재';
  bodyMaterial?: string;
  
  // 3. 절곡물 구성그룹 - 케이스 선택
  caseComponents?: {
    점검구?: boolean;
    린텔부?: boolean;
    후면코너부?: boolean;
    상부덮개?: boolean;
    마구리?: boolean;
    연기차단재?: boolean;
  };
  caseDetails?: string;
  
  // 4. 가이드레일 선택
  guideRailType?: '벽면형' | '측면형' | '혼합형';
  guideRailComponents?: {
    마감재?: boolean;
    본체1_가이드레일?: boolean;
    본체2_가이드레일?: boolean;
    C형?: boolean;
    D형?: boolean;
    연기차단제?: boolean;
    별도마감제?: boolean;
  };
  
  // 5. 하단마감재 선택
  bottomFinishComponents?: {
    하장바?: boolean;
    보강엘바?: boolean;
    보강평철?: boolean;
    무게평철?: boolean;
  };
  
  // 6. 모터구성 선택
  motorComponents?: {
    모터?: boolean;
    브라켓?: boolean;
  };
  motorType?: string;
  motorSpec?: string;
  
  // 7. 부자재 선택
  subMaterials?: {
    감기샤프트?: boolean;
    각파이프?: boolean;
    앵글?: boolean;
  };
  subMaterialDetails?: string;
  
  // 최종 승인
  isApproved?: boolean;
}

interface ModelRegistrationProps {
  onCancel: () => void;
  onSave: (data: ModelFormData) => void;
}

export function ModelRegistration({ onCancel, onSave }: ModelRegistrationProps) {
  const [isMobile, setIsMobile] = useState(false);
  const [currentStep, setCurrentStep] = useState(1);
  const [formData, setFormData] = useState<ModelFormData>({
    caseComponents: {},
    guideRailComponents: {},
    bottomFinishComponents: {},
    motorComponents: {},
    subMaterials: {},
  });

  // 자재관리에서 등록된 자재 목록 (Mock 데이터)
  const screenMaterials = [
    { code: "SCR-001", name: "폴리에스터 스크린 100%, 1.2mm" },
    { code: "SCR-002", name: "PVC 코팅 스크린, 1.0mm" },
    { code: "SCR-003", name: "아크릴 혼방 스크린, 1.5mm" },
    { code: "SCR-004", name: "차광 스크린 (블랙아웃), 1.3mm" },
  ];

  const steelMaterials = [
    { code: "STL-001", name: "알루미늄, 0.8T" },
    { code: "STL-002", name: "스테인리스강, 1.0T" },
    { code: "STL-003", name: "아연도금강판, 0.6T" },
    { code: "STL-004", name: "냉연강판, 0.8T" },
  ];

  // 화면 크기 감지
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < 768);
    };
    
    checkMobile();
    window.addEventListener('resize', checkMobile);
    return () => window.removeEventListener('resize', checkMobile);
  }, []);

  // 데스크톱: 4단계, 모바일: 8단계
  const totalSteps = isMobile ? 8 : 4;

  const desktopSteps = [
    { num: 1, label: "모델명 & 본체", icon: Package, desc: "모델 기본정보 및 본체 선택" },
    { num: 2, label: "절곡물 & 가이드레일", icon: Settings, desc: "케이스 및 가이드레일 구성" },
    { num: 3, label: "마감재 & 모터 & 부자재", icon: Cog, desc: "하단마감재, 모터, 부자재 선택" },
    { num: 4, label: "최종 승인", icon: CheckCircle2, desc: "검증 및 승인" },
  ];

  const mobileSteps = [
    { num: 1, label: "모델명", icon: Package },
    { num: 2, label: "본체", icon: Box },
    { num: 3, label: "절곡물", icon: Grid3x3 },
    { num: 4, label: "가이드레일", icon: Layers },
    { num: 5, label: "하단마감재", icon: Scissors },
    { num: 6, label: "모터구성", icon: Zap },
    { num: 7, label: "부자재", icon: FileText },
    { num: 8, label: "승인", icon: CheckCircle2 },
  ];

  const steps = isMobile ? mobileSteps : desktopSteps;

  const handleSave = () => {
    // 필수 필드 검증
    if (!formData.code || !formData.name) {
      toast.error("모델명과 모델 이름을 입력해주세요.");
      setCurrentStep(1);
      return;
    }
    if (!formData.bodyType) {
      toast.error("본체 유형을 선택해주세요.");
      setCurrentStep(isMobile ? 2 : 1);
      return;
    }
    if (!formData.isApproved) {
      toast.error("최종 승인이 필요합니다.");
      setCurrentStep(isMobile ? 8 : 4);
      return;
    }

    onSave(formData);
  };

  const updateFormData = (updates: Partial<ModelFormData>) => {
    setFormData({ ...formData, ...updates });
  };

  const handleNext = () => {
    if (currentStep < totalSteps) {
      setCurrentStep(currentStep + 1);
    }
  };

  const handlePrev = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
    }
  };

  const toggleCaseComponent = (component: string) => {
    updateFormData({
      caseComponents: {
        ...formData.caseComponents,
        [component]: !formData.caseComponents?.[component as keyof typeof formData.caseComponents],
      },
    });
  };

  const toggleGuideRailComponent = (component: string) => {
    updateFormData({
      guideRailComponents: {
        ...formData.guideRailComponents,
        [component]: !formData.guideRailComponents?.[component as keyof typeof formData.guideRailComponents],
      },
    });
  };

  const toggleBottomFinishComponent = (component: string) => {
    updateFormData({
      bottomFinishComponents: {
        ...formData.bottomFinishComponents,
        [component]: !formData.bottomFinishComponents?.[component as keyof typeof formData.bottomFinishComponents],
      },
    });
  };

  const toggleMotorComponent = (component: string) => {
    updateFormData({
      motorComponents: {
        ...formData.motorComponents,
        [component]: !formData.motorComponents?.[component as keyof typeof formData.motorComponents],
      },
    });
  };

  const toggleSubMaterial = (material: string) => {
    updateFormData({
      subMaterials: {
        ...formData.subMaterials,
        [material]: !formData.subMaterials?.[material as keyof typeof formData.subMaterials],
      },
    });
  };

  // 데스크톱 렌더링
  const renderDesktopStep = () => {
    switch (currentStep) {
      case 1:
        // 모델명 & 본체 (2열 레이아웃)
        return (
          <div className="space-y-6">
            <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
              <div className="flex items-start space-x-3">
                <Package className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
                <div>
                  <h3 className="font-medium text-blue-900">1단계: 모델명 & 본체 선택</h3>
                  <p className="text-sm text-blue-700 mt-1">
                    모델의 기본 정보와 본체 유형을 선택합니다.
                  </p>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 왼쪽: 모델명/모델 이름 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-base flex items-center space-x-2">
                    <Package className="h-5 w-5" />
                    <span>모델 기본정보</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-2">
                    <Label htmlFor="code" className="flex items-center">
                      모델명 <span className="text-red-500 ml-1">*</span>
                    </Label>
                    <Input
                      id="code"
                      placeholder="예: SCR-2025-001"
                      value={formData.code || ""}
                      onChange={(e) => updateFormData({ code: e.target.value })}
                    />
                    <p className="text-xs text-muted-foreground">
                      고유한 모델명을 입력하세요
                    </p>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="name" className="flex items-center">
                      모델 이름 <span className="text-red-500 ml-1">*</span>
                    </Label>
                    <Input
                      id="name"
                      placeholder="예: 스크린 표준형 A타입"
                      value={formData.name || ""}
                      onChange={(e) => updateFormData({ name: e.target.value })}
                    />
                    <p className="text-xs text-muted-foreground">
                      식별 가능한 모델 이름을 입력하세요
                    </p>
                  </div>
                </CardContent>
              </Card>

              {/* 오른쪽: 본체 선택 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-base flex items-center space-x-2">
                    <Box className="h-5 w-5" />
                    <span>본체 선택</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-3">
                    <Label className="flex items-center">
                      본체 유형 <span className="text-red-500 ml-1">*</span>
                    </Label>
                    <RadioGroup
                      value={formData.bodyType || ''}
                      onValueChange={(value: '스크린' | '철재') => updateFormData({ bodyType: value })}
                    >
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="스크린" id="screen" />
                        <Label htmlFor="screen" className="cursor-pointer">
                          스크린 (패브릭 소재)
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="철재" id="steel" />
                        <Label htmlFor="steel" className="cursor-pointer">
                          철재 (금속 소재)
                        </Label>
                      </div>
                    </RadioGroup>
                  </div>

                  {formData.bodyType && (
                    <div className="space-y-2">
                      <Label htmlFor="bodyMaterial">
                        {formData.bodyType} 자재 선택 <span className="text-red-500 ml-1">*</span>
                      </Label>
                      <Select
                        value={formData.bodyMaterial || ""}
                        onValueChange={(value) => updateFormData({ bodyMaterial: value })}
                      >
                        <SelectTrigger id="bodyMaterial">
                          <SelectValue placeholder="자재관리에 등록된 자재를 선택하세요" />
                        </SelectTrigger>
                        <SelectContent>
                          {(formData.bodyType === '스크린' ? screenMaterials : steelMaterials).map((material) => (
                            <SelectItem key={material.code} value={`${material.code} - ${material.name}`}>
                              <div className="flex flex-col">
                                <span className="font-medium">{material.code}</span>
                                <span className="text-xs text-muted-foreground">{material.name}</span>
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <p className="text-xs text-muted-foreground">
                        자재관리에 등록된 자재 목록에서 선택
                      </p>
                    </div>
                  )}

                  <div className="p-3 bg-blue-50 rounded-lg border border-blue-200">
                    <p className="text-xs text-blue-700">
                      <strong>스크린:</strong> 롤스크린, 버티컬 블라인드 등<br />
                      <strong>철재:</strong> 슬랫 블라인드, 절곡 제품 등
                    </p>
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        );

      case 2:
        // 절곡물 & 가이드레일 (2열 레이아웃)
        return (
          <div className="space-y-6">
            <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
              <div className="flex items-start space-x-3">
                <Settings className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
                <div>
                  <h3 className="font-medium text-blue-900">2단계: 절곡물 구성 & 가이드레일</h3>
                  <p className="text-sm text-blue-700 mt-1">
                    케이스 구성요소와 가이드레일 유형을 선택합니다.
                  </p>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 왼쪽: 절곡물 구성그룹 - 케이스 선택 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-base flex items-center space-x-2">
                    <Grid3x3 className="h-5 w-5" />
                    <span>절곡물 구성 - 케이스</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-3">
                    <Label>케이스 구성요소 선택</Label>
                    <div className="space-y-2">
                      {[
                        { id: '점검구', label: '점검구' },
                        { id: '린텔부', label: '린텔부' },
                        { id: '후면코너부', label: '후면코너부' },
                        { id: '상부덮개', label: '상부덮개' },
                        { id: '마구리', label: '마구리' },
                        { id: '연기차단재', label: '연기차단재' },
                      ].map((component) => (
                        <div key={component.id} className="flex items-center space-x-2">
                          <Checkbox
                            id={component.id}
                            checked={formData.caseComponents?.[component.id as keyof typeof formData.caseComponents] || false}
                            onCheckedChange={() => toggleCaseComponent(component.id)}
                          />
                          <Label htmlFor={component.id} className="cursor-pointer">
                            {component.label}
                          </Label>
                        </div>
                      ))}
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="caseDetails">케이스 상세 사양</Label>
                    <Input
                      id="caseDetails"
                      placeholder="예: 아연도금강판 0.8T"
                      value={formData.caseDetails || ""}
                      onChange={(e) => updateFormData({ caseDetails: e.target.value })}
                    />
                  </div>

                  <div className="p-3 bg-gray-50 rounded-lg">
                    <p className="text-xs text-muted-foreground">
                      선택된 구성요소: {
                        Object.entries(formData.caseComponents || {})
                          .filter(([_, value]) => value)
                          .map(([key]) => key)
                          .join(', ') || '없음'
                      }
                    </p>
                  </div>
                </CardContent>
              </Card>

              {/* 오른쪽: 가이드레일 선택 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-base flex items-center space-x-2">
                    <Layers className="h-5 w-5" />
                    <span>가이드레일 선택</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="space-y-3">
                    <Label>가이드레일 유형</Label>
                    <RadioGroup
                      value={formData.guideRailType || ''}
                      onValueChange={(value: '벽면형' | '측면형' | '혼합형') => 
                        updateFormData({ guideRailType: value })
                      }
                    >
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="벽면형" id="wall" />
                        <Label htmlFor="wall" className="cursor-pointer">
                          벽면형
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="측면형" id="side" />
                        <Label htmlFor="side" className="cursor-pointer">
                          측면형
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="혼합형" id="mixed" />
                        <Label htmlFor="mixed" className="cursor-pointer">
                          혼합형
                        </Label>
                      </div>
                    </RadioGroup>
                  </div>

                  {formData.guideRailType && (
                    <>
                      <div className="space-y-3 pt-3 border-t">
                        <Label>가이드레일 구성요소</Label>
                        <div className="space-y-2">
                          {[
                            { id: '마감재', label: '마감재' },
                            { id: '본체1_가이드레일', label: '본체1 (가이드레일)' },
                            { id: '본체2_가이드레일', label: '본체2 (가이드레일)' },
                            { id: 'C형', label: 'C형' },
                            { id: 'D형', label: 'D형' },
                            { id: '연기차단제', label: '연기차단제' },
                            { id: '별도마감제', label: '별도마감제' },
                          ].map((component) => (
                            <div key={component.id} className="flex items-center space-x-2">
                              <Checkbox
                                id={`guide-${component.id}`}
                                checked={formData.guideRailComponents?.[component.id as keyof typeof formData.guideRailComponents] || false}
                                onCheckedChange={() => toggleGuideRailComponent(component.id)}
                              />
                              <Label htmlFor={`guide-${component.id}`} className="cursor-pointer text-sm">
                                {component.label}
                              </Label>
                            </div>
                          ))}
                        </div>
                      </div>

                      <div className="p-3 bg-gray-50 rounded-lg">
                        <p className="text-xs text-muted-foreground">
                          선택된 구성요소: {
                            Object.entries(formData.guideRailComponents || {})
                              .filter(([_, value]) => value)
                              .map(([key]) => key.replace('_', ' '))
                              .join(', ') || '없음'
                          }
                        </p>
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>
            </div>
          </div>
        );

      case 3:
        // 하단마감재 & 모터 & 부자재 (3열 레이아웃)
        return (
          <div className="space-y-6">
            <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
              <div className="flex items-start space-x-3">
                <Cog className="h-5 w-5 text-blue-600 mt-0.5 flex-shrink-0" />
                <div>
                  <h3 className="font-medium text-blue-900">3단계: 하단마감재 & 모터구성 & 부자재</h3>
                  <p className="text-sm text-blue-700 mt-1">
                    하단 마감재, 모터 구성, 부자재를 선택합니다.
                  </p>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
              {/* 하단마감재 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm flex items-center space-x-2">
                    <Scissors className="h-4 w-4" />
                    <span>하단마감재</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <Label className="text-xs">본체 하단 구성요소</Label>
                  <div className="space-y-2">
                    {[
                      { id: '하장바', label: '하장바' },
                      { id: '보강엘바', label: '보강엘바' },
                      { id: '보강평철', label: '보강평철' },
                      { id: '무게평철', label: '무게평철' },
                    ].map((component) => (
                      <div key={component.id} className="flex items-center space-x-2">
                        <Checkbox
                          id={`bottom-${component.id}`}
                          checked={formData.bottomFinishComponents?.[component.id as keyof typeof formData.bottomFinishComponents] || false}
                          onCheckedChange={() => toggleBottomFinishComponent(component.id)}
                        />
                        <Label htmlFor={`bottom-${component.id}`} className="cursor-pointer text-sm">
                          {component.label}
                        </Label>
                      </div>
                    ))}
                  </div>
                  <div className="p-2 bg-gray-50 rounded text-xs text-muted-foreground">
                    선택: {
                      Object.entries(formData.bottomFinishComponents || {})
                        .filter(([_, value]) => value)
                        .map(([key]) => key)
                        .join(', ') || '없음'
                    }
                  </div>
                </CardContent>
              </Card>

              {/* 모터구성 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm flex items-center space-x-2">
                    <Zap className="h-4 w-4" />
                    <span>모터구성</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <Label className="text-xs">모터 구성요소</Label>
                  <div className="space-y-2">
                    {[
                      { id: '모터', label: '모터' },
                      { id: '브라켓', label: '브라켓' },
                    ].map((component) => (
                      <div key={component.id} className="flex items-center space-x-2">
                        <Checkbox
                          id={`motor-${component.id}`}
                          checked={formData.motorComponents?.[component.id as keyof typeof formData.motorComponents] || false}
                          onCheckedChange={() => toggleMotorComponent(component.id)}
                        />
                        <Label htmlFor={`motor-${component.id}`} className="cursor-pointer text-sm">
                          {component.label}
                        </Label>
                      </div>
                    ))}
                  </div>

                  {formData.motorComponents?.모터 && (
                    <>
                      <div className="space-y-2 pt-2 border-t">
                        <Label className="text-xs">모터 유형</Label>
                        <Select
                          value={formData.motorType || ""}
                          onValueChange={(value) => updateFormData({ motorType: value })}
                        >
                          <SelectTrigger>
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="튜블러모터">튜블러 모터</SelectItem>
                            <SelectItem value="체인모터">체인 모터</SelectItem>
                            <SelectItem value="외장모터">외장 모터</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div className="space-y-2">
                        <Label className="text-xs">모터 규격</Label>
                        <Input
                          placeholder="예: 35mm, 6Nm"
                          value={formData.motorSpec || ""}
                          onChange={(e) => updateFormData({ motorSpec: e.target.value })}
                        />
                      </div>
                    </>
                  )}
                </CardContent>
              </Card>

              {/* 부자재 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-sm flex items-center space-x-2">
                    <FileText className="h-4 w-4" />
                    <span>부자재</span>
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <Label className="text-xs">부자재 선택</Label>
                  <div className="space-y-2">
                    {[
                      { id: '감기샤프트', label: '감기샤프트' },
                      { id: '각파이프', label: '각파이프' },
                      { id: '앵글', label: '앵글' },
                    ].map((material) => (
                      <div key={material.id} className="flex items-center space-x-2">
                        <Checkbox
                          id={`sub-${material.id}`}
                          checked={formData.subMaterials?.[material.id as keyof typeof formData.subMaterials] || false}
                          onCheckedChange={() => toggleSubMaterial(material.id)}
                        />
                        <Label htmlFor={`sub-${material.id}`} className="cursor-pointer text-sm">
                          {material.label}
                        </Label>
                      </div>
                    ))}
                  </div>

                  <div className="space-y-2 pt-2 border-t">
                    <Label className="text-xs">부자재 상세</Label>
                    <Input
                      placeholder="예: Ø60mm, 1.2T"
                      value={formData.subMaterialDetails || ""}
                      onChange={(e) => updateFormData({ subMaterialDetails: e.target.value })}
                    />
                  </div>

                  <div className="p-2 bg-gray-50 rounded text-xs text-muted-foreground">
                    선택: {
                      Object.entries(formData.subMaterials || {})
                        .filter(([_, value]) => value)
                        .map(([key]) => key)
                        .join(', ') || '없음'
                    }
                  </div>
                </CardContent>
              </Card>
            </div>
          </div>
        );

      case 4:
        // 최종 승인
        return (
          <div className="space-y-6">
            <div className="bg-green-50 p-4 rounded-lg border border-green-200">
              <div className="flex items-start space-x-3">
                <CheckCircle2 className="h-5 w-5 text-green-600 mt-0.5 flex-shrink-0" />
                <div>
                  <h3 className="font-medium text-green-900">4단계: 모델 설정 완료</h3>
                  <p className="text-sm text-green-700 mt-1">
                    입력한 모든 정보를 확인하고 모델 등록을 완료합니다.
                  </p>
                </div>
              </div>
            </div>

            {/* 입력 정보 요약 */}
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
              <Card>
                <CardHeader>
                  <CardTitle className="text-base">기본 정보</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="grid grid-cols-2 gap-y-2 text-sm">
                    <span className="text-muted-foreground">모델 코드:</span>
                    <span className="font-medium">{formData.code || "-"}</span>
                    
                    <span className="text-muted-foreground">모델명:</span>
                    <span className="font-medium">{formData.name || "-"}</span>
                    
                    <span className="text-muted-foreground">본체 유형:</span>
                    <Badge variant="outline">{formData.bodyType || "-"}</Badge>
                    
                    <span className="text-muted-foreground">본체 재질:</span>
                    <span className="font-medium text-xs">{formData.bodyMaterial || "-"}</span>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-base">절곡물 & 가이드레일</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="space-y-2 text-sm">
                    <div>
                      <span className="text-muted-foreground text-xs">케이스 구성:</span>
                      <p className="font-medium text-xs mt-1">
                        {Object.entries(formData.caseComponents || {})
                          .filter(([_, value]) => value)
                          .map(([key]) => key)
                          .join(', ') || '선택 안함'}
                      </p>
                    </div>
                    
                    <div className="pt-2 border-t">
                      <span className="text-muted-foreground text-xs">가이드레일:</span>
                      <p className="font-medium text-xs mt-1">
                        {formData.guideRailType || '-'}
                      </p>
                    </div>

                    <div>
                      <span className="text-muted-foreground text-xs">가이드레일 구성:</span>
                      <p className="font-medium text-xs mt-1">
                        {Object.entries(formData.guideRailComponents || {})
                          .filter(([_, value]) => value)
                          .map(([key]) => key.replace('_', ' '))
                          .join(', ') || '선택 안함'}
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-base">하단마감재</CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    {Object.entries(formData.bottomFinishComponents || {})
                      .filter(([_, value]) => value)
                      .map(([key]) => (
                        <Badge key={key} variant="secondary" className="mr-1">
                          {key}
                        </Badge>
                      ))}
                    {Object.values(formData.bottomFinishComponents || {}).every(v => !v) && (
                      <p className="text-sm text-muted-foreground">선택 안함</p>
                    )}
                  </div>
                </CardContent>
              </Card>

              <Card>
                <CardHeader>
                  <CardTitle className="text-base">모터 & 부자재</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <div className="space-y-2 text-sm">
                    <div>
                      <span className="text-muted-foreground text-xs">모터 구성:</span>
                      <p className="font-medium text-xs mt-1">
                        {Object.entries(formData.motorComponents || {})
                          .filter(([_, value]) => value)
                          .map(([key]) => key)
                          .join(', ') || '선택 안함'}
                      </p>
                      {formData.motorType && (
                        <p className="text-xs text-muted-foreground mt-1">
                          {formData.motorType} {formData.motorSpec && `(${formData.motorSpec})`}
                        </p>
                      )}
                    </div>

                    <div className="pt-2 border-t">
                      <span className="text-muted-foreground text-xs">부자재:</span>
                      <p className="font-medium text-xs mt-1">
                        {Object.entries(formData.subMaterials || {})
                          .filter(([_, value]) => value)
                          .map(([key]) => key)
                          .join(', ') || '선택 안함'}
                      </p>
                      {formData.subMaterialDetails && (
                        <p className="text-xs text-muted-foreground mt-1">
                          {formData.subMaterialDetails}
                        </p>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            </div>

            {/* 최종 승인 */}
            <Card className="border-green-200 bg-green-50">
              <CardContent className="pt-6">
                <div className="flex items-center space-x-3">
                  <Checkbox
                    id="isApproved"
                    checked={formData.isApproved || false}
                    onCheckedChange={(checked) => updateFormData({ isApproved: checked as boolean })}
                  />
                  <Label htmlFor="isApproved" className="text-base font-medium cursor-pointer">
                    위의 모든 정보를 확인했으며, 모델 설정을 완료하고 등록합니다.
                  </Label>
                </div>
              </CardContent>
            </Card>
          </div>
        );

      default:
        return null;
    }
  };

  // 모바일 렌더링
  const renderMobileStep = () => {
    switch (currentStep) {
      case 1:
        // 모델명
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">모델 기본정보</h3>
              <p className="text-xs text-blue-700 mt-1">모델명과 모델 이름을 입력합니다.</p>
            </div>

            <div className="space-y-3">
              <div className="space-y-2">
                <Label htmlFor="code">모델명 <span className="text-red-500">*</span></Label>
                <Input
                  id="code"
                  placeholder="예: SCR-2025-001"
                  value={formData.code || ""}
                  onChange={(e) => updateFormData({ code: e.target.value })}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="name">모델 이름 <span className="text-red-500">*</span></Label>
                <Input
                  id="name"
                  placeholder="예: 스크린 표준형 A타입"
                  value={formData.name || ""}
                  onChange={(e) => updateFormData({ name: e.target.value })}
                />
              </div>
            </div>
          </div>
        );

      case 2:
        // 본체
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">본체 선택</h3>
              <p className="text-xs text-blue-700 mt-1">본체 유형과 자재를 선택합니다.</p>
            </div>

            <div className="space-y-3">
              <div className="space-y-2">
                <Label>본체 유형 <span className="text-red-500">*</span></Label>
                <RadioGroup
                  value={formData.bodyType || ''}
                  onValueChange={(value: '스크린' | '철재') => updateFormData({ bodyType: value })}
                >
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="스크린" id="screen-m" />
                    <Label htmlFor="screen-m" className="cursor-pointer">
                      스크린 (패브릭 소재)
                    </Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="철재" id="steel-m" />
                    <Label htmlFor="steel-m" className="cursor-pointer">
                      철재 (금속 소재)
                    </Label>
                  </div>
                </RadioGroup>
              </div>

              {formData.bodyType && (
                <div className="space-y-2">
                  <Label htmlFor="bodyMaterial">{formData.bodyType} 자재 선택 <span className="text-red-500">*</span></Label>
                  <Select
                    value={formData.bodyMaterial || ""}
                    onValueChange={(value) => updateFormData({ bodyMaterial: value })}
                  >
                    <SelectTrigger id="bodyMaterial">
                      <SelectValue placeholder="자재 선택" />
                    </SelectTrigger>
                    <SelectContent>
                      {(formData.bodyType === '스크린' ? screenMaterials : steelMaterials).map((material) => (
                        <SelectItem key={material.code} value={`${material.code} - ${material.name}`}>
                          <div className="flex flex-col">
                            <span className="font-medium text-sm">{material.code}</span>
                            <span className="text-xs text-muted-foreground">{material.name}</span>
                          </div>
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">
                    자재관리에 등록된 자재
                  </p>
                </div>
              )}
            </div>
          </div>
        );

      case 3:
        // 절곡물
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">절곡물 구성 - 케이스</h3>
              <p className="text-xs text-blue-700 mt-1">케이스 구성요소를 선택합니다.</p>
            </div>

            <div className="space-y-3">
              <Label>케이스 구성요소</Label>
              <div className="space-y-2">
                {[
                  { id: '점검구', label: '점검구' },
                  { id: '린텔부', label: '린텔부' },
                  { id: '후면코너부', label: '후면코너부' },
                  { id: '상부덮개', label: '상부덮개' },
                  { id: '마구리', label: '마구리' },
                  { id: '연기차단재', label: '연기차단재' },
                ].map((component) => (
                  <div key={component.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={`m-${component.id}`}
                      checked={formData.caseComponents?.[component.id as keyof typeof formData.caseComponents] || false}
                      onCheckedChange={() => toggleCaseComponent(component.id)}
                    />
                    <Label htmlFor={`m-${component.id}`} className="cursor-pointer">
                      {component.label}
                    </Label>
                  </div>
                ))}
              </div>

              <div className="space-y-2 pt-2">
                <Label htmlFor="caseDetails">상세 사양</Label>
                <Input
                  id="caseDetails"
                  placeholder="예: 아연도금강판 0.8T"
                  value={formData.caseDetails || ""}
                  onChange={(e) => updateFormData({ caseDetails: e.target.value })}
                />
              </div>
            </div>
          </div>
        );

      case 4:
        // 가이드레일
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">가이드레일</h3>
              <p className="text-xs text-blue-700 mt-1">가이드레일 유형과 구성요소를 선택합니다.</p>
            </div>

            <div className="space-y-3">
              <div className="space-y-2">
                <Label>가이드레일 유형</Label>
                <RadioGroup
                  value={formData.guideRailType || ''}
                  onValueChange={(value: '벽면형' | '측면형' | '혼합형') => 
                    updateFormData({ guideRailType: value })
                  }
                >
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="벽면형" id="wall-m" />
                    <Label htmlFor="wall-m" className="cursor-pointer">벽면형</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="측면형" id="side-m" />
                    <Label htmlFor="side-m" className="cursor-pointer">측면형</Label>
                  </div>
                  <div className="flex items-center space-x-2">
                    <RadioGroupItem value="혼합형" id="mixed-m" />
                    <Label htmlFor="mixed-m" className="cursor-pointer">혼합형</Label>
                  </div>
                </RadioGroup>
              </div>

              {formData.guideRailType && (
                <div className="space-y-2 pt-2 border-t">
                  <Label>구성요소</Label>
                  <div className="space-y-2">
                    {[
                      { id: '마감재', label: '마감재' },
                      { id: '본체1_가이드레일', label: '본체1 (가이드레일)' },
                      { id: '본체2_가이드레일', label: '본체2 (가이드레일)' },
                      { id: 'C형', label: 'C형' },
                      { id: 'D형', label: 'D형' },
                      { id: '연기차단제', label: '연기차단제' },
                      { id: '별도마감제', label: '별도마감제' },
                    ].map((component) => (
                      <div key={component.id} className="flex items-center space-x-2">
                        <Checkbox
                          id={`m-guide-${component.id}`}
                          checked={formData.guideRailComponents?.[component.id as keyof typeof formData.guideRailComponents] || false}
                          onCheckedChange={() => toggleGuideRailComponent(component.id)}
                        />
                        <Label htmlFor={`m-guide-${component.id}`} className="cursor-pointer text-sm">
                          {component.label}
                        </Label>
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        );

      case 5:
        // 하단마감재
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">하단마감재</h3>
              <p className="text-xs text-blue-700 mt-1">본체 하단 구성요소를 선택합니다.</p>
            </div>

            <div className="space-y-3">
              <Label>하단 구성요소</Label>
              <div className="space-y-2">
                {[
                  { id: '하장바', label: '하장바' },
                  { id: '보강엘바', label: '보강엘바' },
                  { id: '보강평철', label: '보강평철' },
                  { id: '무게평철', label: '무게평철' },
                ].map((component) => (
                  <div key={component.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={`m-bottom-${component.id}`}
                      checked={formData.bottomFinishComponents?.[component.id as keyof typeof formData.bottomFinishComponents] || false}
                      onCheckedChange={() => toggleBottomFinishComponent(component.id)}
                    />
                    <Label htmlFor={`m-bottom-${component.id}`} className="cursor-pointer">
                      {component.label}
                    </Label>
                  </div>
                ))}
              </div>
            </div>
          </div>
        );

      case 6:
        // 모터구성
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">모터구성</h3>
              <p className="text-xs text-blue-700 mt-1">모터와 브라켓을 선택합니다.</p>
            </div>

            <div className="space-y-3">
              <Label>모터 구성요소</Label>
              <div className="space-y-2">
                {[
                  { id: '모터', label: '모터' },
                  { id: '브라켓', label: '브라켓' },
                ].map((component) => (
                  <div key={component.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={`m-motor-${component.id}`}
                      checked={formData.motorComponents?.[component.id as keyof typeof formData.motorComponents] || false}
                      onCheckedChange={() => toggleMotorComponent(component.id)}
                    />
                    <Label htmlFor={`m-motor-${component.id}`} className="cursor-pointer">
                      {component.label}
                    </Label>
                  </div>
                ))}
              </div>

              {formData.motorComponents?.모터 && (
                <>
                  <div className="space-y-2 pt-2 border-t">
                    <Label>모터 유형</Label>
                    <Select
                      value={formData.motorType || ""}
                      onValueChange={(value) => updateFormData({ motorType: value })}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="선택하세요" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="튜블러모터">튜블러 모터</SelectItem>
                        <SelectItem value="체인모터">체인 모터</SelectItem>
                        <SelectItem value="외장모터">외장 모터</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>모터 규격</Label>
                    <Input
                      placeholder="예: 35mm, 6Nm"
                      value={formData.motorSpec || ""}
                      onChange={(e) => updateFormData({ motorSpec: e.target.value })}
                    />
                  </div>
                </>
              )}
            </div>
          </div>
        );

      case 7:
        // 부자재
        return (
          <div className="space-y-4">
            <div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
              <h3 className="font-medium text-blue-900 text-sm">부자재</h3>
              <p className="text-xs text-blue-700 mt-1">필요한 부자재를 선택합니다.</p>
            </div>

            <div className="space-y-3">
              <Label>부자재 선택</Label>
              <div className="space-y-2">
                {[
                  { id: '감기샤프트', label: '감기샤프트' },
                  { id: '각파이프', label: '각파이프' },
                  { id: '앵글', label: '앵글' },
                ].map((material) => (
                  <div key={material.id} className="flex items-center space-x-2">
                    <Checkbox
                      id={`m-sub-${material.id}`}
                      checked={formData.subMaterials?.[material.id as keyof typeof formData.subMaterials] || false}
                      onCheckedChange={() => toggleSubMaterial(material.id)}
                    />
                    <Label htmlFor={`m-sub-${material.id}`} className="cursor-pointer">
                      {material.label}
                    </Label>
                  </div>
                ))}
              </div>

              <div className="space-y-2 pt-2">
                <Label>부자재 상세</Label>
                <Input
                  placeholder="예: Ø60mm, 1.2T"
                  value={formData.subMaterialDetails || ""}
                  onChange={(e) => updateFormData({ subMaterialDetails: e.target.value })}
                />
              </div>
            </div>
          </div>
        );

      case 8:
        // 승인
        return (
          <div className="space-y-4">
            <div className="bg-green-50 p-3 rounded-lg border border-green-200">
              <h3 className="font-medium text-green-900 text-sm">모델 설정 완료</h3>
              <p className="text-xs text-green-700 mt-1">모든 정보를 확인하고 승인합니다.</p>
            </div>

            {/* 요약 정보 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">입력 정보 요약</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">모델 코드:</span>
                  <span className="font-medium">{formData.code || "-"}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">모델명:</span>
                  <span className="font-medium">{formData.name || "-"}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">본체:</span>
                  <Badge variant="outline">{formData.bodyType || "-"}</Badge>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">가이드레일:</span>
                  <span className="font-medium">{formData.guideRailType || "-"}</span>
                </div>
              </CardContent>
            </Card>

            {/* 승인 */}
            <Card className="border-green-200 bg-green-50">
              <CardContent className="pt-4">
                <div className="flex items-start space-x-3">
                  <Checkbox
                    id="isApproved-m"
                    checked={formData.isApproved || false}
                    onCheckedChange={(checked) => updateFormData({ isApproved: checked as boolean })}
                  />
                  <Label htmlFor="isApproved-m" className="text-sm cursor-pointer">
                    위의 모든 정보를 확인했으며, 모델 설정을 완료하고 등록합니다.
                  </Label>
                </div>
              </CardContent>
            </Card>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 p-3 md:p-6">
      {/* 헤더 */}
      <div className="max-w-7xl mx-auto mb-4 md:mb-6">
        <div className="flex items-center justify-between mb-3 md:mb-4">
          <div className="flex items-center space-x-2 md:space-x-3">
            <Button variant="ghost" size="sm" onClick={onCancel}>
              <ArrowLeft className="h-4 w-4 mr-2" />
              목록으로
            </Button>
            <div className="h-5 md:h-6 w-px bg-gray-300" />
            <div>
              <h1 className="text-lg md:text-2xl font-semibold">신규 모델 등록</h1>
              <p className="text-xs md:text-sm text-muted-foreground hidden sm:block">
                스크린/슬랫/절곡 제품 모델 템플릿 등록
              </p>
            </div>
          </div>
          <Badge variant="outline">
            {currentStep} / {totalSteps}
          </Badge>
        </div>

        {/* 단계 진행 표시 */}
        <Card>
          <CardContent className="pt-4 md:pt-6">
            <div className="flex items-center justify-between overflow-x-auto pb-2">
              {steps.map((step, idx) => (
                <div key={step.num} className="flex items-center flex-shrink-0">
                  <div className="flex flex-col items-center">
                    <div
                      className={`w-8 h-8 md:w-10 md:h-10 rounded-full flex items-center justify-center transition-all ${
                        currentStep >= step.num
                          ? "bg-blue-600 text-white"
                          : "bg-gray-200 text-gray-500"
                      }`}
                    >
                      {currentStep > step.num ? (
                        <span className="text-xs md:text-sm">✓</span>
                      ) : (
                        <step.icon className="h-4 w-4" />
                      )}
                    </div>
                    <p className="text-xs mt-1 md:mt-2 text-center whitespace-nowrap">
                      {step.label}
                    </p>
                  </div>
                  {idx < steps.length - 1 && (
                    <div
                      className={`w-6 md:w-12 h-1 mx-1 md:mx-2 transition-all ${
                        currentStep > step.num ? "bg-blue-600" : "bg-gray-200"
                      }`}
                    />
                  )}
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 메인 컨텐츠 */}
      <div className="max-w-7xl mx-auto">
        <Card>
          <CardContent className="pt-4 md:pt-6">
            {isMobile ? renderMobileStep() : renderDesktopStep()}
          </CardContent>
        </Card>

        {/* 하단 버튼 */}
        <div className="flex items-center justify-between mt-4 md:mt-6 gap-3">
          <Button
            variant="outline"
            onClick={handlePrev}
            disabled={currentStep === 1}
            className="flex-1 md:flex-none"
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            이전
          </Button>

          <div className="flex-1 md:flex-none" />

          {currentStep < totalSteps ? (
            <Button onClick={handleNext} className="flex-1 md:flex-none">
              다음
              <ArrowRight className="h-4 w-4 ml-2" />
            </Button>
          ) : (
            <Button
              onClick={handleSave}
              disabled={!formData.isApproved}
              className="flex-1 md:flex-none samsung-button"
            >
              <Save className="h-4 w-4 mr-2" />
              등록 완료
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
