/**
 * 컴포넌트 상세 미리보기 및 편집 다이얼로그
 * - 컴포넌트 실제 미리보기
 * - 하위 구성 요소(Atoms/Molecules/Organisms) 관리
 */

import React, { useState } from "react";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "./ui/dialog";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { Badge } from "./ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import { 
  Eye, Code, Layers, Plus, Edit, Trash2, Box, 
  CheckCircle, XCircle, Monitor, Smartphone, Tablet 
} from "lucide-react";
import { toast } from "sonner@2.0.3";

// UI 컴포넌트 임포트 (실제 미리보기용)
import * as UIComponents from "./ui/button";
import { PageHeader } from "./organisms/PageHeader";
import { StatCard } from "./molecules/StatCard";
import { FormField } from "./molecules/FormField";
import { SearchBar } from "./molecules/SearchBar";
import { CustomerDetailPage } from "./CustomerDetailPage";
import { IntegratedFormTemplateV3Example } from "./examples/IntegratedFormTemplateV3Example";

interface CompositionItem {
  id: string;
  componentId: string;
  componentName: string;
  componentDisplayName: string;
  componentCategory: "atoms" | "molecules" | "organisms";
  props?: Record<string, any>;
  order: number;
}

interface ComponentItem {
  id: string;
  name: string;
  displayName: string;
  category: "atoms" | "molecules" | "organisms" | "templates";
  path: string;
  description: string;
  status: "stable" | "beta" | "deprecated";
  responsive: boolean;
  composition?: CompositionItem[];
}

interface ComponentDetailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  component: ComponentItem | null;
  availableComponents: ComponentItem[];
  onUpdateComposition: (componentId: string, composition: CompositionItem[]) => void;
}

