/**
 * BasicRegistrationTemplate 사용 예시
 * 
 * 품목 등록 페이지 스타일을 재사용하는 예제입니다.
 */

import { useState } from "react";
import { Package, FileImage } from "lucide-react";
import { BasicRegistrationTemplate, FormSection, ValidationErrors, VersionHistoryItem, FieldNameMap } from "../templates/BasicRegistrationTemplate";
import { Input } from "../ui/input";
import { Label } from "../ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Textarea } from "../ui/textarea";
import { Checkbox } from "../ui/checkbox";
import { Button } from "../ui/button";
import { toast } from "sonner@2.0.3";

/**
 * 예시: 품목 등록 페이지
 */
export function BasicRegistrationTemplateExample() {
  const [formData, setFormData] = useState({
    itemType: "",
    itemName: "",
    itemCode: "",
    unit: "",
    description: "",
    needsBOM: false,
  });

  const [validationErrors, setValidationErrors] = useState<ValidationErrors>({});

  // 수정 모드 예시 (실제로는 편집 중인 항목의 이력)
  const versionHistory: VersionHistoryItem[] = [
    {
      id: "1",
      version: 1,
      changeDescription: "품목명 변경",
      changedBy: "홍길동",
      changedAt: "2024-01-15T10:30:00",
    },
    {
      id: "2",
      version: 2,
      changeDescription: "단가 수정",
      changedBy: "김철수",
      changedAt: "2024-01-16T14:20:00",
    },
  ];

  // 필드명 맵핑
  const fieldNameMap: FieldNameMap = {
    itemType: "품목유형",
    itemName: "품목명",
    itemCode: "품목코드",
    unit: "단위",
    description: "설명",
  };

  // 저장 핸들러
  const handleSave = () => {
    // 유효성 검증
    const errors: ValidationErrors = {};
    
    if (!formData.itemType) {
      errors.itemType = "품목유형을 선택해주세요";
    }
    if (!formData.itemName) {
      errors.itemName = "품목명을 입력해주세요";
    }
    if (!formData.unit) {
      errors.unit = "단위를 선택해주세요";
    }

    if (Object.keys(errors).length > 0) {
      setValidationErrors(errors);
      toast.error("입력 내용을 확인해주세요");
      return;
    }

    // 저장 로직
    toast.success("저장되었습니다");
    setValidationErrors({});
  };

  // 취소 핸들러
  const handleCancel = () => {
    toast.info("취소되었습니다");
  };

  // 필드 에러 제거
  const clearFieldError = (field: string) => {
    setValidationErrors((prev) => {
      const newErrors = { ...prev };
      delete newErrors[field];
      return newErrors;
    });
  };

  // 폼 섹션 정의
  const sections: FormSection[] = [
    {
      id: "basic-info",
      title: "기본 정보",
      icon: Package,
      error: !!(validationErrors.itemType || validationErrors.itemName || validationErrors.itemCode),
      content: (
        <div className="space-y-4">
          <div>
            <Label className="flex items-center gap-1">
              품목유형 <span className="text-red-500">*</span>
            </Label>
            <Select
              value={formData.itemType}
              onValueChange={(value) => {
                setFormData({ ...formData, itemType: value });
                clearFieldError("itemType");
              }}
            >
              <SelectTrigger
                name="itemType"
                className={validationErrors.itemType ? "border-red-500" : ""}
              >
                <SelectValue placeholder="품목 유형을 선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="FG">제품 (Finished Goods)</SelectItem>
                <SelectItem value="PT">부품 (Part)</SelectItem>
                <SelectItem value="SM">부자재 (Sub Material)</SelectItem>
                <SelectItem value="RM">원자재 (Raw Material)</SelectItem>
                <SelectItem value="CS">소모품 (Consumables)</SelectItem>
              </SelectContent>
            </Select>
            {validationErrors.itemType && (
              <p className="text-sm text-red-500 mt-1">{validationErrors.itemType}</p>
            )}
          </div>

          {formData.itemType && (
            <>
              <div>
                <Label className="flex items-center gap-1">
                  품목명 <span className="text-red-500">*</span>
                </Label>
                <Input
                  name="itemName"
                  value={formData.itemName}
                  onChange={(e) => {
                    setFormData({ ...formData, itemName: e.target.value });
                    clearFieldError("itemName");
                  }}
                  placeholder="품목명을 입력하세요"
                  className={validationErrors.itemName ? "border-red-500" : ""}
                />
                {validationErrors.itemName && (
                  <p className="text-sm text-red-500 mt-1">{validationErrors.itemName}</p>
                )}
              </div>

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

              <div>
                <Label className="flex items-center gap-1">
                  단위 <span className="text-red-500">*</span>
                </Label>
                <Select
                  value={formData.unit}
                  onValueChange={(value) => {
                    setFormData({ ...formData, unit: value });
                    clearFieldError("unit");
                  }}
                >
                  <SelectTrigger
                    name="unit"
                    className={validationErrors.unit ? "border-red-500" : ""}
                  >
                    <SelectValue placeholder="단위를 선택하세요" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="EA">EA</SelectItem>
                    <SelectItem value="SET">SET</SelectItem>
                    <SelectItem value="KG">KG</SelectItem>
                    <SelectItem value="M">M</SelectItem>
                    <SelectItem value="M2">M2</SelectItem>
                  </SelectContent>
                </Select>
                {validationErrors.unit && (
                  <p className="text-sm text-red-500 mt-1">{validationErrors.unit}</p>
                )}
              </div>

              <div>
                <Label>설명</Label>
                <Textarea
                  name="description"
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  placeholder="설명을 입력하세요"
                  rows={3}
                />
              </div>

              <div className="pt-4 border-t">
                <div className="flex items-center space-x-2">
                  <Checkbox
                    id="needsBOM"
                    checked={formData.needsBOM}
                    onCheckedChange={(checked) =>
                      setFormData({ ...formData, needsBOM: checked as boolean })
                    }
                  />
                  <Label htmlFor="needsBOM" className="cursor-pointer">
                    부품구성 (BOM) 필요
                  </Label>
                </div>
                <p className="text-xs text-muted-foreground mt-1 ml-6">
                  * 이 품목이 하위 구성품을 포함하는 경우 체크하세요
                </p>
              </div>
            </>
          )}
        </div>
      ),
    },
    {
      id: "additional-info",
      title: "추가 정보 (선택사항)",
      icon: FileImage,
      content: (
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            필요한 경우 추가 정보를 입력할 수 있습니다.
          </p>
          {/* 추가 필드들을 여기에 배치 */}
        </div>
      ),
    },
  ];

  return (
    <BasicRegistrationTemplate
      title="품목 등록"
      description="새로운 품목을 등록합니다"
      icon={Package}
      onSave={handleSave}
      onCancel={handleCancel}
      saveDisabled={!formData.itemType}
      versionHistory={versionHistory}
      showVersionHistory={false} // 신규 등록이므로 false
      validationErrors={validationErrors}
      fieldNameMap={fieldNameMap}
      sections={sections}
      bottomActions={
        <div className="flex justify-end gap-2 mt-6">
          <Button variant="outline" onClick={handleCancel}>
            목록으로
          </Button>
          <Button onClick={handleSave} disabled={!formData.itemType}>
            저장
          </Button>
        </div>
      }
    />
  );
}
