/**
 * 템플릿 상세 다이얼로그
 * 
 * 템플릿에 포함된 원자/분자/유기체 컴포넌트를 확인하고 관리하는 다이얼로그
 */

import React, { useState } from "react";
import { StandardDialog } from "./molecules/StandardDialog";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Plus, Edit, Trash2, Save, X, CircleDot, SquareDashedBottom, Container } from "lucide-react";
import { toast } from "sonner@2.0.3";

interface TemplateComponent {
  name: string;
  path: string;
  description?: string;
}

interface TemplateData {
  name: string;
  path: string;
  category: string;
  description: string;
  structure: string;
  components?: {
    atoms: TemplateComponent[];
    molecules: TemplateComponent[];
    organisms: TemplateComponent[];
  };
}

interface TemplateDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  template: TemplateData | null;
  onUpdateTemplate: (updatedTemplate: TemplateData) => void;
}

export function TemplateDetailDialog({
  open,
  onOpenChange,
  template,
  onUpdateTemplate,
}: TemplateDetailDialogProps) {
  const [editingType, setEditingType] = useState<'atoms' | 'molecules' | 'organisms' | null>(null);
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const [componentName, setComponentName] = useState("");
  const [componentPath, setComponentPath] = useState("");
  const [componentDescription, setComponentDescription] = useState("");

  if (!template) return null;

  const components = template.components || { atoms: [], molecules: [], organisms: [] };

  // 컴포넌트 추가
  const handleAddComponent = (type: 'atoms' | 'molecules' | 'organisms') => {
    if (!componentName.trim()) {
      toast.error("컴포넌트 이름을 입력하세요.");
      return;
    }

    const newComponent: TemplateComponent = {
      name: componentName.trim(),
      path: componentPath.trim() || `/components/${type}/${componentName.trim()}.tsx`,
      description: componentDescription.trim(),
    };

    const updatedTemplate = {
      ...template,
      components: {
        ...components,
        [type]: [...components[type], newComponent],
      },
    };

    onUpdateTemplate(updatedTemplate);
    resetForm();
    toast.success("컴포넌트가 추가되었습니다.");
  };

  // 컴포넌트 수정
  const handleEditComponent = (type: 'atoms' | 'molecules' | 'organisms', index: number) => {
    const component = components[type][index];
    setEditingType(type);
    setEditingIndex(index);
    setComponentName(component.name);
    setComponentPath(component.path);
    setComponentDescription(component.description || "");
  };

  // 컴포넌트 수정 저장
  const handleSaveEdit = () => {
    if (!editingType || editingIndex === null) return;

    if (!componentName.trim()) {
      toast.error("컴포넌트 이름을 입력하세요.");
      return;
    }

    const updatedComponents = [...components[editingType]];
    updatedComponents[editingIndex] = {
      name: componentName.trim(),
      path: componentPath.trim() || `/components/${editingType}/${componentName.trim()}.tsx`,
      description: componentDescription.trim(),
    };

    const updatedTemplate = {
      ...template,
      components: {
        ...components,
        [editingType]: updatedComponents,
      },
    };

    onUpdateTemplate(updatedTemplate);
    resetForm();
    toast.success("컴포넌트가 수정되었습니다.");
  };

  // 컴포넌트 삭제
  const handleDeleteComponent = (type: 'atoms' | 'molecules' | 'organisms', index: number) => {
    if (!confirm("이 컴포넌트를 삭제하시겠습니까?")) return;

    const updatedComponents = components[type].filter((_, i) => i !== index);

    const updatedTemplate = {
      ...template,
      components: {
        ...components,
        [type]: updatedComponents,
      },
    };

    onUpdateTemplate(updatedTemplate);
    toast.success("컴포넌트가 삭제되었습니다.");
  };

  // 폼 초기화
  const resetForm = () => {
    setEditingType(null);
    setEditingIndex(null);
    setComponentName("");
    setComponentPath("");
    setComponentDescription("");
  };

  // 컴포넌트 리스트 렌더링
  const renderComponentList = (type: 'atoms' | 'molecules' | 'organisms', icon: any, label: string, color: string) => {
    const componentList = components[type];
    const Icon = icon;
    const isEditing = editingType === type && editingIndex === null;

    return (
      <div className="space-y-4">
        {/* 컴포넌트 추가 폼 */}
        <div className={`border rounded-lg p-4 ${color}`}>
          <div className="flex items-center gap-2 mb-3">
            <Icon className="w-5 h-5" />
            <Label className="font-medium">{label} 추가</Label>
          </div>
          <div className="space-y-3">
            <div>
              <Label className="text-xs">컴포넌트 이름 *</Label>
              <Input
                value={isEditing ? componentName : ""}
                onChange={(e) => setComponentName(e.target.value)}
                placeholder="예: Button, SearchFilter"
                disabled={editingType !== null && editingType !== type}
                onKeyPress={(e) => {
                  if (e.key === "Enter" && isEditing) {
                    handleAddComponent(type);
                  }
                }}
              />
            </div>
            <div>
              <Label className="text-xs">경로 (선택)</Label>
              <Input
                value={isEditing ? componentPath : ""}
                onChange={(e) => setComponentPath(e.target.value)}
                placeholder={`/components/${type}/ComponentName.tsx`}
                disabled={editingType !== null && editingType !== type}
              />
            </div>
            <div>
              <Label className="text-xs">설명 (선택)</Label>
              <Input
                value={isEditing ? componentDescription : ""}
                onChange={(e) => setComponentDescription(e.target.value)}
                placeholder="컴포넌트 설명"
                disabled={editingType !== null && editingType !== type}
              />
            </div>
            <div className="flex gap-2">
              {isEditing ? (
                <>
                  <Button
                    onClick={() => handleAddComponent(type)}
                    size="sm"
                    className="flex-1"
                  >
                    <Plus className="w-4 h-4 mr-2" />
                    추가
                  </Button>
                  <Button
                    variant="outline"
                    onClick={resetForm}
                    size="sm"
                  >
                    <X className="w-4 h-4" />
                  </Button>
                </>
              ) : (
                <Button
                  variant="outline"
                  onClick={() => {
                    setEditingType(type);
                    setEditingIndex(null);
                  }}
                  size="sm"
                  className="flex-1"
                  disabled={editingType !== null}
                >
                  <Plus className="w-4 h-4 mr-2" />
                  {label} 추가
                </Button>
              )}
            </div>
          </div>
        </div>

        {/* 컴포넌트 목록 */}
        <div className="space-y-2">
          <Label className="flex items-center gap-2">
            <Icon className="w-4 h-4" />
            {label} 목록 ({componentList.length}개)
          </Label>
          <div className="border rounded-lg overflow-hidden">
            {componentList.length === 0 ? (
              <div className="p-6 text-center text-sm text-muted-foreground">
                등록된 {label}가 없습니다.
              </div>
            ) : (
              componentList.map((component, index) => {
                const isEditingThis = editingType === type && editingIndex === index;

                return (
                  <div
                    key={index}
                    className="p-4 border-b last:border-b-0 bg-white hover:bg-gray-50"
                  >
                    {isEditingThis ? (
                      <div className="space-y-3">
                        <div>
                          <Label className="text-xs">컴포넌트 이름 *</Label>
                          <Input
                            value={componentName}
                            onChange={(e) => setComponentName(e.target.value)}
                            placeholder="컴포넌트 이름"
                          />
                        </div>
                        <div>
                          <Label className="text-xs">경로</Label>
                          <Input
                            value={componentPath}
                            onChange={(e) => setComponentPath(e.target.value)}
                            placeholder="경로"
                          />
                        </div>
                        <div>
                          <Label className="text-xs">설명</Label>
                          <Input
                            value={componentDescription}
                            onChange={(e) => setComponentDescription(e.target.value)}
                            placeholder="설명"
                          />
                        </div>
                        <div className="flex gap-2">
                          <Button
                            onClick={handleSaveEdit}
                            size="sm"
                          >
                            <Save className="w-4 h-4 mr-2" />
                            저장
                          </Button>
                          <Button
                            variant="outline"
                            onClick={resetForm}
                            size="sm"
                          >
                            <X className="w-4 h-4 mr-2" />
                            취소
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <div className="flex items-start gap-3">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-1">
                            <span className="font-medium">{component.name}</span>
                            <Badge variant="outline" className="text-xs">
                              {type === 'atoms' ? '원자' : type === 'molecules' ? '분자' : '유기체'}
                            </Badge>
                          </div>
                          <p className="text-sm text-muted-foreground">{component.path}</p>
                          {component.description && (
                            <p className="text-sm text-gray-600 mt-1">{component.description}</p>
                          )}
                        </div>
                        <div className="flex gap-1">
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleEditComponent(type, index)}
                            disabled={editingType !== null}
                          >
                            <Edit className="w-4 h-4" />
                          </Button>
                          <Button
                            variant="ghost"
                            size="sm"
                            onClick={() => handleDeleteComponent(type, index)}
                            disabled={editingType !== null}
                          >
                            <Trash2 className="w-4 h-4 text-red-500" />
                          </Button>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })
            )}
          </div>
        </div>
      </div>
    );
  };

  return (
    <StandardDialog
      open={open}
      onOpenChange={(open) => {
        onOpenChange(open);
        if (!open) resetForm();
      }}
      title={`${template.name} 상세정보`}
      description="템플릿에 포함된 컴포넌트를 확인하고 관리할 수 있습니다."
      size="xl"
    >
      <div className="space-y-4">
        {/* 템플릿 기본 정보 */}
        <div className="bg-gray-50 border rounded-lg p-4 space-y-2">
          <div className="flex items-center justify-between">
            <h3 className="font-medium">템플릿 정보</h3>
            <Badge>{template.category}</Badge>
          </div>
          <p className="text-sm text-gray-600">{template.description}</p>
          <div className="pt-2 border-t">
            <p className="text-xs text-gray-500 mb-1">구조:</p>
            <p className="text-sm font-mono bg-white px-3 py-2 rounded border">
              {template.structure}
            </p>
          </div>
          <div>
            <p className="text-xs text-gray-500 mb-1">경로:</p>
            <p className="text-sm text-gray-600">{template.path}</p>
          </div>
        </div>

        {/* 컴포넌트 관리 탭 */}
        <Tabs defaultValue="atoms" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="atoms">
              <CircleDot className="w-4 h-4 mr-2" />
              원자 ({components.atoms.length})
            </TabsTrigger>
            <TabsTrigger value="molecules">
              <SquareDashedBottom className="w-4 h-4 mr-2" />
              분자 ({components.molecules.length})
            </TabsTrigger>
            <TabsTrigger value="organisms">
              <Container className="w-4 h-4 mr-2" />
              유기체 ({components.organisms.length})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="atoms" className="mt-4">
            {renderComponentList('atoms', CircleDot, '원자', 'bg-blue-50')}
          </TabsContent>

          <TabsContent value="molecules" className="mt-4">
            {renderComponentList('molecules', SquareDashedBottom, '분자', 'bg-purple-50')}
          </TabsContent>

          <TabsContent value="organisms" className="mt-4">
            {renderComponentList('organisms', Container, '유기체', 'bg-green-50')}
          </TabsContent>
        </Tabs>

        {/* 안내 메시지 */}
        <div className="text-sm text-muted-foreground space-y-1 p-3 bg-blue-50 rounded-lg border border-blue-200">
          <p>• 템플릿에 포함된 모든 원자/분자/유기체 컴포넌트를 관리할 수 있습니다.</p>
          <p>• 컴포넌트 이름, 경로, 설명을 입력하여 추가할 수 있습니다.</p>
          <p>• 경로를 입력하지 않으면 기본 경로가 자동으로 설정됩니다.</p>
        </div>
      </div>
    </StandardDialog>
  );
}
