/**
 * 디자인 시스템 관리 v2
 * 
 * Context 기반 CRUD 지원 버전
 */

import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "./ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Badge } from "./ui/badge";
import { 
  Palette, 
  Plus,
  Edit,
  Trash2,
  CircleDot,
  SquareDashedBottom,
  Container,
  Boxes,
  LayoutDashboard,
  AlertCircle,
  Package,
} from "lucide-react";
import { useDesignSystem } from "./contexts/DesignSystemContext";
import { ComponentManageDialog } from "./ComponentManageDialog";
import { TemplateDetailView } from "./TemplateDetailView";
import { toast } from "sonner@2.0.3";
import { EmptyState } from "./organisms/EmptyState";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "./ui/alert-dialog";

export function DesignSystemManagement2() {
  const { data, addComponent, updateComponent, deleteComponent } = useDesignSystem();
  const [activeTab, setActiveTab] = useState("overview");
  const [atomicTab, setAtomicTab] = useState("atoms");
  const [searchTerm, setSearchTerm] = useState("");
  
  // 다이얼로그 상태
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] = useState<"add" | "edit">("add");
  const [dialogType, setDialogType] = useState<"atoms" | "molecules" | "organisms" | "templates" | "widgets">("atoms");
  const [selectedComponent, setSelectedComponent] = useState<any>(null);
  
  // 삭제 확인 다이얼로그
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [componentToDelete, setComponentToDelete] = useState<{ type: any; id: string } | null>(null);
  
  // 템플릿 상세 보기
  const [selectedTemplate, setSelectedTemplate] = useState<any | null>(null);

  const handleAdd = (type: typeof dialogType) => {
    setDialogType(type);
    setDialogMode("add");
    setSelectedComponent(null);
    setDialogOpen(true);
  };

  const handleEdit = (type: typeof dialogType, component: any) => {
    setDialogType(type);
    setDialogMode("edit");
    setSelectedComponent(component);
    setDialogOpen(true);
  };

  const handleDeleteClick = (type: typeof dialogType, id: string) => {
    setComponentToDelete({ type, id });
    setDeleteDialogOpen(true);
  };

  const handleDeleteConfirm = () => {
    if (componentToDelete) {
      deleteComponent(componentToDelete.type, componentToDelete.id);
      toast.success("삭제되었습니다");
      setDeleteDialogOpen(false);
      setComponentToDelete(null);
    }
  };

  const handleSave = (componentData: any) => {
    if (dialogMode === "add") {
      addComponent(dialogType, componentData);
      toast.success("추가되었습니다");
    } else if (selectedComponent) {
      updateComponent(dialogType, selectedComponent.id, componentData);
      toast.success("수정되었습니다");
    }
  };

  const handleTemplateEdit = () => {
    if (selectedTemplate) {
      setDialogType("templates");
      setDialogMode("edit");
      setSelectedComponent(selectedTemplate);
      setSelectedTemplate(null);
      setDialogOpen(true);
    }
  };

  const handleTemplateDelete = () => {
    if (selectedTemplate) {
      setComponentToDelete({ type: "templates", id: selectedTemplate.id });
      setSelectedTemplate(null);
      setDeleteDialogOpen(true);
    }
  };

  // 필터링
  const filterComponents = (components: any[]) => {
    if (searchTerm === "") return components;
    return components.filter(comp => 
      comp.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      comp.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
      comp.category.toLowerCase().includes(searchTerm.toLowerCase())
    );
  };

  const filteredAtoms = filterComponents(data.atoms);
  const filteredMolecules = filterComponents(data.molecules);
  const filteredOrganisms = filterComponents(data.organisms);
  const filteredTemplates = filterComponents(data.templates);
  const filteredWidgets = filterComponents(data.widgets);

  const totalComponents = data.atoms.length + data.molecules.length + data.organisms.length + data.templates.length + data.widgets.length;

  // 템플릿 상세 보기인 경우
  if (selectedTemplate) {
    return (
      <TemplateDetailView
        template={selectedTemplate}
        onBack={() => setSelectedTemplate(null)}
        onEdit={handleTemplateEdit}
        onDelete={handleTemplateDelete}
      />
    );
  }

  // 컴포넌트 카드 렌더링
  const renderComponentCard = (component: any, type: typeof dialogType) => (
    <Card key={component.id} className="hover:shadow-md transition-shadow">
      <CardHeader>
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-1">
              <CardTitle className="text-lg">{component.name}</CardTitle>
              <Badge variant="outline" className="text-xs">{component.category}</Badge>
            </div>
            <CardDescription className="text-sm">{component.description}</CardDescription>
          </div>
          <div className="flex gap-1">
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleEdit(type, component)}
            >
              <Edit className="h-4 w-4" />
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleDeleteClick(type, component.id)}
            >
              <Trash2 className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </CardHeader>
      <CardContent>
        <div className="space-y-2">
          <div className="text-xs text-muted-foreground">
            <code className="bg-gray-100 px-2 py-1 rounded">{component.path}</code>
          </div>
          {component.variants && component.variants.length > 0 && (
            <div className="flex gap-1 flex-wrap">
              {component.variants.map((variant: string) => (
                <Badge key={variant} variant="secondary" className="text-xs">
                  {variant}
                </Badge>
              ))}
            </div>
          )}
          {type === "templates" && (
            <Button
              variant="link"
              size="sm"
              className="p-0 h-auto text-xs"
              onClick={() => setSelectedTemplate(component)}
            >
              상세 보기 →
            </Button>
          )}
        </div>
      </CardContent>
    </Card>
  );

  // 섹션 헤더 렌더링
  const renderSectionHeader = (title: string, type: typeof dialogType, count: number) => (
    <div className="flex items-center justify-between mb-4">
      <div>
        <h3 className="text-lg font-semibold">{title}</h3>
        <p className="text-sm text-muted-foreground">{count}개의 컴포넌트</p>
      </div>
      <Button onClick={() => handleAdd(type)}>
        <Plus className="h-4 w-4 mr-2" />
        추가
      </Button>
    </div>
  );

  return (
    <div className="flex-1 overflow-auto">
      {/* 페이지 헤더 */}
      <div className="bg-gradient-to-r from-purple-50 to-blue-50 border-b border-border p-6 sticky top-0 z-10 backdrop-blur-sm">
        <div className="flex items-center gap-4">
          <div className="bg-gradient-to-br from-purple-500 to-blue-600 p-3 rounded-xl shadow-lg">
            <Palette className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-2xl font-semibold text-foreground">디자인 시스템 관리</h1>
            <p className="text-sm text-muted-foreground mt-1">
              아토믹 디자인 시스템 - 전체 {totalComponents}개 컴포넌트 통합 관리
            </p>
          </div>
        </div>
      </div>

      <div className="p-6">
        {/* 통계 카드 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 mb-6">
          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">Atoms</p>
                  <p className="text-2xl font-semibold mt-1">{data.atoms.length}</p>
                </div>
                <div className="bg-purple-100 p-3 rounded-lg">
                  <CircleDot className="w-5 h-5 text-purple-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">Molecules</p>
                  <p className="text-2xl font-semibold mt-1">{data.molecules.length}</p>
                </div>
                <div className="bg-blue-100 p-3 rounded-lg">
                  <SquareDashedBottom className="w-5 h-5 text-blue-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">Organisms</p>
                  <p className="text-2xl font-semibold mt-1">{data.organisms.length}</p>
                </div>
                <div className="bg-green-100 p-3 rounded-lg">
                  <Container className="w-5 h-5 text-green-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">Templates</p>
                  <p className="text-2xl font-semibold mt-1">{data.templates.length}</p>
                </div>
                <div className="bg-orange-100 p-3 rounded-lg">
                  <Boxes className="w-5 h-5 text-orange-600" />
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="pt-6">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-muted-foreground">Widgets</p>
                  <p className="text-2xl font-semibold mt-1">{data.widgets.length}</p>
                </div>
                <div className="bg-pink-100 p-3 rounded-lg">
                  <LayoutDashboard className="w-5 h-5 text-pink-600" />
                </div>
              </div>
            </CardContent>
          </Card>
        </div>

        {/* 검색 */}
        <div className="mb-6">
          <Input
            type="search"
            placeholder="컴포넌트 이름, 설명, 카테고리로 검색..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="max-w-md"
          />
        </div>

        {/* 탭 */}
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="overview">📊 개요</TabsTrigger>
            <TabsTrigger value="atomic">🎨 아토믹 디자인 시스템</TabsTrigger>
            <TabsTrigger value="widgets">📦 Widgets</TabsTrigger>
          </TabsList>

          {/* 개요 탭 */}
          <TabsContent value="overview" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>아토믹 디자인 시스템</CardTitle>
                <CardDescription>
                  SAM MES의 모든 UI는 아토믹 디자인 원칙으로 구성되어 일관성과 재사용성을 보장합니다
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid md:grid-cols-2 gap-4">
                  <div className="border rounded-lg p-4 space-y-2">
                    <div className="flex items-center gap-2">
                      <CircleDot className="w-5 h-5 text-purple-600" />
                      <h4 className="font-medium">Atoms (기본 UI)</h4>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Button, Input, Select 등 가장 기본적인 UI 요소들
                    </p>
                  </div>
                  <div className="border rounded-lg p-4 space-y-2">
                    <div className="flex items-center gap-2">
                      <SquareDashedBottom className="w-5 h-5 text-blue-600" />
                      <h4 className="font-medium">Molecules (조합 컴포넌트)</h4>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      FormField, SearchBar 등 Atoms를 조합한 컴포넌트
                    </p>
                  </div>
                  <div className="border rounded-lg p-4 space-y-2">
                    <div className="flex items-center gap-2">
                      <Container className="w-5 h-5 text-green-600" />
                      <h4 className="font-medium">Organisms (복합 컴포넌트)</h4>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      PageHeader, StatCards 등 복잡한 기능 블록
                    </p>
                  </div>
                  <div className="border rounded-lg p-4 space-y-2">
                    <div className="flex items-center gap-2">
                      <Boxes className="w-5 h-5 text-orange-600" />
                      <h4 className="font-medium">Templates (페이지 템플릿)</h4>
                    </div>
                    <p className="text-sm text-muted-foreground">
                      ResponsiveListTemplate 등 완전한 페이지 레이아웃
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>

            {totalComponents === 0 && (
              <Card>
                <CardContent className="py-8">
                  <EmptyState
                    icon={Package}
                    title="컴포넌트가 없습니다"
                    description="아토믹 디자인 시스템 탭에서 컴포넌트를 추가해보세요"
                    action={
                      <Button onClick={() => setActiveTab("atomic")}>
                        컴포넌트 추가하기
                      </Button>
                    }
                  />
                </CardContent>
              </Card>
            )}
          </TabsContent>

          {/* 아토믹 디자인 시스템 탭 */}
          <TabsContent value="atomic" className="space-y-6 mt-6">
            <Tabs value={atomicTab} onValueChange={setAtomicTab}>
              <TabsList className="grid w-full grid-cols-4">
                <TabsTrigger value="atoms">Atoms ({data.atoms.length})</TabsTrigger>
                <TabsTrigger value="molecules">Molecules ({data.molecules.length})</TabsTrigger>
                <TabsTrigger value="organisms">Organisms ({data.organisms.length})</TabsTrigger>
                <TabsTrigger value="templates">Templates ({data.templates.length})</TabsTrigger>
              </TabsList>

              {/* Atoms 탭 */}
              <TabsContent value="atoms" className="space-y-4 mt-6">
                {renderSectionHeader("Atoms (기본 UI)", "atoms", data.atoms.length)}
                {filteredAtoms.length === 0 ? (
                  <EmptyState
                    icon={CircleDot}
                    title="Atoms가 없습니다"
                    description="Button, Input 등 기본 UI 컴포넌트를 추가해보세요"
                    action={
                      <Button onClick={() => handleAdd("atoms")}>
                        <Plus className="h-4 w-4 mr-2" />
                        Atom 추가
                      </Button>
                    }
                  />
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredAtoms.map((atom) => renderComponentCard(atom, "atoms"))}
                  </div>
                )}
              </TabsContent>

              {/* Molecules 탭 */}
              <TabsContent value="molecules" className="space-y-4 mt-6">
                {renderSectionHeader("Molecules (조합 컴포넌트)", "molecules", data.molecules.length)}
                {filteredMolecules.length === 0 ? (
                  <EmptyState
                    icon={SquareDashedBottom}
                    title="Molecules가 없습니다"
                    description="FormField, SearchBar 등 조합 컴포넌트를 추가해보세요"
                    action={
                      <Button onClick={() => handleAdd("molecules")}>
                        <Plus className="h-4 w-4 mr-2" />
                        Molecule 추가
                      </Button>
                    }
                  />
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredMolecules.map((molecule) => renderComponentCard(molecule, "molecules"))}
                  </div>
                )}
              </TabsContent>

              {/* Organisms 탭 */}
              <TabsContent value="organisms" className="space-y-4 mt-6">
                {renderSectionHeader("Organisms (복합 컴포넌트)", "organisms", data.organisms.length)}
                {filteredOrganisms.length === 0 ? (
                  <EmptyState
                    icon={Container}
                    title="Organisms가 없습니다"
                    description="PageHeader, StatCards 등 복합 컴포넌트를 추가해보세요"
                    action={
                      <Button onClick={() => handleAdd("organisms")}>
                        <Plus className="h-4 w-4 mr-2" />
                        Organism 추가
                      </Button>
                    }
                  />
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {filteredOrganisms.map((organism) => renderComponentCard(organism, "organisms"))}
                  </div>
                )}
              </TabsContent>

              {/* Templates 탭 */}
              <TabsContent value="templates" className="space-y-4 mt-6">
                {renderSectionHeader("Templates (페이지 템플릿)", "templates", data.templates.length)}
                {filteredTemplates.length === 0 ? (
                  <EmptyState
                    icon={Boxes}
                    title="Templates가 없습니다"
                    description="ResponsiveListTemplate 등 페이지 템플릿을 추가해보세요"
                    action={
                      <Button onClick={() => handleAdd("templates")}>
                        <Plus className="h-4 w-4 mr-2" />
                        Template 추가
                      </Button>
                    }
                  />
                ) : (
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {filteredTemplates.map((template) => renderComponentCard(template, "templates"))}
                  </div>
                )}
              </TabsContent>
            </Tabs>
          </TabsContent>

          {/* Widgets 탭 */}
          <TabsContent value="widgets" className="space-y-4 mt-6">
            {renderSectionHeader("Widgets (대시보드 위젯)", "widgets", data.widgets.length)}
            {filteredWidgets.length === 0 ? (
              <EmptyState
                icon={LayoutDashboard}
                title="Widgets가 없습니다"
                description="대시보드에 사용할 위젯을 추가해보세요"
                action={
                  <Button onClick={() => handleAdd("widgets")}>
                    <Plus className="h-4 w-4 mr-2" />
                    Widget 추가
                  </Button>
                }
              />
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {filteredWidgets.map((widget) => renderComponentCard(widget, "widgets"))}
              </div>
            )}
          </TabsContent>
        </Tabs>
      </div>

      {/* 추가/수정 다이얼로그 */}
      <ComponentManageDialog
        open={dialogOpen}
        onOpenChange={setDialogOpen}
        type={dialogType}
        mode={dialogMode}
        component={selectedComponent}
        onSave={handleSave}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>컴포넌트 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              정말로 이 컴포넌트를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleDeleteConfirm} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
