/**
 * 절곡 부품 (BENDING) 폼 컴포넌트
 * - 가이드레일(벽면/측면), 케이스, 하단마감재 등
 */

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

export interface BendingPartFormProps {
  selectedCategory1: string;
  setSelectedCategory1: (value: string) => void;
  selectedBendingItemType: string;
  setSelectedBendingItemType: (value: string) => void;
  material: string;
  setMaterial: (value: string) => void;
  widthSum: string;
  setWidthSum: (value: string) => void;
  bendingLength: string;
  setBendingLength: (value: string) => void;
  partUnit: string;
  setPartUnit: (value: string) => void;
  bendingDetailsLength: number;
  partStatus: string;
  setPartStatus: (value: string) => void;
  generateItemCode: () => string;
  register: UseFormRegister<CreateItemFormData>;
  setValue: UseFormSetValue<CreateItemFormData>;
  clearErrors: UseFormClearErrors<CreateItemFormData>;
  errors: FieldErrors<CreateItemFormData>;
}

export default function BendingPartForm({
  selectedCategory1,
  setSelectedCategory1,
  selectedBendingItemType,
  setSelectedBendingItemType,
  material,
  setMaterial,
  widthSum,
  setWidthSum,
  bendingLength,
  setBendingLength,
  partUnit,
  setPartUnit,
  bendingDetailsLength,
  partStatus,
  setPartStatus,
  generateItemCode,
  register,
  setValue,
  clearErrors,
  errors,
}: BendingPartFormProps) {
  return (
    <>
      {/* 품목명 선택 */}
      <div>
        <Label>
          품목명 <span className="text-red-500">*</span>
        </Label>
        <Select
          value={selectedCategory1}
          onValueChange={(val) => {
            setSelectedCategory1(val);
            setValue('category1', val);
          }}
        >
          <SelectTrigger>
            <SelectValue placeholder="품목명을 선택하세요" />
          </SelectTrigger>
          <SelectContent>
            {PART_TYPE_CATEGORIES.BENDING?.categories.map((cat) => (
              <SelectItem key={cat.value} value={cat.value}>
                {cat.label} ({cat.code})
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      {/* 종류 선택 */}
      {selectedCategory1 && PART_ITEM_NAMES[selectedCategory1] && (
        <div>
          <Label>
            종류 <span className="text-red-500">*</span>
          </Label>
          <Select
            value={selectedBendingItemType}
            onValueChange={(value) => {
              setSelectedBendingItemType(value);
              const selected = PART_ITEM_NAMES[selectedCategory1].find(item => item.label === value);
              if (selected) {
                setValue('itemName', selected.label);
                setValue('category2', selected.code);
                clearErrors('category2');
              }
            }}
          >
            <SelectTrigger>
              <SelectValue placeholder="종류를 선택하세요" />
            </SelectTrigger>
            <SelectContent>
              {PART_ITEM_NAMES[selectedCategory1].map((item) => (
                <SelectItem key={item.value} value={item.label}>
                  {item.label} ({item.code})
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      )}

      {/* 재질, 폭 합계, 모양&길이 (Purple Section) */}
      {selectedBendingItemType && (
        <div className="md:col-span-2 grid grid-cols-1 md:grid-cols-3 gap-4 p-4 bg-purple-50 rounded-lg border border-purple-200">
          <div>
            <Label>
              재질 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={material}
              onValueChange={(value) => {
                setMaterial(value);
                setValue('material', value);
              }}
            >
              <SelectTrigger className={(errors as any).material ? 'border-red-500' : ''}>
                <SelectValue placeholder="재질을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="EGI 1.15T">EGI 1.15T</SelectItem>
                <SelectItem value="EGI 1.55T">EGI 1.55T</SelectItem>
                <SelectItem value="SUS 1.2T">SUS 1.2T</SelectItem>
                <SelectItem value="SUS 1.5T">SUS 1.5T</SelectItem>
              </SelectContent>
            </Select>
            {(errors as any).material && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).material.message}
              </p>
            )}
          </div>

          <div>
            <Label>
              폭 합계 <span className="text-red-500">*</span>
            </Label>
            <div className="flex items-center gap-2">
              <NumberInput
                value={parseFloat(widthSum) || 0}
                onChange={(value) => {
                  const strValue = String(value ?? 0);
                  setWidthSum(strValue);
                  setValue('length', strValue);
                }}
                placeholder="전개도 상세를 입력해주세요"
                disabled={bendingDetailsLength > 0}
                allowDecimal
                className={`${bendingDetailsLength > 0 ? "bg-blue-50 font-medium" : ""} ${(errors as any).length ? 'border-red-500' : ''}`}
              />
              <span className="text-sm text-muted-foreground">mm</span>
            </div>
            {(errors as any).length && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).length.message}
              </p>
            )}
            {!(errors as any).length && bendingDetailsLength > 0 && (
              <p className="text-xs text-blue-600 mt-1">
                * 전개도 상세 입력의 합계가 자동 반영됩니다
              </p>
            )}
          </div>

          <div>
            <Label>
              모양&길이 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={bendingLength}
              onValueChange={(value) => {
                setBendingLength(value);
                setValue('bendingLength', value);
              }}
            >
              <SelectTrigger className={(errors as any).bendingLength ? 'border-red-500' : ''}>
                <SelectValue placeholder="모양&길이를 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="W50x3000">W50×3000mm</SelectItem>
                <SelectItem value="W50x4000">W50×4000mm</SelectItem>
                <SelectItem value="W80x3000">W80×3000mm</SelectItem>
                <SelectItem value="W80x4000">W80×4000mm</SelectItem>
                <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>
            {(errors as any).bendingLength && (
              <p className="text-xs text-red-500 mt-1">
                {(errors as any).bendingLength.message}
              </p>
            )}
          </div>
        </div>
      )}

      {/* 단위, 비고 (종류 선택 후 표시) */}
      {selectedBendingItemType && (
        <>
          <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>

          {/* 품목코드 자동생성 */}
          <div className="md:col-span-2">
            <Label>품목코드 (자동생성)</Label>
            <Input
              value={generateItemCode()}
              disabled
              className="bg-muted text-muted-foreground"
              placeholder="품목명과 규격이 입력되면 자동으로 생성됩니다"
            />
            <p className="text-xs text-muted-foreground mt-1">
              {(selectedCategory1 === "guide_rail_wall" || selectedCategory1 === "guide_rail_side")
                ? "* 가이드레일 품목코드는 '제품구분(R/S)+종류(M/T/C/D/S/U)+모양&길이' 형식으로 자동 생성됩니다 (예: RD30, SM53)"
                : "* 절곡 부품 품목코드는 '품목명+종류+길이축약' 형식으로 자동 생성됩니다 (예: 케이스후면부30)"}
            </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>
    </>
  );
}