import React, { useState, useEffect } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/components/ui/use-toast';
import { Loader2, Send, TestTube, Settings } from 'lucide-react';
import type { NotificationTemplateDTO } from '../types';
import type { NotificationChannelDTO } from '../../../NotificationChannel/List/types';
import { getChannelsPage } from '../../../NotificationChannel/List/service';
import { sendTestMessage, type TestMessageRequest } from '../service';
import { FormDesigner, FormRenderer, type FormSchema } from '@/components/FormDesigner';

interface TestTemplateDialogProps {
  open: boolean;
  template?: NotificationTemplateDTO;
  onOpenChange: (open: boolean) => void;
}


const TestTemplateDialog: React.FC<TestTemplateDialogProps> = ({
  open,
  template,
  onOpenChange,
}) => {
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);
  const [channels, setChannels] = useState<NotificationChannelDTO[]>([]);
  const [selectedChannelId, setSelectedChannelId] = useState<string>('');
  const [formSchema, setFormSchema] = useState<FormSchema | null>(null);
  const [formData, setFormData] = useState<Record<string, any>>({});
  const [designerOpen, setDesignerOpen] = useState(false);

  // 加载渠道列表
  useEffect(() => {
    if (open) {
      loadChannels();
      // 打开时清空上次数据，用户可通过表单设计器自定义参数
      setFormSchema(null);
      setFormData({});
    }
  }, [open, template]);

  // 参数变化不再触发后端渲染（此页面不调用渲染接口）

  const loadChannels = async () => {
    try {
      const res = await getChannelsPage({
        enabled: true,
        page: 0,
        size: 100,
      });
      setChannels(res.content || []);
    } catch (error: any) {
      toast({
        variant: 'destructive',
        title: '加载渠道失败',
        description: error.response?.data?.message || error.message,
      });
    }
  };

  // 渲染模板内容
  // 不再调用后端渲染接口，此处保留占位以说明设计意图

  // 不再基于正则推断参数，改为表单设计器动态定义

  // 发送测试消息
  const handleSend = async () => {
    if (!selectedChannelId || !template) {
      toast({
        variant: 'destructive',
        title: '请选择渠道',
      });
      return;
    }

    setLoading(true);
    try {
      const request: TestMessageRequest = {
        channelId: parseInt(selectedChannelId),
        notificationTemplateId: template.id,
        params: formData || {},
      };

      await sendTestMessage(request);
      
      toast({
        title: '测试消息发送成功',
        description: '请检查对应渠道是否收到消息',
      });
      
      onOpenChange(false);
    } catch (error: any) {
      // 错误已经在 request.ts 中通过 toast 显示了，这里不需要再显示
    } finally {
      setLoading(false);
    }
  };

  // 重置状态
  const handleClose = () => {
    setSelectedChannelId('');
    setFormSchema(null);
    setFormData({});
    onOpenChange(false);
  };

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-xl">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <TestTube className="h-5 w-5" />
            测试模板消息
          </DialogTitle>
        </DialogHeader>

        <DialogBody className="space-y-4">
          {/* 模板信息 */}
          <div className="p-3 bg-muted/50 rounded-md">
            <div className="text-sm">
              <div className="font-medium">{template?.name}</div>
              <div className="text-muted-foreground mt-1">
                类型：{template?.channelType}
              </div>
            </div>
          </div>

          {/* 选择渠道 */}
          <div className="space-y-2">
            <Label htmlFor="channel-select">选择渠道 *</Label>
            <Select value={selectedChannelId} onValueChange={setSelectedChannelId}>
              <SelectTrigger id="channel-select">
                <SelectValue placeholder="请选择要测试的渠道" />
              </SelectTrigger>
              <SelectContent>
                {channels
                  .filter(channel => channel.channelType === template?.channelType)
                  .map(channel => (
                    <SelectItem key={channel.id} value={channel.id!.toString()}>
                      {channel.name}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
          </div>

          {/* 模板参数（动态表单） */}
          <div className="space-y-3">
            <div className="flex items-center justify-between">
              <Label>模板参数</Label>
              <Button type="button" variant="ghost" size="sm" onClick={() => setDesignerOpen(true)}>
                <Settings className="h-4 w-4 mr-1" /> 设计参数表单
              </Button>
            </div>
            {formSchema ? (
              <div className="border rounded p-3 bg-muted/30">
                <FormRenderer
                  schema={formSchema}
                  onChange={(data) => setFormData(data)}
                  showSubmit={false}
                  showCancel={false}
                />
              </div>
            ) : (
              <div className="text-xs text-muted-foreground">未定义参数表单，点击右上角按钮进行设计。</div>
            )}
          </div>

          {/* 模板内容 */}
          <div className="space-y-2">
            <Label>模板内容</Label>
            <Textarea
              value={template?.contentTemplate || ''}
              readOnly
              className="min-h-[120px] bg-muted/30 text-sm"
              placeholder="模板内容"
            />
          </div>
        </DialogBody>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>
            取消
          </Button>
          <Button 
            onClick={handleSend} 
            disabled={loading || !selectedChannelId}
          >
            {loading ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                发送中...
              </>
            ) : (
              <>
                <Send className="h-4 w-4 mr-2" />
                发送测试
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>

      {/* 参数表单设计器 */}
      <Dialog open={designerOpen} onOpenChange={setDesignerOpen}>
        <DialogContent className="max-w-5xl max-h-[90vh] overflow-hidden flex flex-col">
          <DialogHeader>
            <DialogTitle>参数表单设计器</DialogTitle>
          </DialogHeader>
          <DialogBody className="flex-1 overflow-hidden">
            <div className="h-[70vh]">
              <FormDesigner
                value={formSchema}
                onChange={setFormSchema}
                onSave={(schema) => {
                  setFormSchema(schema);
                  setDesignerOpen(false);
                }}
              />
            </div>
          </DialogBody>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDesignerOpen(false)}>取消</Button>
            <Button onClick={() => setDesignerOpen(false)}>完成</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </Dialog>
  );
};

export default TestTemplateDialog;