export function ComponentDetailDialog({
  open,
  onOpenChange,
  component,
  availableComponents,
  onUpdateComposition,
}: ComponentDetailDialogProps) {
  const [activeTab, setActiveTab] = useState<"preview" | "structure">("preview");
  const [composition, setComposition] = useState<CompositionItem[]>(component?.composition || []);
  const [isAddingComponent, setIsAddingComponent] = useState(false);
  const [selectedComponentId, setSelectedComponentId] = useState<string>("");
  const [previewSize, setPreviewSize] = useState<"desktop" | "tablet" | "mobile">("desktop");

  // 컴포넌트가 변경될 때 composition 업데이트
  React.useEffect(() => {
    if (component?.composition) {
      setComposition(component.composition);
    } else {
      setComposition([]);
    }
  }, [component]);

  if (!component) return null;

  // 하위 컴포넌트 추가
  const handleAddComponent = () => {
    if (!selectedComponentId) {
      toast.error("컴포넌트를 선택해주세요");
      return;
    }

    const selectedComp = availableComponents.find(c => c.id === selectedComponentId);
    if (!selectedComp) return;

    const newItem: CompositionItem = {
      id: `comp-${Date.now()}`,
      componentId: selectedComp.id,
      componentName: selectedComp.name,
      componentDisplayName: selectedComp.displayName,
      componentCategory: selectedComp.category as "atoms" | "molecules" | "organisms",
      order: composition.length,
    };

    const newComposition = [...composition, newItem];
    setComposition(newComposition);
    setIsAddingComponent(false);
    setSelectedComponentId("");
    toast.success(`${selectedComp.displayName}이(가) 추가되었습니다`);
  };

  // 하위 컴포넌트 삭제
  const handleDeleteComponent = (id: string) => {
    const newComposition = composition.filter(c => c.id !== id);
    setComposition(newComposition);
    toast.success("컴포넌트가 삭제되었습니다");
  };

  // 순서 변경
  const handleMoveUp = (index: number) => {
    if (index === 0) return;
    const newComposition = [...composition];
    [newComposition[index - 1], newComposition[index]] = [newComposition[index], newComposition[index - 1]];
    newComposition.forEach((item, idx) => {
      item.order = idx;
    });
    setComposition(newComposition);
  };

  const handleMoveDown = (index: number) => {
    if (index === composition.length - 1) return;
    const newComposition = [...composition];
    [newComposition[index], newComposition[index + 1]] = [newComposition[index + 1], newComposition[index]];
    newComposition.forEach((item, idx) => {
      item.order = idx;
    });
    setComposition(newComposition);
  };

  // 저장
  const handleSave = () => {
    onUpdateComposition(component.id, composition);
    onOpenChange(false);
    toast.success("컴포넌트 구조가 저장되었습니다");
  };

  // 카테고리별 아이콘
  const getCategoryIcon = (category: string) => {
    switch (category) {
      case "atoms":
        return <Box className="w-4 h-4" />;
      case "molecules":
        return <Layers className="w-4 h-4" />;
      case "organisms":
        return <Code className="w-4 h-4" />;
      default:
        return <Box className="w-4 h-4" />;
    }
  };

  // 카테고리별 색상
  const getCategoryColor = (category: string) => {
    switch (category) {
      case "atoms":
        return "bg-blue-50 text-blue-700 border-blue-200";
      case "molecules":
        return "bg-purple-50 text-purple-700 border-purple-200";
      case "organisms":
        return "bg-green-50 text-green-700 border-green-200";
      default:
        return "bg-gray-50 text-gray-700 border-gray-200";
    }
  };

  // 컴포넌트 미리보기 렌더링
  const renderPreview = () => {
    const previewClass = 
      previewSize === "mobile" ? "max-w-[375px]" :
      previewSize === "tablet" ? "max-w-[768px]" :
      "w-full";

    // 간단한 컴포넌트 미리보기 (실제로는 동적 import 필요)
    return (
      <div className={`${previewClass} mx-auto border rounded-lg p-6 bg-white shadow-sm`}>
        <div className="space-y-4">
          <div className="border-b pb-4">
            <h3 className="font-semibold text-lg">{component.displayName} 미리보기</h3>
            <p className="text-sm text-muted-foreground mt-1">{component.description}</p>
          </div>

          {/* 컴포넌트별 미리보기 예시 */}
          {component.category === "atoms" && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">
                원자 단위 컴포넌트는 가장 기본적인 UI 요소입니다.
              </p>
              <div className="flex gap-2 flex-wrap">
                <Badge>예시 배지</Badge>
                <Button size="sm">예시 버튼</Button>
                <Input placeholder="예시 입력 필드" className="max-w-[200px]" />
              </div>
            </div>
          )}

          {component.category === "molecules" && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">
                분자 단위 컴포넌트는 여러 원자를 조합한 요소입니다.
              </p>
              {component.name === "FormField" && (
                <FormField
                  label="예시 필드"
                  required
                  error="오류 메시지 예시"
                >
                  <Input placeholder="입력해주세요" />
                </FormField>
              )}
              {component.name === "SearchBar" && (
                <SearchBar
                  value=""
                  onChange={() => {}}
                  placeholder="검색어를 입력하세요"
                />
              )}
            </div>
          )}

          {component.category === "organisms" && (
            <div className="space-y-3">
              <p className="text-sm text-muted-foreground">
                유기체 단위 컴포넌트는 복잡한 UI 구성 요소입니다.
              </p>
              {component.name === "PageHeader" && (
                <PageHeader
                  title="페이지 제목 예시"
                  description="페이지 설명 예시"
                  icon={Eye}
                />
              )}
            </div>
          )}

          {component.category === "templates" && (
            <div className="space-y-3">
              {/* IntegratedFormTemplateV2 실제 미리보기 */}
              {component.name === "IntegratedFormTemplateV2" ? (
                <div className="border rounded-lg overflow-hidden">
                  <CustomerDetailPage />
                </div>
              ) : component.name === "IntegratedFormTemplateV3" ? (
                <div className="border rounded-lg overflow-hidden">
                  <IntegratedFormTemplateV3Example />
                </div>
              ) : (
                <div>
                  <p className="text-sm text-muted-foreground mb-4">
                    템플릿은 전체 페이지 레이아웃을 정의합니다.
                  </p>
                  <div className="border-2 border-dashed border-gray-300 rounded p-4 text-center text-muted-foreground">
                    템플릿 레이아웃 영역
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 구성 요소 표시 */}
          {composition.length > 0 && (
            <div className="mt-6 pt-6 border-t">
              <h4 className="font-medium mb-3">구성 요소 ({composition.length}개)</h4>
              <div className="space-y-2">
                {composition.map((item, index) => (
                  <div key={item.id} className="flex items-center gap-2 p-2 bg-muted rounded">
                    <span className="text-sm text-muted-foreground">{index + 1}.</span>
                    {getCategoryIcon(item.componentCategory)}
                    <span className="text-sm font-medium">{item.componentDisplayName}</span>
                    <Badge variant="outline" className={getCategoryColor(item.componentCategory)}>
                      {item.componentCategory}
                    </Badge>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    );
  };

  // 하위 컴포넌트만 필터링 (atoms, molecules만)
  const getAvailableSubComponents = () => {
    if (component.category === "templates") {
      return availableComponents.filter(c => 
        c.category === "organisms" || c.category === "molecules" || c.category === "atoms"
      );
    }
    if (component.category === "organisms") {
      return availableComponents.filter(c => 
        c.category === "molecules" || c.category === "atoms"
      );
    }
    if (component.category === "molecules") {
      return availableComponents.filter(c => c.category === "atoms");
    }
    return [];
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-6xl max-h-[90vh] overflow-hidden flex flex-col">
        <DialogHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <DialogTitle className="text-2xl">{component.displayName}</DialogTitle>
              <Badge variant={component.status === "stable" ? "default" : "secondary"}>
                {component.status}
              </Badge>
              <Badge variant="outline" className={getCategoryColor(component.category)}>
                {component.category}
              </Badge>
            </div>
            <div className="flex gap-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPreviewSize("desktop")}
                className={previewSize === "desktop" ? "bg-primary/10" : ""}
              >
                <Monitor className="w-4 h-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPreviewSize("tablet")}
                className={previewSize === "tablet" ? "bg-primary/10" : ""}
              >
                <Tablet className="w-4 h-4" />
              </Button>
              <Button
                variant="outline"
                size="sm"
                onClick={() => setPreviewSize("mobile")}
                className={previewSize === "mobile" ? "bg-primary/10" : ""}
              >
                <Smartphone className="w-4 h-4" />
              </Button>
            </div>
          </div>
          <DialogDescription>
            {component.description}
          </DialogDescription>
        </DialogHeader>

        <Tabs value={activeTab} onValueChange={(v: any) => setActiveTab(v)} className="flex-1 flex flex-col overflow-hidden">
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="preview">
              <Eye className="w-4 h-4 mr-2" />
              미리보기
            </TabsTrigger>
            <TabsTrigger value="structure">
              <Layers className="w-4 h-4 mr-2" />
              구조 편집
            </TabsTrigger>
          </TabsList>

          <TabsContent value="preview" className="flex-1 overflow-y-auto mt-4">
            {renderPreview()}
          </TabsContent>

          <TabsContent value="structure" className="flex-1 overflow-y-auto mt-4">
            <div className="space-y-6">
              {/* 컴포넌트 정보 */}
              <Card>
                <CardHeader>
                  <CardTitle className="text-base">컴포넌트 정보</CardTitle>
                </CardHeader>
                <CardContent className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <Label className="text-muted-foreground">이름</Label>
                    <p className="font-medium">{component.name}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">카테고리</Label>
                    <p className="font-medium">{component.category}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">경로</Label>
                    <p className="font-mono text-xs">{component.path}</p>
                  </div>
                  <div>
                    <Label className="text-muted-foreground">반응형</Label>
                    <p className="font-medium">{component.responsive ? "지원" : "미지원"}</p>
                  </div>
                </CardContent>
              </Card>

              {/* 구성 요소 관리 */}
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-base">
                      구성 요소 ({composition.length}개)
                    </CardTitle>
                    {getAvailableSubComponents().length > 0 && (
                      <Button size="sm" onClick={() => setIsAddingComponent(true)}>
                        <Plus className="w-4 h-4 mr-1" />
                        추가
                      </Button>
                    )}
                  </div>
                  <CardDescription>
                    이 컴포넌트를 구성하는 하위 요소들을 관리합니다
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  {/* 컴포넌트 추가 폼 */}
                  {isAddingComponent && (
                    <div className="mb-4 p-4 border rounded-lg bg-muted/30">
                      <Label>하위 컴포넌트 선택</Label>
                      <div className="flex gap-2 mt-2">
                        <Select value={selectedComponentId} onValueChange={setSelectedComponentId}>
                          <SelectTrigger className="flex-1">
                            <SelectValue placeholder="컴포넌트를 선택하세요" />
                          </SelectTrigger>
                          <SelectContent>
                            {getAvailableSubComponents().map((comp) => (
                              <SelectItem key={comp.id} value={comp.id}>
                                <div className="flex items-center gap-2">
                                  {getCategoryIcon(comp.category)}
                                  <span>{comp.displayName}</span>
                                  <Badge variant="outline" className="ml-2">
                                    {comp.category}
                                  </Badge>
                                </div>
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <Button onClick={handleAddComponent}>추가</Button>
                        <Button variant="outline" onClick={() => {
                          setIsAddingComponent(false);
                          setSelectedComponentId("");
                        }}>
                          취소
                        </Button>
                      </div>
                    </div>
                  )}

                  {/* 구성 요소 목록 */}
                  {composition.length > 0 ? (
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead className="w-12">#</TableHead>
                          <TableHead>컴포넌트</TableHead>
                          <TableHead>카테고리</TableHead>
                          <TableHead className="w-32">순서</TableHead>
                          <TableHead className="w-24">작업</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {composition.map((item, index) => (
                          <TableRow key={item.id}>
                            <TableCell>{index + 1}</TableCell>
                            <TableCell>
                              <div className="flex items-center gap-2">
                                {getCategoryIcon(item.componentCategory)}
                                <span className="font-medium">{item.componentDisplayName}</span>
                              </div>
                            </TableCell>
                            <TableCell>
                              <Badge variant="outline" className={getCategoryColor(item.componentCategory)}>
                                {item.componentCategory}
                              </Badge>
                            </TableCell>
                            <TableCell>
                              <div className="flex gap-1">
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleMoveUp(index)}
                                  disabled={index === 0}
                                >
                                  ↑
                                </Button>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handleMoveDown(index)}
                                  disabled={index === composition.length - 1}
                                >
                                  ↓
                                </Button>
                              </div>
                            </TableCell>
                            <TableCell>
                              <Button
                                variant="ghost"
                                size="sm"
                                onClick={() => handleDeleteComponent(item.id)}
                              >
                                <Trash2 className="w-4 h-4 text-destructive" />
                              </Button>
                            </TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  ) : (
                    <div className="text-center py-8 text-muted-foreground">
                      <Layers className="w-12 h-12 mx-auto mb-2 opacity-50" />
                      <p>구성 요소가 없습니다</p>
                      {getAvailableSubComponents().length > 0 && (
                        <p className="text-sm mt-1">상단의 "추가" 버튼을 클릭하여 하위 컴포넌트를 추가하세요</p>
                      )}
                    </div>
                  )}
                </CardContent>
              </Card>
            </div>
          </TabsContent>
        </Tabs>

        <DialogFooter className="mt-4">
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            취소
          </Button>
          <Button onClick={handleSave}>
            <CheckCircle className="w-4 h-4 mr-2" />
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}