/**
 * ResponsiveFormTemplate 사용 예제
 * 
 * 기본 등록_데스크톱/태블릿/모바일 통합 템플릿의 실제 사용 예시
 */

import { useState } from "react";
import { Package, Upload, Link as LinkIcon } from "lucide-react";
import {
  ResponsiveFormTemplate,
  FormSection,
  FormField,
  FormFieldGrid,
  ValidationError,
} from "./ResponsiveFormTemplate";
import { Input } from "../ui/input";
import { Textarea } from "../ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select";
import { Switch } from "../ui/switch";
import { Button } from "../ui/button";
import { Label } from "../ui/label";
import { toast } from "sonner@2.0.3";

// 샘플 폼 데이터 타입
interface SampleFormData {
  itemCode: string;
  itemName: string;
  itemType: string;
  category: string;
  specification: string;
  unit: string;
  unitPrice: string;
  safetyStock: string;
  leadTime: string;
  supplier: string;
  description: string;
  isActive: boolean;
}

export function ResponsiveFormTemplateExample() {
  const [formData, setFormData] = useState<SampleFormData>({
    itemCode: "",
    itemName: "",
    itemType: "",
    category: "",
    specification: "",
    unit: "",
    unitPrice: "",
    safetyStock: "",
    leadTime: "",
    supplier: "",
    description: "",
    isActive: true,
  });

  const [validationErrors, setValidationErrors] = useState<ValidationError[]>([]);

  // 유효성 검사
  const validateForm = (): boolean => {
    const errors: ValidationError[] = [];

    if (!formData.itemName) {
      errors.push({
        field: "itemName",
        fieldLabel: "품목명",
        message: "품목명을 입력해주세요",
      });
    }

    if (!formData.itemType) {
      errors.push({
        field: "itemType",
        fieldLabel: "품목 유형",
        message: "품목 유형을 선택해주세요",
      });
    }

    if (!formData.unit) {
      errors.push({
        field: "unit",
        fieldLabel: "단위",
        message: "단위를 선택해주세요",
      });
    }

    if (formData.unitPrice && isNaN(Number(formData.unitPrice))) {
      errors.push({
        field: "unitPrice",
        fieldLabel: "단가",
        message: "올바른 숫자를 입력해주세요",
      });
    }

    setValidationErrors(errors);
    return errors.length === 0;
  };

  // 저장 핸들러
  const handleSave = () => {
    if (!validateForm()) {
      toast.error("입력 내용을 확인해주세요");
      return;
    }

    console.log("저장할 데이터:", formData);
    toast.success("품목이 저장되었습니다");
    
    // 폼 초기화
    setFormData({
      itemCode: "",
      itemName: "",
      itemType: "",
      category: "",
      specification: "",
      unit: "",
      unitPrice: "",
      safetyStock: "",
      leadTime: "",
      supplier: "",
      description: "",
      isActive: true,
    });
    setValidationErrors([]);
  };

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

  // 에러 필드로 스크롤
  const handleErrorClick = (field: string) => {
    const element = document.querySelector(`[name="${field}"]`) as HTMLElement;
    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "center" });
      element.focus();
    }
  };

  // 필드 값 변경
  const updateField = (field: keyof SampleFormData, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
    
    // 해당 필드의 에러 제거
    setValidationErrors((prev) =>
      prev.filter((error) => error.field !== field)
    );
  };

  // 필드에 에러가 있는지 확인
  const getFieldError = (field: string): string | undefined => {
    return validationErrors.find((error) => error.field === field)?.message;
  };

  return (
    <ResponsiveFormTemplate
      title="품목 등록"
      description="새로운 품목 정보를 입력하세요"
      icon={Package}
      onSave={handleSave}
      onCancel={handleCancel}
      saveDisabled={false}
      validationErrors={validationErrors}
      onErrorClick={handleErrorClick}
      maxWidth="2xl"
      helpText="품목 정보는 생산, 구매, 재고 관리에 사용됩니다. 정확하게 입력해주세요."
      headerActions={
        <>
          <Button variant="outline" size="sm">
            <Upload className="h-4 w-4 mr-2" />
            엑셀 업로드
          </Button>
        </>
      }
    >
      {/* 기본 정보 섹션 */}
      <FormSection
        title="기본 정보"
        description="품목의 기본 정보를 입력합니다"
        icon={Package}
        badge="필수"
      >
        <FormFieldGrid columns={2}>
          <FormField
            label="품목코드"
            htmlFor="itemCode"
            helpText="자동 생성됩니다"
          >
            <Input
              id="itemCode"
              name="itemCode"
              value={formData.itemCode}
              onChange={(e) => updateField("itemCode", e.target.value)}
              placeholder="PRD-0001"
              disabled
              className="bg-muted"
            />
          </FormField>

          <FormField
            label="품목명"
            htmlFor="itemName"
            required
            error={getFieldError("itemName")}
          >
            <Input
              id="itemName"
              name="itemName"
              value={formData.itemName}
              onChange={(e) => updateField("itemName", e.target.value)}
              placeholder="품목명을 입력하세요"
              className={getFieldError("itemName") ? "border-red-500" : ""}
            />
          </FormField>

          <FormField
            label="품목 유형"
            htmlFor="itemType"
            required
            error={getFieldError("itemType")}
          >
            <Select
              value={formData.itemType}
              onValueChange={(value) => updateField("itemType", value)}
            >
              <SelectTrigger
                id="itemType"
                name="itemType"
                className={getFieldError("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>
          </FormField>

          <FormField
            label="카테고리"
            htmlFor="category"
            helpText="품목 분류"
          >
            <Select
              value={formData.category}
              onValueChange={(value) => updateField("category", value)}
            >
              <SelectTrigger id="category" name="category">
                <SelectValue placeholder="선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="screen">스크린</SelectItem>
                <SelectItem value="steel">철재</SelectItem>
                <SelectItem value="other">기타</SelectItem>
              </SelectContent>
            </Select>
          </FormField>
        </FormFieldGrid>

        <FormField label="규격" htmlFor="specification">
          <Input
            id="specification"
            name="specification"
            value={formData.specification}
            onChange={(e) => updateField("specification", e.target.value)}
            placeholder="예: 3000 x 3000"
          />
        </FormField>
      </FormSection>

      {/* 단가 및 재고 정보 섹션 */}
      <FormSection
        title="단가 및 재고 정보"
        description="가격 및 재고 관리 정보"
      >
        <FormFieldGrid columns={3}>
          <FormField
            label="단위"
            htmlFor="unit"
            required
            error={getFieldError("unit")}
          >
            <Select
              value={formData.unit}
              onValueChange={(value) => updateField("unit", value)}
            >
              <SelectTrigger
                id="unit"
                name="unit"
                className={getFieldError("unit") ? "border-red-500" : ""}
              >
                <SelectValue placeholder="선택하세요" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="EA">EA (개)</SelectItem>
                <SelectItem value="SET">SET (세트)</SelectItem>
                <SelectItem value="M">M (미터)</SelectItem>
                <SelectItem value="KG">KG (킬로그램)</SelectItem>
                <SelectItem value="BOX">BOX (박스)</SelectItem>
              </SelectContent>
            </Select>
          </FormField>

          <FormField
            label="단가"
            htmlFor="unitPrice"
            error={getFieldError("unitPrice")}
            helpText="원 (₩)"
          >
            <Input
              id="unitPrice"
              name="unitPrice"
              type="number"
              value={formData.unitPrice}
              onChange={(e) => updateField("unitPrice", e.target.value)}
              placeholder="0"
              className={getFieldError("unitPrice") ? "border-red-500" : ""}
            />
          </FormField>

          <FormField label="안전재고" htmlFor="safetyStock" helpText="최소 수량">
            <Input
              id="safetyStock"
              name="safetyStock"
              type="number"
              value={formData.safetyStock}
              onChange={(e) => updateField("safetyStock", e.target.value)}
              placeholder="0"
            />
          </FormField>
        </FormFieldGrid>
      </FormSection>

      {/* 구매 정보 섹션 */}
      <FormSection title="구매 정보" description="구매 및 조달 관련 정보">
        <FormFieldGrid columns={2}>
          <FormField label="공급업체" htmlFor="supplier">
            <Input
              id="supplier"
              name="supplier"
              value={formData.supplier}
              onChange={(e) => updateField("supplier", e.target.value)}
              placeholder="공급업체명"
            />
          </FormField>

          <FormField label="리드타임" htmlFor="leadTime" helpText="일 단위">
            <Input
              id="leadTime"
              name="leadTime"
              type="number"
              value={formData.leadTime}
              onChange={(e) => updateField("leadTime", e.target.value)}
              placeholder="0"
            />
          </FormField>
        </FormFieldGrid>
      </FormSection>

      {/* 추가 정보 섹션 */}
      <FormSection title="추가 정보" description="기타 참고 정보">
        <FormField label="설명" htmlFor="description">
          <Textarea
            id="description"
            name="description"
            value={formData.description}
            onChange={(e) => updateField("description", e.target.value)}
            placeholder="품목에 대한 상세 설명을 입력하세요"
            rows={4}
          />
        </FormField>

        <div className="flex items-center justify-between p-4 border rounded-lg">
          <div className="space-y-0.5">
            <Label htmlFor="isActive">품목 활성화</Label>
            <p className="text-sm text-muted-foreground">
              활성화된 품목만 사용할 수 있습니다
            </p>
          </div>
          <Switch
            id="isActive"
            checked={formData.isActive}
            onCheckedChange={(checked) => updateField("isActive", checked)}
          />
        </div>
      </FormSection>
    </ResponsiveFormTemplate>
  );
}
