/**
 * 구매 부품 (PURCHASED) 폼 컴포넌트
 * - 전동개폐기, 모터, 체인 등
 */

import { useMemo } from 'react';
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 { QuantityInput } from '@/components/ui/quantity-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';
import { PART_TYPE_CATEGORIES } from '../../constants';
import { generatePurchasedItemCode } from '@/components/items/DynamicItemForm/utils/itemCodeGenerator';

export interface PurchasedPartFormProps {
  selectedCategory1: string;
  setSelectedCategory1: (value: string) => void;
  electricOpenerPower: string;
  setElectricOpenerPower: (value: string) => void;
  electricOpenerCapacity: string;
  setElectricOpenerCapacity: (value: string) => void;
  motorVoltage: string;
  setMotorVoltage: (value: string) => void;
  chainSpec: string;
  setChainSpec: (value: string) => void;
  partUnit: string;
  setPartUnit: (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 PurchasedPartForm({
  selectedCategory1,
  setSelectedCategory1,
  electricOpenerPower,
  setElectricOpenerPower,
  electricOpenerCapacity,
  setElectricOpenerCapacity,
  motorVoltage,
  setMotorVoltage,
  chainSpec,
  setChainSpec,
  partUnit,
  setPartUnit,
  partStatus,
  setPartStatus,
  needsBOM,
  setNeedsBOM,
  register,
  setValue,
  errors,
}: PurchasedPartFormProps) {
  // 전동개폐기 품목코드 자동생성 (품목명 + 용량 + 전원)
  const generatedItemCode = useMemo(() => {
    if (selectedCategory1 === 'electric_opener') {
      const category = PART_TYPE_CATEGORIES.PURCHASED?.categories.find(
        c => c.value === selectedCategory1
      );
      const itemName = category?.label || '';
      return generatePurchasedItemCode(itemName, electricOpenerCapacity, electricOpenerPower);
    }
    return '';
  }, [selectedCategory1, electricOpenerCapacity, electricOpenerPower]);

  return (
    <>
      {/* 품목명 선택 */}
      <div>
        <Label>
          품목명 <span className="text-red-500">*</span>
        </Label>
        <Select
          value={selectedCategory1}
          onValueChange={(val) => {
            setSelectedCategory1(val);
            setValue('category1', val);
            const cat = PART_TYPE_CATEGORIES.PURCHASED?.categories.find(c => c.value === val);
            if (cat) {
              setValue('category2', cat.code);
            }
          }}
        >
          <SelectTrigger>
            <SelectValue placeholder="품목명을 선택하세요" />
          </SelectTrigger>
          <SelectContent>
            {PART_TYPE_CATEGORIES.PURCHASED?.categories.map((cat) => (
              <SelectItem key={cat.value} value={cat.value}>
                {cat.label} ({cat.code})
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 전동개폐기 전용 필드 */}
      {selectedCategory1 === 'electric_opener' && (
        <>
          <div>
            <Label>
              전원 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={electricOpenerPower}
              onValueChange={(value) => {
                setElectricOpenerPower(value);
                setValue('electricOpenerPower', value);
              }}
            >
              <SelectTrigger className={(errors as any).electricOpenerPower ? 'border-red-500' : ''}>
                <SelectValue placeholder="전원을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="220V">220V</SelectItem>
                <SelectItem value="380V">380V</SelectItem>
              </SelectContent>
            </Select>
            {(errors as any).electricOpenerPower && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).electricOpenerPower.message}
              </p>
            )}
          </div>
          <div>
            <Label>
              용량 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={electricOpenerCapacity}
              onValueChange={(value) => {
                setElectricOpenerCapacity(value);
                setValue('electricOpenerCapacity', value);
              }}
            >
              <SelectTrigger className={(errors as any).electricOpenerCapacity ? 'border-red-500' : ''}>
                <SelectValue placeholder="용량을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="150">150 KG</SelectItem>
                <SelectItem value="300">300 KG</SelectItem>
                <SelectItem value="400">400 KG</SelectItem>
                <SelectItem value="500">500 KG</SelectItem>
                <SelectItem value="600">600 KG</SelectItem>
                <SelectItem value="800">800 KG</SelectItem>
                <SelectItem value="1000">1000 KG</SelectItem>
              </SelectContent>
            </Select>
            {(errors as any).electricOpenerCapacity && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).electricOpenerCapacity.message}
              </p>
            )}
          </div>
        </>
      )}

      {/* 모터 전용 필드 */}
      {selectedCategory1 === 'motor' && (
        <div className="md:col-span-2 grid grid-cols-2 gap-4 p-4 bg-green-50 rounded-lg border border-green-200">
          <div>
            <Label>모터 용량 (kg) *</Label>
            <NumberInput placeholder="예: 1.5" step={0.1} allowDecimal value={undefined} onChange={() => {}} />
          </div>
          <div>
            <Label>전압 (V) *</Label>
            <Select
              value={motorVoltage}
              onValueChange={(value) => {
                setMotorVoltage(value);
                setValue('motorVoltage', value);
              }}
            >
              <SelectTrigger className={(errors as any).motorVoltage ? 'border-red-500' : ''}>
                <SelectValue placeholder="전압을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="220">220V</SelectItem>
                <SelectItem value="380">380V</SelectItem>
              </SelectContent>
            </Select>
            {(errors as any).motorVoltage && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).motorVoltage.message}
              </p>
            )}
          </div>
        </div>
      )}

      {/* 체인 전용 필드 */}
      {selectedCategory1 === 'chain' && (
        <div className="md:col-span-2 grid grid-cols-2 gap-4 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
          <div>
            <Label>체인 규격 *</Label>
            <Select
              value={chainSpec}
              onValueChange={(value) => {
                setChainSpec(value);
                setValue('chainSpec', value);
              }}
            >
              <SelectTrigger className={(errors as any).chainSpec ? 'border-red-500' : ''}>
                <SelectValue placeholder="규격을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="40">40</SelectItem>
                <SelectItem value="50">50</SelectItem>
                <SelectItem value="60">60</SelectItem>
                <SelectItem value="80">80</SelectItem>
              </SelectContent>
            </Select>
            {(errors as any).chainSpec && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).chainSpec.message}
              </p>
            )}
          </div>
          <div>
            <Label>길이 (링크 수) *</Label>
            <QuantityInput placeholder="예: 100" value={undefined} onChange={() => {}} />
          </div>
        </div>
      )}

      {/* 품목명 선택 후에만 단위, 비고 표시 */}
      {selectedCategory1 && (
        <>
          <div>
            <Label>
              단위 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={partUnit}
              onValueChange={(value) => {
                setPartUnit(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="KG">KG (킬로그램)</SelectItem>
                <SelectItem value="L">L (리터)</SelectItem>
                <SelectItem value="SET">SET (세트)</SelectItem>
                <SelectItem value="BOX">BOX (박스)</SelectItem>
                <SelectItem value="ROLL">ROLL (롤)</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label>비고</Label>
            <Input
              placeholder="비고 사항을 입력하세요"
              {...register('note')}
            />
          </div>

          {/* 품목코드 자동생성 - 전동개폐기만 표시 */}
          {selectedCategory1 === 'electric_opener' && (
            <div className="md:col-span-2">
              <Label>품목코드 (자동생성)</Label>
              <Input
                value={generatedItemCode}
                disabled
                className="bg-muted text-muted-foreground"
                placeholder="용량과 전원을 선택하면 자동으로 생성됩니다"
              />
              <p className="text-xs text-muted-foreground mt-1">
                * 품목코드는 '품목명+용량+전원' 형식으로 자동 생성됩니다 (예: 전동개폐기150KG380V)
              </p>
            </div>
          )}

          {/* 품목 상태 */}
          <div className="md:col-span-2">
            <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) 필요 여부 */}
          <div className="md:col-span-2 pt-6 mt-6 border-t">
            <div className="flex items-center space-x-2">
              <Checkbox
                id="needsBOM-purchased"
                checked={needsBOM}
                onCheckedChange={(checked) => setNeedsBOM(checked as boolean)}
              />
              <Label htmlFor="needsBOM-purchased" className="cursor-pointer">
                부품구성 (BOM) 필요
              </Label>
            </div>
            <p className="text-xs text-muted-foreground mt-1 ml-6">
              * 이 부품이 하위 구성품을 포함하는 경우 체크하세요
            </p>
          </div>
        </>
      )}
    </>
  );
}