/**
 * 模板预览组件
 */
import React, { useState, useEffect } from 'react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Loader2, AlertCircle } from 'lucide-react';
import { NotificationChannelType } from '../../../NotificationChannel/List/types';
import { renderTemplate } from '../service';

interface TemplateRenderProps {
  template: string;
  channelType: NotificationChannelType;
  formData?: Record<string, any>; // 来自FormDesigner的表单数据
}

export const TemplateRender: React.FC<TemplateRenderProps> = ({
  template,
  channelType,
  formData,
}) => {
  const [loading, setLoading] = useState(false);
  const [previewContent, setPreviewContent] = useState('');
  const [error, setError] = useState<string | null>(null);

  // 预览模板
  const handlePreview = async () => {
    console.log('handlePreview called, template:', template);
    console.log('formData:', formData);

    if (!template.trim()) {
      setPreviewContent('');
      setError(null);
      console.log('Template is empty, returning');
      return;
    }

    setLoading(true);
    setError(null);
    
    try {
      // 调用后端 render API 进行 FreeMarker 模板渲染
      // 后端返回格式: { success: true, data: "渲染后的内容", message: "操作成功", code: 200 }
      // request 工具会自动解析并返回 data 字段
      const renderedContent = await renderTemplate(
        template,  // templateContext
        formData || {}  // params
      );
      
      setPreviewContent(renderedContent);
      setError(null);
    } catch (error: any) {
      console.error('Template render error:', error);
      setError(error.response?.data?.message || error.message || '渲染失败');
      setPreviewContent('');
    } finally {
      setLoading(false);
    }
  };

  // 自动预览
  useEffect(() => {
    const timer = setTimeout(() => {
      handlePreview();
    }, 500);
    
    return () => clearTimeout(timer);
  }, [template, channelType, formData]);

  return (
    <div className="h-full flex flex-col">
      {loading ? (
        <div className="flex items-center justify-center h-full">
          <Loader2 className="h-6 w-6 animate-spin mr-2" />
          加载中...
        </div>
      ) : error ? (
        <Alert variant="destructive" className="m-4">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      ) : (
        <div className="flex-1 p-4 overflow-auto">
          <div className="whitespace-pre-wrap font-mono text-sm bg-muted/30 p-4 rounded border min-h-full">
            {previewContent || '请输入模板内容进行预览'}
          </div>
        </div>
      )}
    </div>
  );
};
