/**
 * 컴포넌트 추가/수정 다이얼로그
 * 
 * atoms, molecules, organisms, templates, widgets 추가/수정 UI
 */

import { useState, useEffect } from "react";
import { StandardDialog } from "./molecules/StandardDialog";
import { FormField } from "./molecules/FormField";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
import { Label } from "./ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { ComponentItem } from "./contexts/DesignSystemContext";

interface ComponentManageDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  type: "atoms" | "molecules" | "organisms" | "templates" | "widgets";
  mode: "add" | "edit";
  component?: ComponentItem;
  onSave: (data: Omit<ComponentItem, "id" | "createdAt" | "updatedAt">) => void;
}

const categoryOptions = {
  atoms: ["Interactive", "Form", "Display", "Feedback", "Layout", "Navigation", "Data"],
  molecules: ["Form", "Display", "Navigation", "Data", "Feedback"],
  organisms: ["Form", "Display", "Navigation", "Data", "Dashboard"],
  templates: ["List", "Page", "Form", "Dashboard"],
  widgets: ["Sales", "Production", "Inventory", "Quality", "Performance", "Dashboard"],
};

export function ComponentManageDialog({
  open,
  onOpenChange,
  type,
  mode,
  component,
  onSave,
}: ComponentManageDialogProps) {
  const [formData, setFormData] = useState({
    name: "",
    path: "",
    category: "",
    description: "",
    variants: "",
    structure: "",
    preview: "",
    code: "",
  });

  useEffect(() => {
    if (mode === "edit" && component) {
      setFormData({
        name: component.name,
        path: component.path,
        category: component.category,
        description: component.description,
        variants: component.variants?.join(", ") || "",
        structure: component.structure || "",
        preview: component.preview,
        code: component.code,
      });
    } else if (mode === "add") {
      setFormData({
        name: "",
        path: `/components/${type}/`,
        category: categoryOptions[type][0] || "",
        description: "",
        variants: "",
        structure: "",
        preview: "",
        code: "",
      });
    }
  }, [mode, component, open, type]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    const data: Omit<ComponentItem, "id" | "createdAt" | "updatedAt"> = {
      name: formData.name,
      path: formData.path,
      category: formData.category,
      description: formData.description,
      preview: formData.preview,
      code: formData.code,
    };

    if (formData.variants) {
      data.variants = formData.variants.split(",").map(v => v.trim());
    }

    if (formData.structure) {
      data.structure = formData.structure;
    }

    onSave(data);
    onOpenChange(false);
  };

  const title = mode === "add" ? `${type} 추가` : `${type} 수정`;

  return (
    <StandardDialog
      open={open}
      onOpenChange={onOpenChange}
      title={title}
      description={mode === "add" ? "새 컴포넌트를 추가합니다" : "컴포넌트 정보를 수정합니다"}
      size="large"
    >
      <form onSubmit={handleSubmit} className="space-y-4">
        <FormField label="컴포넌트 이름" required>
          <Input
            value={formData.name}
            onChange={(e) => setFormData({ ...formData, name: e.target.value })}
            placeholder="예: Button, FormField, ResponsiveListTemplate"
            required
          />
        </FormField>

        <FormField label="파일 경로" required>
          <Input
            value={formData.path}
            onChange={(e) => setFormData({ ...formData, path: e.target.value })}
            placeholder="예: /components/ui/button.tsx"
            required
          />
        </FormField>

        <FormField label="카테고리" required>
          <Select
            value={formData.category}
            onValueChange={(value) => setFormData({ ...formData, category: value })}
          >
            <SelectTrigger>
              <SelectValue placeholder="카테고리 선택" />
            </SelectTrigger>
            <SelectContent>
              {categoryOptions[type].map((cat) => (
                <SelectItem key={cat} value={cat}>
                  {cat}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </FormField>

        <FormField label="설명" required>
          <Textarea
            value={formData.description}
            onChange={(e) => setFormData({ ...formData, description: e.target.value })}
            placeholder="컴포넌트에 대한 간단한 설명"
            rows={2}
            required
          />
        </FormField>

        {(type === "atoms" || type === "molecules") && (
          <FormField label="Variants (쉼표로 구분)">
            <Input
              value={formData.variants}
              onChange={(e) => setFormData({ ...formData, variants: e.target.value })}
              placeholder="예: default, destructive, outline"
            />
          </FormField>
        )}

        {type === "templates" && (
          <FormField label="구조">
            <Input
              value={formData.structure}
              onChange={(e) => setFormData({ ...formData, structure: e.target.value })}
              placeholder="예: PageHeader → StatCards → DataTable"
            />
          </FormField>
        )}

        <FormField 
          label="미리보기 설명" 
          helper="실제 미리보기는 코드로 구현됩니다"
        >
          <Textarea
            value={formData.preview}
            onChange={(e) => setFormData({ ...formData, preview: e.target.value })}
            placeholder="미리보기에 표시할 내용"
            rows={3}
          />
        </FormField>

        <FormField label="사용 예제 코드" required>
          <Textarea
            value={formData.code}
            onChange={(e) => setFormData({ ...formData, code: e.target.value })}
            placeholder="import 구문과 사용 예제를 작성하세요"
            rows={8}
            className="font-mono text-sm"
            required
          />
        </FormField>

        <div className="flex justify-end gap-2 pt-4">
          <button
            type="button"
            onClick={() => onOpenChange(false)}
            className="px-4 py-2 border rounded-md hover:bg-gray-50"
          >
            취소
          </button>
          <button
            type="submit"
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            {mode === "add" ? "추가" : "수정"}
          </button>
        </div>
      </form>
    </StandardDialog>
  );
}
