/**
 * 제품 (FG) 폼 컴포넌트
 */

import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { FileInput } from '@/components/ui/file-input';
import type { UseFormRegister, UseFormSetValue, UseFormGetValues, FieldErrors } from 'react-hook-form';
import type { CreateItemFormData } from '@/lib/utils/validation';

// ProductForm에서 사용하는 확장 타입 (productName 포함)
type ProductFormErrors = FieldErrors<CreateItemFormData> & {
  productName?: { message?: string };
};

interface ProductFormProps {
  productName: string;
  setProductName: (value: string) => void;
  productStatus: string;
  setProductStatus: (value: string) => void;
  remarks: string;
  setRemarks: (value: string) => void;
  needsBOM: boolean;
  setNeedsBOM: (value: boolean) => void;
  specificationFile: File | null;
  setSpecificationFile: (file: File | null) => void;
  certificationFile: File | null;
  setCertificationFile: (file: File | null) => void;
  isSubmitting: boolean;
  register: UseFormRegister<CreateItemFormData>;
  setValue: UseFormSetValue<CreateItemFormData>;
  getValues: UseFormGetValues<CreateItemFormData>;
  errors: ProductFormErrors;
}

export default function ProductForm({
  productName,
  setProductName,
  productStatus,
  setProductStatus,
  remarks,
  setRemarks,
  needsBOM: _needsBOM,
  setNeedsBOM: _setNeedsBOM,
  specificationFile: _specificationFile,
  setSpecificationFile: _setSpecificationFile,
  certificationFile: _certificationFile,
  setCertificationFile: _setCertificationFile,
  isSubmitting: _isSubmitting,
  register,
  setValue,
  getValues,
  errors,
}: ProductFormProps) {
  return (
    <>
      {/* 기본 정보 */}
      <div>
        <Label htmlFor="productName">
          상품명 <span className="text-red-500">*</span>
        </Label>
        <Input
          id="productName"
          placeholder="상품명을 입력하세요 (예: 프리미엄 스크린)"
          value={productName}
          onChange={(e) => {
            const newName = e.target.value;
            setProductName(newName);
            setValue('productName', newName);
          }}
          className={errors.productName ? 'border-red-500' : ''}
        />
        {errors.productName && (
          <p className="text-xs text-red-500 mt-1">
            {errors.productName.message}
          </p>
        )}
        {!errors.productName && (
          <p className="text-xs text-muted-foreground mt-1">
            상품명을 입력해주세요
          </p>
        )}
      </div>

      <div>
        <Label htmlFor="itemName">
          품목명 <span className="text-red-500">*</span>
        </Label>
        <Input
          id="itemName"
          placeholder="품목명을 입력하세요"
          {...register('itemName')}
          className={errors.itemName ? 'border-red-500' : ''}
        />
        {errors.itemName && (
          <p className="text-xs text-red-500 mt-1">
            {errors.itemName.message}
          </p>
        )}
        {!errors.itemName && (
          <p className="text-xs text-muted-foreground mt-1">
            품목명을 입력해주세요
          </p>
        )}
      </div>

      <div>
        <Label>품목코드 (자동생성)</Label>
        <Input
          value={getValues('itemName') || ''}
          disabled
          className="bg-muted text-muted-foreground"
          placeholder="품목명이 입력되면 자동으로 동일하게 생성됩니다"
        />
        <p className="text-xs text-muted-foreground mt-1">
          * 품목명과 품목코드가 동일하게 설정됩니다
        </p>
      </div>

      <div>
        <Label>로트 약자</Label>
        <Input
          placeholder="로트 약자를 입력하세요"
          {...register('lotAbbreviation')}
          maxLength={10}
        />
        <p className="text-xs text-muted-foreground mt-1">
          * 로트 번호 생성 시 사용되는 약자 (선택사항)
        </p>
      </div>

      <div>
        <Label>품목 상태</Label>
        <Select
          value={productStatus}
          onValueChange={(value) => {
            setProductStatus(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>

      <div>
        <Label>비고</Label>
        <Input
          placeholder="비고 사항을 입력하세요"
          value={remarks}
          onChange={(e) => setRemarks(e.target.value)}
        />
      </div>
    </>
  );
}

/**
 * FG 인정 정보 섹션 컴포넌트
 */
export function ProductCertificationSection({
  remarks,
  setRemarks,
  needsBOM,
  setNeedsBOM,
  specificationFile,
  setSpecificationFile,
  certificationFile,
  setCertificationFile,
  isSubmitting,
  register,
  setValue,
  getValues,
}: Pick<ProductFormProps,
  | 'remarks'
  | 'setRemarks'
  | 'needsBOM'
  | 'setNeedsBOM'
  | 'specificationFile'
  | 'setSpecificationFile'
  | 'certificationFile'
  | 'setCertificationFile'
  | 'isSubmitting'
  | 'register'
  | 'setValue'
  | 'getValues'
>) {
  return (
    <div className="pt-6 mt-6 border-t space-y-4">
      <div>
        <h3 className="text-base font-semibold mb-4">인정 정보</h3>
        <p className="text-sm text-muted-foreground mb-4">
          제품 인정서 및 시방서를 관리합니다
        </p>
      </div>

      {/* 인정번호, 유효기간, 파일 업로드, 비고 */}
      <div className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="certificationNumber">인정번호</Label>
          <Input
            id="certificationNumber"
            placeholder="인정번호를 입력하세요"
            {...register('certificationNumber')}
            disabled={isSubmitting}
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="certificationStartDate">인정 유효기간 시작일</Label>
          <DatePicker
            value={getValues('certificationStartDate') || ''}
            onChange={(date) => setValue('certificationStartDate', date)}
            disabled={isSubmitting}
          />
        </div>

        <div className="space-y-2">
          <Label htmlFor="certificationEndDate">인정 유효기간 종료일</Label>
          <DatePicker
            value={getValues('certificationEndDate') || ''}
            onChange={(date) => setValue('certificationEndDate', date)}
            disabled={isSubmitting}
          />
        </div>

        {/* 시방서 파일 */}
        <div className="space-y-2">
          <Label>시방서 (PDF)</Label>
          <FileInput
            value={specificationFile}
            onFileSelect={setSpecificationFile}
            onFileRemove={() => setSpecificationFile(null)}
            accept=".pdf"
            disabled={isSubmitting}
            buttonText="파일 선택"
            placeholder="선택된 파일 없음"
          />
        </div>

        {/* 인정서 파일 */}
        <div className="space-y-2">
          <Label>인정서 (PDF)</Label>
          <FileInput
            value={certificationFile}
            onFileSelect={setCertificationFile}
            onFileRemove={() => setCertificationFile(null)}
            accept=".pdf"
            disabled={isSubmitting}
            buttonText="파일 선택"
            placeholder="선택된 파일 없음"
          />
        </div>

        {/* 비고 */}
        <div>
          <Label>비고</Label>
          <Textarea
            value={remarks}
            onChange={(e) => setRemarks(e.target.value)}
            placeholder="비고 사항을 입력하세요"
            rows={3}
            disabled={isSubmitting}
          />
          <p className="text-xs text-muted-foreground mt-1">
            * 추가 설명이나 특이사항을 기록할 수 있습니다
          </p>
        </div>
      </div>

      {/* 부품구성 (BOM) 필요 여부 - FG 전용, 인정 정보 카드 내부 */}
      <div className="md:col-span-2 pt-6 mt-6 border-t">
        <div className="flex items-center space-x-2">
          <Checkbox
            id="needsBOM-fg"
            checked={needsBOM}
            onCheckedChange={(checked) => setNeedsBOM(checked as boolean)}
          />
          <Label htmlFor="needsBOM-fg" className="cursor-pointer">
            부품구성 (BOM) 필요
          </Label>
        </div>
        <p className="text-xs text-muted-foreground mt-1 ml-6">
          * 이 제품이 하위 구성품을 포함하는 경우 체크하세요
        </p>
      </div>
    </div>
  );
}