import { useState, useEffect } from 'react';
import { Card } from '../ui/card';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Badge } from '../ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '../ui/dialog';
import { Label } from '../ui/label';
import { Textarea } from '../ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Switch } from '../ui/switch';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { MessageTemplate as MessageTemplateType } from '../../types/message';
import { Search, Plus, Edit, Trash2, Send, Download, Upload, Mail, MessageSquare, Smartphone, Bell } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function MessageTemplate() {
  const [templates, setTemplates] = useState<MessageTemplateType[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [showDialog, setShowDialog] = useState(false);
  const [showTestDialog, setShowTestDialog] = useState(false);
  const [editingTemplate, setEditingTemplate] = useState<MessageTemplateType | null>(null);
  const [testTemplate, setTestTemplate] = useState<MessageTemplateType | null>(null);

  const [formData, setFormData] = useState({
    code: '',
    name: '',
    type: 'internal' as 'sms' | 'email' | 'internal' | 'push',
    subject: '',
    content: '',
    variables: [] as string[],
    description: '',
    isActive: true,
  });

  const [testData, setTestData] = useState({
    recipient: '',
    variables: {} as Record<string, string>,
  });

  useEffect(() => {
    loadTemplates();
  }, []);

  const loadTemplates = () => {
    const data = localStorage.getItem('smart_agriculture_message_templates');
    if (data) {
      setTemplates(JSON.parse(data));
    } else {
      const mockTemplates: MessageTemplateType[] = [
        {
          id: 'tpl-1',
          code: 'TASK_ASSIGNED',
          name: '任务分配通知',
          type: 'internal',
          subject: '新任务分配',
          content: '您好，{{username}}！您有新的作业任务：{{taskName}}，计划执行时间：{{executeTime}}。请及时查看并准备。',
          variables: ['username', 'taskName', 'executeTime'],
          isActive: true,
          description: '当任务分配给驾驶员时发送',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          createdBy: 'admin',
        },
        {
          id: 'tpl-2',
          code: 'EQUIPMENT_WARNING',
          name: '设备预警通知',
          type: 'sms',
          content: '【智慧农业】设备预警：{{equipmentName}}检测到异常，{{warningType}}，请及时处理。',
          variables: ['equipmentName', 'warningType'],
          isActive: true,
          description: '设备出现异常时发送短信通知',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          createdBy: 'admin',
        },
        {
          id: 'tpl-3',
          code: 'MAINTENANCE_REMINDER',
          name: '保养提醒',
          type: 'email',
          subject: '设备保养提醒',
          content: '尊敬的用户：\n\n您的设备{{equipmentName}}（编号：{{equipmentCode}}）已使用{{hours}}小时，建议进行保养维护。\n\n保养周期：{{maintenanceCycle}}\n上次保养时间：{{lastMaintenanceTime}}\n\n请及时安排保养，确保设备正常运行。\n\n智慧农业管理系统',
          variables: ['equipmentName', 'equipmentCode', 'hours', 'maintenanceCycle', 'lastMaintenanceTime'],
          isActive: true,
          description: '设备到达保养周期时发送邮件提醒',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          createdBy: 'admin',
        },
        {
          id: 'tpl-4',
          code: 'TASK_COMPLETED',
          name: '任务完成通知',
          type: 'push',
          subject: '任务完成',
          content: '作业任务{{taskName}}已完成，作业面积：{{area}}亩，耗时：{{duration}}。',
          variables: ['taskName', 'area', 'duration'],
          isActive: true,
          description: '任务完成后推送通知',
          createdAt: '2024-01-01T00:00:00',
          updatedAt: '2024-01-01T00:00:00',
          createdBy: 'admin',
        },
      ];
      localStorage.setItem('smart_agriculture_message_templates', JSON.stringify(mockTemplates));
      setTemplates(mockTemplates);
    }
  };

  const saveTemplates = (newTemplates: MessageTemplateType[]) => {
    localStorage.setItem('smart_agriculture_message_templates', JSON.stringify(newTemplates));
    setTemplates(newTemplates);
  };

  const filteredTemplates = templates.filter(tpl => {
    const matchKeyword = !searchKeyword ||
      tpl.name.includes(searchKeyword) ||
      tpl.code.includes(searchKeyword) ||
      tpl.content.includes(searchKeyword);
    const matchType = typeFilter === 'all' || tpl.type === typeFilter;
    return matchKeyword && matchType;
  });

  const handleAdd = () => {
    setEditingTemplate(null);
    setFormData({
      code: '',
      name: '',
      type: 'internal',
      subject: '',
      content: '',
      variables: [],
      description: '',
      isActive: true,
    });
    setShowDialog(true);
  };

  const handleEdit = (template: MessageTemplateType) => {
    setEditingTemplate(template);
    setFormData({
      code: template.code,
      name: template.name,
      type: template.type,
      subject: template.subject || '',
      content: template.content,
      variables: template.variables,
      description: template.description || '',
      isActive: template.isActive,
    });
    setShowDialog(true);
  };

  const handleDelete = (id: string) => {
    const updated = templates.filter(t => t.id !== id);
    saveTemplates(updated);
    toast.success('删除成功');
  };

  const handleSave = () => {
    if (!formData.code.trim() || !formData.name.trim() || !formData.content.trim()) {
      toast.error('请填写必填项');
      return;
    }

    const now = new Date().toISOString();
    
    // 提取变量
    const variableRegex = /\{\{(\w+)\}\}/g;
    const matches = formData.content.matchAll(variableRegex);
    const extractedVars = Array.from(new Set(Array.from(matches, m => m[1])));

    if (editingTemplate) {
      const updated = templates.map(t =>
        t.id === editingTemplate.id
          ? {
              ...t,
              ...formData,
              variables: extractedVars,
              updatedAt: now,
            }
          : t
      );
      saveTemplates(updated);
      toast.success('更新成功');
    } else {
      const newTemplate: MessageTemplateType = {
        id: `tpl-${Date.now()}`,
        ...formData,
        variables: extractedVars,
        createdAt: now,
        updatedAt: now,
        createdBy: 'admin',
      };
      saveTemplates([...templates, newTemplate]);
      toast.success('添加成功');
    }

    setShowDialog(false);
  };

  const handleTest = (template: MessageTemplateType) => {
    setTestTemplate(template);
    const varsObj: Record<string, string> = {};
    template.variables.forEach(v => {
      varsObj[v] = '';
    });
    setTestData({
      recipient: '',
      variables: varsObj,
    });
    setShowTestDialog(true);
  };

  const handleSendTest = () => {
    if (!testData.recipient.trim()) {
      toast.error('请输入接收人');
      return;
    }

    // 检查变量是否都填写了
    const emptyVars = Object.entries(testData.variables).filter(([k, v]) => !v.trim());
    if (emptyVars.length > 0) {
      toast.error(`请填写变量：${emptyVars.map(([k]) => k).join(', ')}`);
      return;
    }

    toast.success('测试消息发送成功');
    setShowTestDialog(false);
  };

  const handleExport = () => {
    const dataStr = JSON.stringify(filteredTemplates, null, 2);
    const dataBlob = new Blob([dataStr], { type: 'application/json' });
    const url = URL.createObjectURL(dataBlob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `message_templates_${new Date().getTime()}.json`;
    link.click();
    toast.success('导出成功');
  };

  const getTypeIcon = (type: string) => {
    switch (type) {
      case 'sms': return <Smartphone className="w-4 h-4" />;
      case 'email': return <Mail className="w-4 h-4" />;
      case 'internal': return <MessageSquare className="w-4 h-4" />;
      case 'push': return <Bell className="w-4 h-4" />;
      default: return <MessageSquare className="w-4 h-4" />;
    }
  };

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      sms: '短信',
      email: '邮件',
      internal: '站内信',
      push: '推送',
    };
    return labels[type] || type;
  };

  const getTypeBadge = (type: string) => {
    const colors: Record<string, string> = {
      sms: 'bg-blue-100 text-blue-700',
      email: 'bg-purple-100 text-purple-700',
      internal: 'bg-green-100 text-green-700',
      push: 'bg-orange-100 text-orange-700',
    };
    return colors[type] || 'bg-gray-100 text-gray-700';
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800">消息模版</h2>
          <p className="text-muted-foreground">集中管理各类系统消息模板</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleExport}>
            <Download className="w-4 h-4 mr-2" />
            导出
          </Button>
          <Button onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            新增模版
          </Button>
        </div>
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              placeholder="搜索模板名称、编码、内容..."
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              className="pl-10"
            />
          </div>
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger>
              <SelectValue placeholder="消息类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="sms">短信</SelectItem>
              <SelectItem value="email">邮件</SelectItem>
              <SelectItem value="internal">站内信</SelectItem>
              <SelectItem value="push">推送</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 模板列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>模板编码</TableHead>
              <TableHead>模板名称</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>变量</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredTemplates.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  暂无模板数据
                </TableCell>
              </TableRow>
            ) : (
              filteredTemplates.map((template) => (
                <TableRow key={template.id}>
                  <TableCell>
                    <code className="text-xs bg-gray-100 px-2 py-1 rounded">
                      {template.code}
                    </code>
                  </TableCell>
                  <TableCell>
                    <div>
                      <div>{template.name}</div>
                      {template.description && (
                        <p className="text-xs text-muted-foreground">{template.description}</p>
                      )}
                    </div>
                  </TableCell>
                  <TableCell>
                    <Badge className={getTypeBadge(template.type)}>
                      <span className="flex items-center gap-1">
                        {getTypeIcon(template.type)}
                        {getTypeLabel(template.type)}
                      </span>
                    </Badge>
                  </TableCell>
                  <TableCell>
                    <div className="flex flex-wrap gap-1">
                      {template.variables.map(v => (
                        <Badge key={v} variant="outline" className="text-xs">
                          {v}
                        </Badge>
                      ))}
                    </div>
                  </TableCell>
                  <TableCell>
                    {template.isActive ? (
                      <Badge className="bg-green-100 text-green-700">启用</Badge>
                    ) : (
                      <Badge variant="outline">停用</Badge>
                    )}
                  </TableCell>
                  <TableCell>
                    <div className="flex gap-1">
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleTest(template)}
                      >
                        <Send className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleEdit(template)}
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => handleDelete(template.id)}
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 编辑对话框 */}
      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {editingTemplate ? '编辑模版' : '新增模版'}
            </DialogTitle>
            <DialogDescription className="sr-only">
              {editingTemplate ? '编辑消息模版' : '添加新消息模版'}
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>模板编码 *</Label>
                <Input
                  value={formData.code}
                  onChange={(e) => setFormData({ ...formData, code: e.target.value })}
                  placeholder="TASK_ASSIGNED"
                />
              </div>
              <div>
                <Label>模板名称 *</Label>
                <Input
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="任务分配通知"
                />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label>消息类型 *</Label>
                <Select
                  value={formData.type}
                  onValueChange={(value: any) => setFormData({ ...formData, type: value })}
                >
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="sms">短信</SelectItem>
                    <SelectItem value="email">邮件</SelectItem>
                    <SelectItem value="internal">站内信</SelectItem>
                    <SelectItem value="push">推送</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center justify-between pt-6">
                <Label>是否启用</Label>
                <Switch
                  checked={formData.isActive}
                  onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
                />
              </div>
            </div>
            {(formData.type === 'email' || formData.type === 'push') && (
              <div>
                <Label>消息主题</Label>
                <Input
                  value={formData.subject}
                  onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                  placeholder="输入消息主题"
                />
              </div>
            )}
            <div>
              <Label>消息内容 *</Label>
              <Textarea
                value={formData.content}
                onChange={(e) => setFormData({ ...formData, content: e.target.value })}
                placeholder="输入消息内容，使用 {{变量名}} 表示变量"
                rows={6}
              />
              <p className="text-xs text-muted-foreground mt-1">
                提示：使用 {'{{'} 和 {'}'} 包裹变量名，如 {'{{username}}'}、{'{{taskName}}'}
              </p>
            </div>
            <div>
              <Label>描述</Label>
              <Textarea
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="模板用途说明"
                rows={2}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSave}>
              保存
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 测试发送对话框 */}
      <Dialog open={showTestDialog} onOpenChange={setShowTestDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>
              <div className="flex items-center gap-2">
                <Send className="w-5 h-5 text-green-600" />
                发送测试消息
              </div>
            </DialogTitle>
            <DialogDescription className="sr-only">
              测试发送消息模版
            </DialogDescription>
          </DialogHeader>
          {testTemplate && (
            <div className="space-y-4">
              <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
                <p className="text-sm text-blue-900">
                  模板：{testTemplate.name}
                </p>
              </div>
              <div>
                <Label>接收人 *</Label>
                <Input
                  value={testData.recipient}
                  onChange={(e) => setTestData({ ...testData, recipient: e.target.value })}
                  placeholder={
                    testTemplate.type === 'sms' ? '手机号' :
                    testTemplate.type === 'email' ? '邮箱地址' :
                    '用户ID'
                  }
                />
              </div>
              {testTemplate.variables.length > 0 && (
                <div className="space-y-3">
                  <Label>填写变量值</Label>
                  {testTemplate.variables.map(v => (
                    <div key={v}>
                      <Label className="text-sm text-muted-foreground">{v}</Label>
                      <Input
                        value={testData.variables[v] || ''}
                        onChange={(e) => setTestData({
                          ...testData,
                          variables: { ...testData.variables, [v]: e.target.value }
                        })}
                        placeholder={`输入 ${v} 的值`}
                      />
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowTestDialog(false)}>
              取消
            </Button>
            <Button onClick={handleSendTest}>
              <Send className="w-4 h-4 mr-2" />
              发送测试
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 使用说明 */}
      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2">
          <MessageSquare className="w-4 h-4 inline mr-2" />
          消息模版说明
        </h4>
        <ul className="space-y-1 text-sm text-blue-800">
          <li>• 支持短信、邮件、站内信、推送四种消息类型</li>
          <li>• 使用 {'{{变量名}}'} 语法嵌入动态变量，系统会自动提取</li>
          <li>• 可以发送测试消息验证模板效果</li>
          <li>• 模板支持导入导出，便于跨环境迁移</li>
          <li>• 停用的模板不会被系统使用</li>
        </ul>
      </Card>
    </div>
  );
}
