"use client";

import React, { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { 
  Mail, 
  Type, 
  Image as ImageIcon, 
  Square, 
  MousePointer,
  Eye,
  Send,
  Save,
  Plus,
  Trash2,
  Settings,
  Upload,
  X
} from "lucide-react";
import { getMailTemplates } from "@/lib/api/mail";

export interface MailComponent {
  id: string;
  type: "text" | "button" | "image" | "spacer" | "table";
  content?: string;
  text?: string;
  url?: string;
  src?: string;
  height?: number;
  styles?: Record<string, string>;
}

export interface QueryConfig {
  id: string;
  name: string;
  sql: string;
  parameters: Array<{
    name: string;
    type: string;
    value?: any;
  }>;
}

interface MailDesignerProps {
  templateId?: string;
  onSave?: (data: any) => void;
  onPreview?: (data: any) => void;
  onSend?: (data: any) => void;
}

export default function MailDesigner({
  templateId,
  onSave,
  onPreview,
  onSend,
}: MailDesignerProps) {
  const [components, setComponents] = useState<MailComponent[]>([]);
  const [selectedComponent, setSelectedComponent] = useState<string | null>(null);
  const [templateName, setTemplateName] = useState("");
  const [subject, setSubject] = useState("");
  const [queries, setQueries] = useState<QueryConfig[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  // 템플릿 데이터 로드 (수정 모드)
  useEffect(() => {
    if (templateId) {
      loadTemplate(templateId);
    }
  }, [templateId]);

  const loadTemplate = async (id: string) => {
    try {
      setIsLoading(true);
      const templates = await getMailTemplates();
      const template = templates.find(t => t.id === id);
      
      if (template) {
        setTemplateName(template.name);
        setSubject(template.subject);
        setComponents(template.components || []);
        console.log('✅ 템플릿 로드 완료:', {
          name: template.name,
          components: template.components?.length || 0
        });
      }
    } catch (error) {
      console.error('❌ 템플릿 로드 실패:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 컴포넌트 타입 정의
  const componentTypes = [
    { type: "text", icon: Type, label: "텍스트", color: "bg-primary/20 hover:bg-blue-200" },
    { type: "button", icon: MousePointer, label: "버튼", color: "bg-success/20 hover:bg-success/30" },
    { type: "image", icon: ImageIcon, label: "이미지", color: "bg-purple-100 hover:bg-purple-200" },
    { type: "spacer", icon: Square, label: "여백", color: "bg-muted hover:bg-muted/80" },
  ];

  // 컴포넌트 추가
  const addComponent = (type: string) => {
    const newComponent: MailComponent = {
      id: `comp-${Date.now()}`,
      type: type as any,
      content: type === "text" ? "" : undefined, // 🎯 빈 문자열로 시작 (HTML 태그 제거)
      text: type === "button" ? "버튼 텍스트" : undefined, // 🎯 더 명확한 기본값
      url: type === "button" || type === "image" ? "" : undefined, // 🎯 빈 문자열로 시작
      src: type === "image" ? "https://placehold.co/600x200/e5e7eb/64748b?text=이미지를+업로드하세요" : undefined, // 🎯 한글 안내
      height: type === "spacer" ? 30 : undefined, // 🎯 기본값 30px로 증가 (더 적절한 간격)
      styles: {
        padding: "10px",
        backgroundColor: type === "button" ? "#007bff" : "transparent",
        color: type === "button" ? "#fff" : "#333",
      },
    };

    setComponents([...components, newComponent]);
  };

  // 컴포넌트 삭제
  const removeComponent = (id: string) => {
    setComponents(components.filter(c => c.id !== id));
    if (selectedComponent === id) {
      setSelectedComponent(null);
    }
  };

  // 컴포넌트 선택
  const selectComponent = (id: string) => {
    setSelectedComponent(id);
  };

  // 컴포넌트 내용 업데이트
  const updateComponent = (id: string, updates: Partial<MailComponent>) => {
    setComponents(
      components.map(c => c.id === id ? { ...c, ...updates } : c)
    );
  };

  // 저장
  const handleSave = () => {
    const data = {
      name: templateName,
      subject,
      components,
      queries,
    };

    if (onSave) {
      onSave(data);
    }
  };

  // 미리보기
  const handlePreview = () => {
    if (onPreview) {
      onPreview({ components, subject });
    }
  };

  // 발송
  const handleSend = () => {
    if (onSend) {
      onSend({ components, subject, queries });
    }
  };

  // 선택된 컴포넌트 가져오기
  const selected = components.find(c => c.id === selectedComponent);

  // 로딩 중일 때
  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen bg-muted/30">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-orange-500 mx-auto mb-4"></div>
          <p className="text-muted-foreground">템플릿을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-screen bg-muted/30">
      {/* 왼쪽: 컴포넌트 팔레트 */}
      <div className="w-64 bg-white border-r p-4 space-y-4 overflow-y-auto">
        <div>
          <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center">
            <Mail className="w-4 h-4 mr-2 text-primary" />
            컴포넌트
          </h3>
          <div className="space-y-2">
            {componentTypes.map(({ type, icon: Icon, label, color }) => (
              <Button
                key={type}
                onClick={() => addComponent(type)}
                variant="outline"
                className={`w-full justify-start ${color} border`}
              >
                <Icon className="w-4 h-4 mr-2" />
                {label}
              </Button>
            ))}
          </div>
        </div>

        {/* 템플릿 정보 */}
        <Card>
          <CardHeader>
            <CardTitle className="text-sm">템플릿 정보</CardTitle>
          </CardHeader>
          <CardContent className="space-y-3">
            <div>
              <Label className="text-xs">템플릿 이름</Label>
              <Input
                value={templateName}
                onChange={(e) => setTemplateName(e.target.value)}
                placeholder="예: 고객 환영 메일"
                className="mt-1"
              />
            </div>
            <div>
              <Label className="text-xs">제목</Label>
              <Input
                value={subject}
                onChange={(e) => setSubject(e.target.value)}
                placeholder="예: {customer_name}님 환영합니다!"
                className="mt-1"
              />
            </div>
          </CardContent>
        </Card>

        {/* 액션 버튼 */}
        <div className="space-y-2">
          <Button onClick={handleSave} className="w-full" variant="default">
            <Save className="w-4 h-4 mr-2" />
            저장
          </Button>
          <Button onClick={handlePreview} className="w-full" variant="outline">
            <Eye className="w-4 h-4 mr-2" />
            미리보기
          </Button>
          <Button onClick={handleSend} variant="default" className="w-full">
            <Send className="w-4 h-4 mr-2" />
            발송
          </Button>
        </div>
      </div>

      {/* 중앙: 캔버스 */}
      <div className="flex-1 p-8 overflow-y-auto">
        <Card className="max-w-3xl mx-auto">
          <CardHeader className="bg-gradient-to-r from-muted to-muted border-b">
            <CardTitle className="flex items-center justify-between">
              <span>메일 미리보기</span>
              <span className="text-sm text-muted-foreground font-normal">
                {components.length}개 컴포넌트
              </span>
            </CardTitle>
          </CardHeader>
          <CardContent className="p-0">
            {/* 제목 영역 */}
            {subject && (
              <div className="p-6 bg-muted/30 border-b">
                <p className="text-sm text-muted-foreground">제목:</p>
                <p className="font-semibold text-lg">{subject}</p>
              </div>
            )}

            {/* 컴포넌트 렌더링 */}
            <div className="p-6 space-y-4">
              {components.length === 0 ? (
                <div className="text-center py-16 text-muted-foreground/50">
                  <Mail className="w-16 h-16 mx-auto mb-4 opacity-20" />
                  <p>왼쪽에서 컴포넌트를 추가하세요</p>
                </div>
              ) : (
                components.map((comp) => (
                  <div
                    key={comp.id}
                    onClick={() => selectComponent(comp.id)}
                    className={`relative group cursor-pointer rounded-lg transition-all ${
                      selectedComponent === comp.id
                        ? "ring-2 ring-orange-500 bg-orange-50/30"
                        : "hover:ring-2 hover:ring-gray-300"
                    }`}
                    style={comp.styles}
                  >
                    {/* 삭제 버튼 */}
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        removeComponent(comp.id);
                      }}
                      className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity bg-destructive text-white rounded-full p-1 hover:bg-destructive/90"
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>

                    {/* 컴포넌트 내용 */}
                    {comp.type === "text" && (
                      <div dangerouslySetInnerHTML={{ __html: comp.content || "" }} />
                    )}
                    {comp.type === "button" && (
                      <a
                        href={comp.url}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="inline-block px-6 py-3 rounded-md"
                        style={comp.styles}
                      >
                        {comp.text}
                      </a>
                    )}
                    {comp.type === "image" && (
                      <img src={comp.src} alt="메일 이미지" className="w-full rounded" />
                    )}
                    {comp.type === "spacer" && (
                      <div style={{ height: `${comp.height}px` }} />
                    )}
                  </div>
                ))
              )}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 오른쪽: 속성 패널 */}
      <div className="w-80 bg-background border-l p-4 overflow-y-auto">
        {selected ? (
          <div className="space-y-4">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-sm font-semibold text-foreground flex items-center">
                <Settings className="w-4 h-4 mr-2 text-primary" />
                속성 편집
              </h3>
              <Button
                size="sm"
                variant="ghost"
                onClick={() => setSelectedComponent(null)}
              >
                닫기
              </Button>
            </div>

            {/* 텍스트 컴포넌트 */}
            {selected.type === "text" && (
              <div className="space-y-4">
                <div>
                  <Label className="text-sm font-medium text-foreground flex items-center gap-2">
                    내용
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1 mb-2">
                    메일에 표시될 텍스트를 입력하세요
                  </p>
                  <Textarea
                    value={(() => {
                      // 🎯 HTML 태그 자동 제거 (비개발자 친화적)
                      const content = selected.content || "";
                      const tmp = document.createElement("DIV");
                      tmp.innerHTML = content;
                      return tmp.textContent || tmp.innerText || "";
                    })()}
                    onChange={(e) =>
                      updateComponent(selected.id, { content: e.target.value })
                    }
                    onFocus={(e) => {
                      // 🎯 클릭 시 placeholder 같은 텍스트 자동 제거
                      const currentValue = e.target.value.trim();
                      if (currentValue === '텍스트를 입력하세요' || 
                          currentValue === '텍스트를 입력하세요...') {
                        e.target.value = '';
                        updateComponent(selected.id, { content: '' });
                      }
                    }}
                    rows={8}
                    className="mt-1"
                    placeholder="예) 안녕하세요! 특별한 소식을 전해드립니다..."
                  />
                </div>
              </div>
            )}

            {/* 버튼 컴포넌트 */}
            {selected.type === "button" && (
              <div className="space-y-4">
                <div>
                  <Label className="text-sm font-medium text-foreground flex items-center gap-2">
                    버튼 텍스트
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1 mb-2">
                    버튼에 표시될 글자를 입력하세요
                  </p>
                  <Input
                    value={selected.text || ""}
                    onChange={(e) =>
                      updateComponent(selected.id, { text: e.target.value })
                    }
                    className="mt-1"
                    placeholder="예) 자세히 보기, 지금 시작하기"
                  />
                </div>
                <div>
                  <Label className="text-sm font-medium text-foreground flex items-center gap-2">
                    연결할 주소
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1 mb-2">
                    버튼을 클릭하면 이동할 웹사이트 주소를 입력하세요
                  </p>
                  <Input
                    value={selected.url || ""}
                    onChange={(e) =>
                      updateComponent(selected.id, { url: e.target.value })
                    }
                    className="mt-1"
                    placeholder="예) https://www.example.com"
                  />
                </div>
                <div>
                  <Label className="text-sm font-medium text-foreground flex items-center gap-2">
                    버튼 색상
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1 mb-2">
                    버튼의 배경색을 선택하세요
                  </p>
                  <div className="flex items-center gap-3">
                    <Input
                      type="color"
                      value={selected.styles?.backgroundColor || "#007bff"}
                      onChange={(e) =>
                        updateComponent(selected.id, {
                          styles: { ...selected.styles, backgroundColor: e.target.value },
                        })
                      }
                      className="w-16 h-10 cursor-pointer"
                    />
                    <span className="text-sm text-muted-foreground">
                      {selected.styles?.backgroundColor || "#007bff"}
                    </span>
                  </div>
                </div>
              </div>
            )}

            {/* 이미지 컴포넌트 */}
            {selected.type === "image" && (
              <div className="space-y-4">
                <div>
                  <Label className="text-sm font-medium text-foreground flex items-center gap-2">
                    이미지 선택
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1 mb-2">
                    컴퓨터에서 이미지 파일을 선택하세요
                  </p>
                  
                  {/* 파일 업로드 버튼 */}
                  <div className="space-y-3">
                    <Button
                      type="button"
                      variant="outline"
                      className="w-full"
                      onClick={() => {
                        const input = document.createElement('input');
                        input.type = 'file';
                        input.accept = 'image/*';
                        input.onchange = (e: any) => {
                          const file = e.target?.files?.[0];
                          if (file) {
                            // 파일을 Base64로 변환
                            const reader = new FileReader();
                            reader.onload = (event) => {
                              updateComponent(selected.id, { 
                                src: event.target?.result as string 
                              });
                            };
                            reader.readAsDataURL(file);
                          }
                        };
                        input.click();
                      }}
                    >
                      <Upload className="w-4 h-4 mr-2" />
                      이미지 파일 선택
                    </Button>
                    
                    {/* 구분선 */}
                    <div className="relative">
                      <div className="absolute inset-0 flex items-center">
                        <div className="w-full border-t border"></div>
                      </div>
                      <div className="relative flex justify-center text-xs">
                        <span className="px-2 bg-white text-muted-foreground">또는</span>
                      </div>
                    </div>
                    
                    {/* URL 입력 */}
                    <div>
                      <Label className="text-xs text-muted-foreground mb-1 block">
                        이미지 웹 주소 입력
                      </Label>
                      <Input
                        value={selected.src || ""}
                        onChange={(e) =>
                          updateComponent(selected.id, { src: e.target.value })
                        }
                        className="text-sm"
                        placeholder="예) https://example.com/image.jpg"
                      />
                    </div>
                  </div>
                </div>
                
                {/* 미리보기 */}
                {selected.src && (
                  <div className="mt-4">
                    <div className="flex items-center justify-between mb-2">
                      <p className="text-xs text-muted-foreground">미리보기:</p>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => updateComponent(selected.id, { src: "" })}
                        className="h-6 text-xs text-red-600 hover:text-red-700 hover:bg-red-50"
                      >
                        <X className="w-3 h-3 mr-1" />
                        이미지 제거
                      </Button>
                    </div>
                    <div className="border rounded-lg p-2 bg-muted/30">
                      <img 
                        src={selected.src} 
                        alt="미리보기" 
                        className="w-full rounded"
                        onError={(e) => {
                          (e.target as HTMLImageElement).src = 'https://placehold.co/600x200?text=이미지+로드+실패';
                        }}
                      />
                    </div>
                  </div>
                )}
              </div>
            )}

            {/* 여백 컴포넌트 */}
            {selected.type === "spacer" && (
              <div className="space-y-4">
                <div>
                  <Label className="text-sm font-medium text-foreground flex items-center gap-2">
                    여백 크기
                  </Label>
                  <p className="text-xs text-muted-foreground mt-1 mb-2">
                    요소 사이의 간격을 조절하세요
                  </p>
                  <div className="flex items-center gap-3">
                    <Input
                      type="number"
                      value={selected.height || 20}
                      onChange={(e) =>
                        updateComponent(selected.id, { height: parseInt(e.target.value) || 20 })
                      }
                      className="w-24"
                      min="0"
                      max="200"
                    />
                    <span className="text-sm text-muted-foreground">픽셀</span>
                  </div>
                  <div className="mt-3 p-3 bg-primary/10 rounded-lg border border-primary/20">
                    <p className="text-xs text-primary">
                      <strong>추천값:</strong><br/>
                      • 좁은 간격: 10~20 픽셀<br/>
                      • 보통 간격: 30~50 픽셀<br/>
                      • 넓은 간격: 60~100 픽셀
                    </p>
                  </div>
                </div>
              </div>
            )}
          </div>
        ) : (
          <div className="text-center py-16 text-muted-foreground">
            <Settings className="w-12 h-12 mx-auto mb-4 opacity-20" />
            <p className="text-sm">컴포넌트를 선택하세요</p>
          </div>
        )}
      </div>
    </div>
  );
}

