/**
 * 원자재/부자재/소모품 (RM/SM/CS) 폼 컴포넌트
 */

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

interface MaterialFormProps {
  selectedItemType: ItemType;
  itemName: string;
  setItemName: (value: string) => void;
  selectedSpecification: string;
  setSelectedSpecification: (value: string) => void;
  materialStatus: string;
  setMaterialStatus: (value: string) => void;
  selectedUnit: string;
  setSelectedUnit: (value: string) => void;
  register: UseFormRegister<CreateItemFormData>;
  setValue: UseFormSetValue<CreateItemFormData>;
  getValues: UseFormGetValues<CreateItemFormData>;
  errors: FieldErrors<CreateItemFormData>;
}

export default function MaterialForm({
  selectedItemType,
  itemName,
  setItemName,
  selectedSpecification,
  setSelectedSpecification,
  materialStatus,
  setMaterialStatus,
  selectedUnit,
  setSelectedUnit,
  register,
  setValue,
  getValues,
  errors,
}: MaterialFormProps) {
  return (
    <>
      <div>
        <Label htmlFor="itemName">
          품목명 <span className="text-red-500">*</span>
        </Label>
        {/* 원자재/부자재는 목록에서 선택, 소모품은 직접 입력 */}
        {selectedItemType === 'RM' ? (
          <>
            <Select
              value={itemName}
              onValueChange={(value) => {
                setItemName(value);
                setValue('itemName', value);
                // 품목명 변경 시 규격 초기화
                setSelectedSpecification('');
                setValue('specification', '');
                // 품목코드 자동생성
                const spec = getValues('specification') || '';
                setValue('itemCode', spec ? `${value}-${spec}` : value);
              }}
            >
              <SelectTrigger className={errors.itemName ? 'border-red-500' : ''}>
                <SelectValue placeholder="품목명을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="철판">철판</SelectItem>
                <SelectItem value="알루미늄">알루미늄</SelectItem>
                <SelectItem value="스테인리스">스테인리스</SelectItem>
                <SelectItem value="아연도금강판">아연도금강판</SelectItem>
              </SelectContent>
            </Select>
            {errors.itemName && (
              <p className="text-xs text-red-500 mt-1">
                {errors.itemName.message}
              </p>
            )}
          </>
        ) : selectedItemType === 'SM' ? (
          <>
            <Select
              value={itemName}
              onValueChange={(value) => {
                setItemName(value);
                setValue('itemName', value);
                // 품목명 변경 시 규격 초기화
                setSelectedSpecification('');
                setValue('specification', '');
                // 품목코드 자동생성
                const spec = getValues('specification') || '';
                setValue('itemCode', spec ? `${value}-${spec}` : value);
              }}
            >
              <SelectTrigger className={errors.itemName ? 'border-red-500' : ''}>
                <SelectValue placeholder="품목명을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="볼트">볼트</SelectItem>
                <SelectItem value="너트">너트</SelectItem>
                <SelectItem value="와셔">와셔</SelectItem>
                <SelectItem value="나사">나사</SelectItem>
                <SelectItem value="앵커">앵커</SelectItem>
              </SelectContent>
            </Select>
            {errors.itemName && (
              <p className="text-xs text-red-500 mt-1">
                {errors.itemName.message}
              </p>
            )}
          </>
        ) : (
          <>
            <Input
              id="itemName"
              placeholder="품목명을 입력하세요"
              value={itemName}
              onChange={(e) => {
                const newName = e.target.value;
                setItemName(newName);
                setValue('itemName', newName);
                // 품목코드 자동생성
                const spec = getValues('specification') || '';
                setValue('itemCode', spec ? `${newName}-${spec}` : newName);
              }}
              className={errors.itemName ? 'border-red-500' : ''}
            />
            {errors.itemName && (
              <p className="text-xs text-red-500 mt-1">
                {errors.itemName.message}
              </p>
            )}
          </>
        )}
      </div>

      {/* 규격(사양) */}
      {selectedItemType === 'CS' ? (
        <div>
          <Label htmlFor="specification">
            규격(사양) <span className="text-red-500">*</span>
          </Label>
          <Input
            id="specification"
            placeholder="예: 면-L, 고급형, A4"
            {...register('specification', {
              onChange: (e) => {
                // 품목코드 자동생성
                const spec = e.target.value;
                const name = itemName || '';
                setValue('itemCode', name && spec ? `${name}-${spec}` : name);
              }
            })}
            className={errors.specification ? 'border-red-500' : ''}
          />
          {errors.specification && (
            <p className="text-xs text-red-500 mt-1">
              {errors.specification.message}
            </p>
          )}
        </div>
      ) : (
        <div className="md:col-span-2">
          <Label htmlFor="specification">
            규격 <span className="text-red-500">*</span>
          </Label>
          <Select
            value={selectedSpecification}
            onValueChange={(value) => {
              setSelectedSpecification(value);
              setValue('specification', value);
              // 품목코드 자동생성
              const name = itemName || '';
              setValue('itemCode', name && value ? `${name}-${value}` : name);
            }}
            disabled={!itemName}
          >
            <SelectTrigger id="specification" className={errors.specification ? 'border-red-500' : ''}>
              <SelectValue placeholder={itemName ? "규격을 선택하세요" : "품목명을 먼저 선택하세요"} />
            </SelectTrigger>
            <SelectContent>
              {selectedItemType === 'RM' && itemName === '철판' && (
                <>
                  <SelectItem value="1.0T">1.0T</SelectItem>
                  <SelectItem value="1.2T">1.2T</SelectItem>
                  <SelectItem value="1.5T">1.5T</SelectItem>
                  <SelectItem value="2.0T">2.0T</SelectItem>
                </>
              )}
              {selectedItemType === 'RM' && itemName === '알루미늄' && (
                <>
                  <SelectItem value="0.8T">0.8T</SelectItem>
                  <SelectItem value="1.0T">1.0T</SelectItem>
                  <SelectItem value="1.5T">1.5T</SelectItem>
                </>
              )}
              {selectedItemType === 'RM' && itemName === '스테인리스' && (
                <>
                  <SelectItem value="0.5T">0.5T</SelectItem>
                  <SelectItem value="1.0T">1.0T</SelectItem>
                  <SelectItem value="1.2T">1.2T</SelectItem>
                </>
              )}
              {selectedItemType === 'SM' && itemName === '볼트' && (
                <>
                  <SelectItem value="M6x20">M6×20mm</SelectItem>
                  <SelectItem value="M8x25">M8×25mm</SelectItem>
                  <SelectItem value="M10x30">M10×30mm</SelectItem>
                  <SelectItem value="M12x40">M12×40mm</SelectItem>
                  <SelectItem value="M16x50">M16×50mm</SelectItem>
                </>
              )}
              {selectedItemType === 'SM' && itemName === '너트' && (
                <>
                  <SelectItem value="M6">M6</SelectItem>
                  <SelectItem value="M8">M8</SelectItem>
                  <SelectItem value="M10">M10</SelectItem>
                  <SelectItem value="M12">M12</SelectItem>
                  <SelectItem value="M16">M16</SelectItem>
                </>
              )}
              {selectedItemType === 'SM' && itemName === '와셔' && (
                <>
                  <SelectItem value="M6">M6</SelectItem>
                  <SelectItem value="M8">M8</SelectItem>
                  <SelectItem value="M10">M10</SelectItem>
                  <SelectItem value="M12">M12</SelectItem>
                  <SelectItem value="M16">M16</SelectItem>
                </>
              )}
              {selectedItemType === 'SM' && itemName === '나사' && (
                <>
                  <SelectItem value="4x20">4×20mm</SelectItem>
                  <SelectItem value="5x25">5×25mm</SelectItem>
                  <SelectItem value="6x30">6×30mm</SelectItem>
                  <SelectItem value="8x40">8×40mm</SelectItem>
                  <SelectItem value="10x50">10×50mm</SelectItem>
                </>
              )}
              {selectedItemType === 'SM' && itemName === '앵커' && (
                <>
                  <SelectItem value="6x30">6×30mm</SelectItem>
                  <SelectItem value="8x40">8×40mm</SelectItem>
                  <SelectItem value="10x50">10×50mm</SelectItem>
                  <SelectItem value="12x60">12×60mm</SelectItem>
                  <SelectItem value="16x80">16×80mm</SelectItem>
                </>
              )}
            </SelectContent>
          </Select>
          {errors.specification && (
            <p className="text-xs text-red-500 mt-1">
              {errors.specification.message}
            </p>
          )}
          {!errors.specification && (
            <p className="text-xs text-muted-foreground mt-1">
              * 규격은 품목명 선택 시 자동으로 필터링됩니다
            </p>
          )}
        </div>
      )}

      {/* 품목코드 (자동생성) */}
      <div className="md:col-span-2">
        <Label htmlFor="itemCode-auto">품목코드 (자동생성)</Label>
        <Input
          id="itemCode-auto"
          placeholder="품목명과 규격이 입력되면 자동으로 생성됩니다"
          value={(() => {
            const name = itemName || '';
            const spec = getValues('specification') || '';
            return spec ? `${name}-${spec}` : name;
          })()}
          disabled
          className="bg-muted text-muted-foreground"
        />
        <p className="text-xs text-muted-foreground mt-1">
          * 품목코드는 '품목명-규격' 형식으로 자동 생성됩니다
        </p>
      </div>

      {/* 품목 상태 (RM/SM만) */}
      {(selectedItemType === 'RM' || selectedItemType === 'SM') && (
        <div className="md:col-span-2">
          <Label htmlFor="isActive">품목 상태</Label>
          <Select
            value={materialStatus}
            onValueChange={(value) => {
              setMaterialStatus(value);
              setValue('isActive', value === 'true');
            }}
          >
            <SelectTrigger id="isActive">
              <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>
      )}

      {/* 단위 (RM/SM/CS 공통) */}
      <div>
        <Label htmlFor="unit">
          단위 <span className="text-red-500">*</span>
        </Label>
        <Select
          value={selectedUnit}
          onValueChange={(value) => {
            setSelectedUnit(value);
            setValue('unit', value);
          }}
        >
          <SelectTrigger id="unit" className={errors.unit ? 'border-red-500' : ''}>
            <SelectValue placeholder="단위를 선택하세요" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="M">M (미터)</SelectItem>
            <SelectItem value="mm">mm (밀리미터)</SelectItem>
            <SelectItem value="EA">EA (개)</SelectItem>
            <SelectItem value="SET">SET (세트)</SelectItem>
            <SelectItem value="KG">KG (킬로그램)</SelectItem>
            <SelectItem value="T">T (톤)</SelectItem>
            <SelectItem value="BOX">BOX (박스)</SelectItem>
            <SelectItem value="L">L (리터)</SelectItem>
            <SelectItem value="M2">M² (제곱미터)</SelectItem>
            <SelectItem value="M3">M³ (세제곱미터)</SelectItem>
            <SelectItem value="ROLL">ROLL (롤)</SelectItem>
            <SelectItem value="SHEET">SHEET (장)</SelectItem>
            <SelectItem value="PACK">PACK (팩)</SelectItem>
          </SelectContent>
        </Select>
        {errors.unit && (
          <p className="text-xs text-red-500 mt-1">
            {errors.unit.message}
          </p>
        )}
      </div>
    </>
  );
}