/**
 * 通知模板创建/编辑对话框
 */
import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Eye, Code } from 'lucide-react';
import { NotificationChannelType } from '../../../NotificationChannel/List/types';
import { TemplateConfigFormFactory } from './template-config-forms/TemplateConfigFormFactory';
import type {
  ChannelTypeOption,
} from '../types';
import {
  createTemplate,
  updateTemplate,
  getTemplateById,
  // checkTemplateCodeUnique, // 暂时注释掉，后端没有这个接口
  renderTemplate,
} from '../service';
import { TemplateEditor, TemplateRender } from './';

interface NotificationTemplateDialogProps {
  open: boolean;
  editId?: number;
  channelTypes: ChannelTypeOption[];
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

// 表单验证Schema
const formSchema = z.object({
  name: z.string().min(1, '请输入模板名称').max(100, '模板名称不能超过100个字符'),
  code: z.string()
    .min(1, '请输入模板编码')
    .max(50, '模板编码不能超过50个字符')
    .regex(/^[a-zA-Z][a-zA-Z0-9_]*$/, '模板编码只能包含字母、数字和下划线，且以字母开头'),
  description: z.string().max(500, '描述不能超过500个字符').optional(),
  channelType: z.nativeEnum(NotificationChannelType),
  titleTemplate: z.string().min(1, '请输入标题模板'),
  contentTemplate: z.string().min(1, '请输入模板内容'),
  templateConfig: z.object({
    // 用于后端多态反序列化，必须存在
    channelType: z.nativeEnum(NotificationChannelType),
    // 企业微信配置
    messageType: z.enum(['TEXT', 'MARKDOWN', 'FILE']).optional(),
    // 邮件配置
    contentType: z.enum(['TEXT', 'HTML']).optional(),
    priority: z.enum(['LOW', 'NORMAL', 'HIGH']).optional(),
  }).optional(),
});

type FormValues = z.infer<typeof formSchema>;

export const NotificationTemplateDialog: React.FC<NotificationTemplateDialogProps> = ({
  open,
  editId,
  channelTypes,
  onOpenChange,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [previewRendering, setPreviewRendering] = useState(false);
  const [renderedContent, setRenderedContent] = useState<string>('');
  const [currentEnabled, setCurrentEnabled] = useState<boolean>(true);
  const [formData, setFormData] = useState<Record<string, any>>({});

  const {
    register,
    handleSubmit,
    formState: { errors, isValid },
    reset,
    setValue,
    watch,
    setError,
    clearErrors,
  } = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    mode: 'onChange',
    defaultValues: {
      channelType: NotificationChannelType.WEWORK,
      titleTemplate: '',
      contentTemplate: '',
    },
  });

  const mode = editId ? 'edit' : 'create';
  const watchedChannelType = watch('channelType');
  const watchedCode = watch('code');
  const watchedTemplate = watch('contentTemplate');
  const watchedTemplateConfig = watch('templateConfig');

  // 验证编码唯一性 - 暂时注释掉，后端没有这个接口
  // const validateCodeUnique = async (code: string) => {
  //   if (!code || code.length < 1) return;
  //   
  //   try {
  //     const isUnique = await checkTemplateCodeUnique(code, editId);
  //     if (!isUnique) {
  //       setError('code', { message: '模板编码已存在' });
  //     } else {
  //       clearErrors('code');
  //     }
  //   } catch (error) {
  //     console.error('Failed to check code uniqueness:', error);
  //   }
  // };

  // 监听编码变化进行唯一性验证 - 暂时注释掉，后端没有这个接口
  // useEffect(() => {
  //   if (watchedCode && mode === 'create') {
  //     const timer = setTimeout(() => {
  //       validateCodeUnique(watchedCode);
  //     }, 500);
  //     return () => clearTimeout(timer);
  //   }
  // }, [watchedCode, mode]);

  // 加载编辑数据
  useEffect(() => {
    if (open && editId) {
      loadTemplateData();
    } else if (open) {
      // 新建时重置
      reset({
        name: '',
        code: '',
        description: '',
        channelType: NotificationChannelType.WEWORK,
        titleTemplate: '',
        contentTemplate: '',
        templateConfig: TemplateConfigFormFactory.getDefaultConfig(NotificationChannelType.WEWORK),
      });
      setShowPreview(false);
    }
  }, [open, editId]);

