"use client";

import React, { useState, useEffect } from 'react';
import { X, Save, Eye } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { MailTemplate, CreateMailTemplateDto, UpdateMailTemplateDto } from '@/lib/api/mail';
import MailDesigner from './MailDesigner';

interface MailTemplateEditorModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: (data: CreateMailTemplateDto | UpdateMailTemplateDto) => Promise<void>;
  template?: MailTemplate | null;
  mode: 'create' | 'edit';
}

export default function MailTemplateEditorModal({
  isOpen,
  onClose,
  onSave,
  template,
  mode,
}: MailTemplateEditorModalProps) {
  const [isSaving, setIsSaving] = useState(false);

  const handleSave = async (designerData: any) => {
    setIsSaving(true);
    try {
      // MailDesigner가 보내는 데이터 구조에 맞춰서 처리
      await onSave({
        name: designerData.name || designerData.templateName || '제목 없음',
        subject: designerData.subject || '제목 없음',
        components: designerData.components || [],
        category: designerData.category,
      });
      onClose();
    } catch (error) {
      console.error('템플릿 저장 실패:', error);
      alert(error instanceof Error ? error.message : '저장 중 오류가 발생했습니다.');
    } finally {
      setIsSaving(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 bg-white">
      {/* 헤더 */}
      <div className="sticky top-0 bg-background border-b px-6 py-4 flex items-center justify-between shadow-sm z-10">
        <div className="flex items-center gap-2">
          <h2 className="text-base sm:text-lg font-semibold">
            {mode === 'create' ? '새 메일 템플릿 만들기' : '메일 템플릿 수정'}
          </h2>
        </div>
        <button
          onClick={onClose}
          disabled={isSaving}
          className="text-muted-foreground hover:text-foreground rounded-md p-1 transition-colors disabled:opacity-50"
        >
          <X className="w-4 h-4" />
        </button>
      </div>

      {/* MailDesigner 컴포넌트 */}
      <div className="h-[calc(100vh-73px)] overflow-hidden">
        <MailDesigner
          templateId={template?.id}
          onSave={handleSave}
          onPreview={(data) => {
            // 미리보기 로직은 MailDesigner 내부에서 처리
            console.log('Preview:', data);
          }}
        />
      </div>
    </div>
  );
}

