/**
 * 조립 부품 (ASSEMBLY) 폼 컴포넌트
 * - 가이드레일, 케이스, 하단마감재
 */

import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { NumberInput } from '@/components/ui/number-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import type { UseFormRegister, UseFormSetValue, FieldErrors } from 'react-hook-form';
import type { CreateItemFormData } from '@/lib/utils/validation';

export interface AssemblyPartFormProps {
  selectedCategory1: string;
  setSelectedCategory1: (value: string) => void;
  selectedInstallationType: string;
  setSelectedInstallationType: (value: string) => void;
  sideSpecWidth: string;
  setSideSpecWidth: (value: string) => void;
  sideSpecHeight: string;
  setSideSpecHeight: (value: string) => void;
  assemblyLength: string;
  setAssemblyLength: (value: string) => void;
  assemblyUnit: string;
  setAssemblyUnit: (value: string) => void;
  partStatus: string;
  setPartStatus: (value: string) => void;
  needsBOM: boolean;
  setNeedsBOM: (value: boolean) => void;
  register: UseFormRegister<CreateItemFormData>;
  setValue: UseFormSetValue<CreateItemFormData>;
  errors: FieldErrors<CreateItemFormData>;
}

export default function AssemblyPartForm({
  selectedCategory1,
  setSelectedCategory1,
  selectedInstallationType,
  setSelectedInstallationType,
  sideSpecWidth,
  setSideSpecWidth,
  sideSpecHeight,
  setSideSpecHeight,
  assemblyLength,
  setAssemblyLength,
  assemblyUnit,
  setAssemblyUnit,
  partStatus,
  setPartStatus,
  needsBOM,
  setNeedsBOM,
  register,
  setValue,
  errors,
}: AssemblyPartFormProps) {
  return (
    <>
      <div>
        <Label>
          품목명 <span className="text-red-500">*</span>
        </Label>
        <Select
          value={selectedCategory1}
          onValueChange={(value) => {
            setSelectedCategory1(value);
            setValue('category1', value);
            if (value === 'guide_rail') setValue('itemName', '가이드레일');
            else if (value === 'case') setValue('itemName', '케이스');
            else if (value === 'bottom_finish') setValue('itemName', '하단마감재');
          }}
        >
          <SelectTrigger className={errors.category1 ? 'border-red-500' : ''}>
            <SelectValue placeholder="품목명을 선택하세요" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="guide_rail">가이드레일</SelectItem>
            <SelectItem value="case">케이스</SelectItem>
            <SelectItem value="bottom_finish">하단마감재</SelectItem>
          </SelectContent>
        </Select>
        {errors.category1 && (
          <p className="text-xs text-red-500 mt-1">
            {errors.category1.message}
          </p>
        )}
      </div>

      {/* 가이드레일: 설치 유형 */}
      {selectedCategory1 === 'guide_rail' && (
        <div>
          <Label>
            설치 유형 <span className="text-red-500">*</span>
          </Label>
          <Select
            value={selectedInstallationType}
            onValueChange={(value) => {
              setSelectedInstallationType(value);
              setValue('installationType', value);
              setValue('category2', value === 'wall' ? 'R' : 'S');
            }}
          >
            <SelectTrigger>
              <SelectValue placeholder="설치 유형을 선택하세요" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="wall">벽면형 (R)</SelectItem>
              <SelectItem value="side">측면형 (S)</SelectItem>
            </SelectContent>
          </Select>
        </div>
      )}

      {/* 케이스: 설치 유형 */}
      {selectedCategory1 === 'case' && (
        <div>
          <Label>
            설치 유형 <span className="text-red-500">*</span>
          </Label>
          <Select
            value={selectedInstallationType}
            onValueChange={(value) => {
              setSelectedInstallationType(value);
              setValue('installationType', value);
              setValue('category2', 'C');
            }}
          >
            <SelectTrigger>
              <SelectValue placeholder="설치 유형을 선택하세요" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="standard">표준형 (C)</SelectItem>
            </SelectContent>
          </Select>
        </div>
      )}

      {/* 하단마감재: 설치 유형 */}
      {selectedCategory1 === 'bottom_finish' && (
        <div>
          <Label>
            설치 유형 <span className="text-red-500">*</span>
          </Label>
          <Select
            value={selectedInstallationType}
            onValueChange={(value) => {
              setSelectedInstallationType(value);
              setValue('installationType', value);
              setValue('category2', value === 'steel' ? 'B' : 'T');
            }}
          >
            <SelectTrigger>
              <SelectValue placeholder="설치 유형을 선택하세요" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="steel">스크린 (B)</SelectItem>
              <SelectItem value="iron">철재 (T)</SelectItem>
            </SelectContent>
          </Select>
        </div>
      )}

      {/* ASSEMBLY 공통: 단위, 비고, 측면규격 및 길이 */}
      <div>
        <Label>
          단위 <span className="text-red-500">*</span>
        </Label>
        <Select
          value={assemblyUnit}
          onValueChange={(value) => {
            setAssemblyUnit(value);
            setValue('unit', value);
          }}
        >
          <SelectTrigger>
            <SelectValue placeholder="단위를 선택하세요" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="EA">EA (개)</SelectItem>
            <SelectItem value="M">M (미터)</SelectItem>
            <SelectItem value="mm">mm (밀리미터)</SelectItem>
            <SelectItem value="SET">SET (세트)</SelectItem>
            <SelectItem value="KG">KG (킬로그램)</SelectItem>
          </SelectContent>
        </Select>
      </div>

      <div className="md:col-span-2">
        <Label>비고</Label>
        <Input
          placeholder="비고 사항을 입력하세요"
          {...register('note')}
        />
      </div>

      {/* 측면 규격 및 길이 */}
      <div className="col-span-2 border-t pt-4">
        <h4 className="text-sm font-semibold mb-3">측면 규격 및 길이</h4>
        <div className="grid grid-cols-3 gap-3">
          <div>
            <Label>
              측면 규격 (가로) <span className="text-red-500">*</span>
            </Label>
            <NumberInput
              placeholder="예: 50"
              value={parseFloat(sideSpecWidth) || 0}
              onChange={(value) => {
                const strValue = String(value ?? 0);
                setSideSpecWidth(strValue);
                setValue('sideSpecWidth', strValue);
              }}
            />
          </div>
          <div>
            <Label>
              측면 규격 (세로) <span className="text-red-500">*</span>
            </Label>
            <NumberInput
              placeholder="예: 100"
              value={parseFloat(sideSpecHeight) || 0}
              onChange={(value) => {
                const strValue = String(value ?? 0);
                setSideSpecHeight(strValue);
                setValue('sideSpecHeight', strValue);
              }}
            />
          </div>
          <div>
            <Label>
              길이 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={assemblyLength}
              onValueChange={(value) => {
                setAssemblyLength(value);
                setValue('assemblyLength', value);
              }}
            >
              <SelectTrigger>
                <SelectValue placeholder="길이를 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="1219">1219mm</SelectItem>
                <SelectItem value="2438">2438mm</SelectItem>
                <SelectItem value="3000">3000mm</SelectItem>
                <SelectItem value="3500">3500mm</SelectItem>
                <SelectItem value="4000">4000mm</SelectItem>
                <SelectItem value="4150">4150mm</SelectItem>
                <SelectItem value="4200">4200mm</SelectItem>
                <SelectItem value="4300">4300mm</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>
        <p className="text-xs text-muted-foreground mt-2">
          * 품목코드: {(() => {
            const itemName = selectedCategory1 === 'guide_rail' ? '가이드레일' :
                            selectedCategory1 === 'case' ? '케이스' :
                            selectedCategory1 === 'bottom_finish' ? '하단마감재' : '';
            const installationTypeMap: Record<string, string> = {
              "standard": "표준형",
              "wall": "벽면형",
              "side": "측면형",
              "steel": "스크린",
              "iron": "철재"
            };
            const installTypeText = installationTypeMap[selectedInstallationType] || selectedInstallationType;
            const length = assemblyLength ? parseInt(assemblyLength) : 0;
            let lengthCode = "";
            if (length === 1219) lengthCode = "12";
            else if (length === 2438) lengthCode = "24";
            else if (length === 3000) lengthCode = "30";
            else if (length === 3500) lengthCode = "35";
            else if (length === 4000) lengthCode = "40";
            else if (length === 4150) lengthCode = "41";
            else if (length === 4200) lengthCode = "42";
            else if (length === 4300) lengthCode = "43";
            else lengthCode = Math.floor(length / 100).toString().padStart(2, '0');

            if (itemName && installTypeText && sideSpecWidth && sideSpecHeight && assemblyLength) {
              return `${itemName} ${installTypeText}-${sideSpecWidth}*${sideSpecHeight}*${lengthCode}`;
            }
            return "품목명 설치유형-?*?*?";
          })()}
        </p>

        {/* 품목 상태 */}
        <div className="mt-4">
          <Label>품목 상태</Label>
          <Select
            value={partStatus}
            onValueChange={(value) => {
              setPartStatus(value);
              setValue('isActive', value === 'true');
            }}
          >
            <SelectTrigger>
              <SelectValue placeholder="품목 상태" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="true">활성</SelectItem>
              <SelectItem value="false">비활성</SelectItem>
            </SelectContent>
          </Select>
          <p className="text-xs text-muted-foreground mt-1">
            * 비활성 시 품목 사용이 제한됩니다
          </p>
        </div>

        {/* 부품구성 (BOM) 필요 여부 - ASSEMBLY 전용 */}
        {selectedCategory1 && (
          <div className="pt-6 mt-6 border-t">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="needsBOM-assembly"
                checked={needsBOM}
                onCheckedChange={(checked) => setNeedsBOM(checked as boolean)}
              />
              <Label htmlFor="needsBOM-assembly" className="cursor-pointer">
                부품구성 (BOM) 필요
              </Label>
            </div>
            <p className="text-xs text-muted-foreground mt-1 ml-6">
              * 이 부품이 하위 구성품을 포함하는 경우 체크하세요
            </p>
          </div>
        )}
      </div>
    </>
  );
}