  // 同步内层 templateConfig.channelType，确保后端多态识别
  useEffect(() => {
    if (watchedChannelType) {
      setValue('templateConfig.channelType', watchedChannelType as any);
    }
  }, [watchedChannelType, setValue]);

  const loadTemplateData = async () => {
    if (!editId) return;
    
    setLoading(true);
    try {
      const data = await getTemplateById(editId);
      const cfg = data.templateConfig || TemplateConfigFormFactory.getDefaultConfig(data.channelType);
      // 补齐内部的 channelType
      if (!cfg.channelType) {
        (cfg as any).channelType = data.channelType;
      }
      reset({
        name: data.name,
        code: data.code,
        description: data.description || '',
        channelType: data.channelType,
        titleTemplate: data.titleTemplate || '',
        contentTemplate: data.contentTemplate,
        templateConfig: cfg,
      });
      setCurrentEnabled(Boolean(data.enabled));
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '加载失败',
        description: error.response?.data?.message || error.message,
      });
      onOpenChange(false);
    } finally {
      setLoading(false);
    }
  };

  // 处理预览按钮点击
  const handlePreviewClick = async () => {
    if (!watchedTemplate || !watchedTemplate.trim()) {
      toast({
        variant: 'destructive',
        title: '无法预览',
        description: '请先输入模板内容',
      });
      return;
    }

    setPreviewRendering(true);
    try {
      // 先调用渲染 API
      const content = await renderTemplate(
        watchedTemplate,
        formData || {}
      );
      
      // 渲染成功，保存结果并弹出预览窗口
      setRenderedContent(content);
      setShowPreview(true);
    } catch (error: any) {
      // 渲染失败，显示错误提示，不弹出窗口
      toast({
        variant: 'destructive',
        title: '渲染失败',
        description: error.response?.data?.message || error.message || '模板渲染出错，请检查模板语法',
      });
    } finally {
      setPreviewRendering(false);
    }
  };

  const onSubmit = async (values: FormValues) => {
    setSaving(true);
    try {
      // 确保 templateConfig不为空
      const templateConfig = values.templateConfig || TemplateConfigFormFactory.getDefaultConfig(values.channelType);
      
      const payload = {
        id: editId!,
        name: values.name,
        code: values.code,
        description: values.description,
        channelType: values.channelType,
        titleTemplate: values.titleTemplate,
        contentTemplate: values.contentTemplate,
        enabled: currentEnabled,
        templateConfig: templateConfig,
      };

      console.log('=== 提交模板数据 ===');
      console.log('Payload:', JSON.stringify(payload, null, 2));
      console.log('TemplateConfig:', templateConfig);

      if (mode === 'edit' && editId) {
        await updateTemplate(editId, payload);
        toast({ title: '更新成功' });
      } else {
        await createTemplate(payload);
        toast({ title: '创建成功' });
      }
      
      onSuccess();
      onOpenChange(false);
    } catch (error: any) {
      console.error('=== 提交失败 ===');
      console.error('Error:', error);
      console.error('Response:', error.response?.data);
      toast({
        variant: 'destructive',
        title: mode === 'edit' ? '更新失败' : '创建失败',
        description: error.response?.data?.message || error.message,
      });
    } finally {
      setSaving(false);
    }
  };


  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle>
              {mode === 'edit' ? '编辑' : '创建'}通知模板
            </DialogTitle>
          </DialogHeader>

          <DialogBody className="flex-1 overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin mr-2" />
                加载中...
              </div>
            ) : (
              <form onSubmit={handleSubmit(onSubmit)} className="flex flex-col space-y-4">
                {/* 基础信息 */}
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="name">
                      模板名称 <span className="text-destructive">*</span>
                    </Label>
                    <Input
                      id="name"
                      placeholder="例如：部署成功通知"
                      {...register('name')}
                    />
                    {errors.name && (
                      <p className="text-sm text-destructive">{errors.name.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="code">
                      模板编码 <span className="text-destructive">*</span>
                    </Label>
                    <Input
                      id="code"
                      placeholder="例如：deploy_success"
                      disabled={mode === 'edit'}
                      {...register('code')}
                    />
                    {mode === 'edit' && (
                      <p className="text-xs text-muted-foreground">
                        编辑时不可修改模板编码
                      </p>
                    )}
                    {errors.code && (
                      <p className="text-sm text-destructive">{errors.code.message}</p>
                    )}
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="channelType">
                      渠道类型 <span className="text-destructive">*</span>
                    </Label>
                    <Select
                      value={watchedChannelType}
                      onValueChange={(value) => setValue('channelType', value as NotificationChannelType)}
                      disabled={mode === 'edit'}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="请选择渠道类型" />
                      </SelectTrigger>
                      <SelectContent>
                        {channelTypes.map((type) => (
                          <SelectItem key={type.code} value={type.code}>
                            {type.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    {mode === 'edit' && (
                      <p className="text-xs text-muted-foreground">
                        编辑时不可修改渠道类型
                      </p>
                    )}
                    {errors.channelType && (
                      <p className="text-sm text-destructive">{errors.channelType.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="description">描述（可选）</Label>
                    <Input
                      id="description"
                      placeholder="模板用途说明"
                      {...register('description')}
                    />
                    {errors.description && (
                      <p className="text-sm text-destructive">{errors.description.message}</p>
                    )}
                  </div>
                </div>

                {/* 标题模板 */}
                <div className="space-y-2">
                  <Label htmlFor="titleTemplate">
                    标题模板 <span className="text-destructive">*</span>
                  </Label>
                  <Input
                    id="titleTemplate"
                    placeholder="请输入标题模板（支持FreeMarker语法）"
                    {...register('titleTemplate')}
                  />
                  {errors.titleTemplate && (
                    <p className="text-sm text-destructive">{errors.titleTemplate.message}</p>
                  )}
                </div>

                {/* 模板配置 */}
                {watchedChannelType && (
                  <div className="space-y-2">
                    <Label>模板配置</Label>
                    <div className="border rounded-lg p-4 bg-muted/30">
                      {TemplateConfigFormFactory.createConfigForm(
                        watchedChannelType as NotificationChannelType,
                        {
                          register,
                          errors,
                          setValue,
                          configState: watchedTemplateConfig || {},
                          updateConfigState: () => {},
                        }
                      )}
                    </div>
                  </div>
                )}

                {/* 模板编辑器区域 */}
                <div className="flex flex-col">
                  <div className="flex items-center justify-between mb-2">
                    <Label>
                      模板内容 <span className="text-destructive">*</span>
                    </Label>
                    {mode === 'edit' && (
                      <div className="flex gap-2">
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={handlePreviewClick}
                          disabled={previewRendering}
                        >
                          {previewRendering ? (
                            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                          ) : (
                            <Eye className="mr-2 h-4 w-4" />
                          )}
                          {previewRendering ? '渲染中...' : '显示预览'}
                        </Button>
                      </div>
                    )}
                  </div>

                  <div className="h-[500px]">
                    <TemplateEditor
                      value={watchedTemplate}
                      onChange={(value) => setValue('contentTemplate', value)}
                      channelType={watchedChannelType}
                      onFormDataChange={setFormData}
                      mode={mode}
                    />
                  </div>

                  {errors.contentTemplate && (
                    <p className="text-sm text-destructive mt-2">
                      {errors.contentTemplate.message}
                    </p>
                  )}
                </div>
              </form>
            )}
          </DialogBody>

          {!loading && (
            <DialogFooter>
              <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
                取消
              </Button>
              <Button
                type="button"
                disabled={saving || !isValid}
                onClick={handleSubmit(onSubmit)}
              >
                {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {mode === 'edit' ? '保存' : '创建'}
              </Button>
            </DialogFooter>
          )}
        </DialogContent>
      </Dialog>
        
      {/* 预览弹窗 - 只在编辑模式显示 */}
      {mode === 'edit' && showPreview && (
        <Dialog open={showPreview} onOpenChange={setShowPreview}>
          <DialogContent className="max-w-3xl max-h-[80vh] overflow-hidden flex flex-col">
            <DialogHeader>
              <DialogTitle>模板预览</DialogTitle>
            </DialogHeader>
            <DialogBody className="flex-1 overflow-auto">
              <div className="whitespace-pre-wrap font-mono text-sm bg-muted/30 p-4 rounded border">
                {renderedContent}
              </div>
            </DialogBody>
            <DialogFooter>
              <Button variant="outline" onClick={() => setShowPreview(false)}>
                关闭
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      )}
    </>
  );
};

export default NotificationTemplateDialog;
