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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../ui/table';
import { MessageLog as MessageLogType } from '../../types/message';
import { Search, Download, Mail, MessageSquare, Smartphone, Bell, CheckCircle, XCircle, Clock } from 'lucide-react';
import { toast } from 'sonner@2.0.3';

export function MessageLog() {
  const [logs, setLogs] = useState<MessageLogType[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');

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

  const loadLogs = () => {
    const data = localStorage.getItem('smart_agriculture_message_logs');
    if (data) {
      setLogs(JSON.parse(data));
    } else {
      const mockLogs: MessageLogType[] = [
        {
          id: 'msg-1',
          templateId: 'tpl-1',
          templateName: '任务分配通知',
          type: 'internal',
          recipient: 'user-2',
          recipientName: '张三',
          subject: '新任务分配',
          content: '您好，张三！您有新的作业任务：小麦播种作业，计划执行时间：2024-10-15 08:00。请及时查看并准备。',
          status: 'sent',
          sentTime: '2024-10-14T09:30:00',
          readTime: '2024-10-14T10:15:00',
          retryCount: 0,
          variables: {
            username: '张三',
            taskName: '小麦播种作业',
            executeTime: '2024-10-15 08:00',
          },
        },
        {
          id: 'msg-2',
          templateId: 'tpl-2',
          templateName: '设备预警通知',
          type: 'sms',
          recipient: '13800138000',
          recipientName: '李四',
          content: '【智慧农业】设备预警：约翰迪尔拖拉机检测到异常，发动机温度过高，请及时处理。',
          status: 'sent',
          sentTime: '2024-10-14T11:20:00',
          retryCount: 0,
        },
        {
          id: 'msg-3',
          templateId: 'tpl-3',
          templateName: '保养提醒',
          type: 'email',
          recipient: 'wangwu@example.com',
          recipientName: '王五',
          subject: '设备保养提醒',
          content: '尊敬的用户：\n\n您的设备约翰迪尔拖拉机（编号：JD-001）已使用500小时，建议进行保养维护...',
          status: 'sent',
          sentTime: '2024-10-14T14:00:00',
          retryCount: 0,
        },
        {
          id: 'msg-4',
          templateId: 'tpl-4',
          templateName: '任务完成通知',
          type: 'push',
          recipient: 'user-2',
          recipientName: '张三',
          subject: '任务完成',
          content: '作业任务小麦播种作业已完成，作业面积：50亩，耗时：3小时。',
          status: 'read',
          sentTime: '2024-10-14T15:30:00',
          readTime: '2024-10-14T15:32:00',
          retryCount: 0,
        },
        {
          id: 'msg-5',
          type: 'sms',
          recipient: '13900139000',
          recipientName: '赵六',
          content: '【智慧农业】验证码：123456，有效期5分钟。',
          status: 'failed',
          sentTime: '2024-10-14T16:00:00',
          failReason: '手机号码格式错误',
          retryCount: 2,
        },
      ];
      localStorage.setItem('smart_agriculture_message_logs', JSON.stringify(mockLogs));
      setLogs(mockLogs);
    }
  };

  const filteredLogs = logs.filter(log => {
    const matchKeyword = !searchKeyword ||
      (log.recipientName && log.recipientName.includes(searchKeyword)) ||
      log.recipient.includes(searchKeyword) ||
      log.content.includes(searchKeyword);
    const matchType = typeFilter === 'all' || log.type === typeFilter;
    const matchStatus = statusFilter === 'all' || log.status === statusFilter;
    return matchKeyword && matchType && matchStatus;
  });

  const handleExport = () => {
    const dataStr = JSON.stringify(filteredLogs, 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_logs_${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';
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'sent':
        return { icon: <CheckCircle className="w-3 h-3" />, label: '已发送', className: 'bg-green-100 text-green-700' };
      case 'read':
        return { icon: <CheckCircle className="w-3 h-3" />, label: '已读', className: 'bg-blue-100 text-blue-700' };
      case 'failed':
        return { icon: <XCircle className="w-3 h-3" />, label: '失败', className: 'bg-red-100 text-red-700' };
      case 'pending':
        return { icon: <Clock className="w-3 h-3" />, label: '待发送', className: 'bg-yellow-100 text-yellow-700' };
      default:
        return { icon: <Clock className="w-3 h-3" />, label: status, className: 'bg-gray-100 text-gray-700' };
    }
  };

  const stats = [
    {
      label: '总消息数',
      value: logs.length,
      color: 'text-blue-600',
    },
    {
      label: '已发送',
      value: logs.filter(l => l.status === 'sent' || l.status === 'read').length,
      color: 'text-green-600',
    },
    {
      label: '已读',
      value: logs.filter(l => l.status === 'read').length,
      color: 'text-purple-600',
    },
    {
      label: '发送失败',
      value: logs.filter(l => l.status === 'failed').length,
      color: 'text-red-600',
    },
  ];

  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>
        <Button onClick={handleExport}>
          <Download className="w-4 h-4 mr-2" />
          导出日志
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        {stats.map((stat, index) => (
          <Card key={index} className="p-4">
            <div className="text-sm text-muted-foreground">{stat.label}</div>
            <div className={`mt-2 ${stat.color}`}>{stat.value}</div>
          </Card>
        ))}
      </div>

      {/* 搜索和筛选 */}
      <Card className="p-4">
        <div className="grid grid-cols-1 md:grid-cols-3 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>
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger>
              <SelectValue placeholder="发送状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="sent">已发送</SelectItem>
              <SelectItem value="read">已读</SelectItem>
              <SelectItem value="failed">失败</SelectItem>
              <SelectItem value="pending">待发送</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </Card>

      {/* 日志列表 */}
      <Card>
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>发送时间</TableHead>
              <TableHead>类型</TableHead>
              <TableHead>接收人</TableHead>
              <TableHead>主题/内容</TableHead>
              <TableHead>状态</TableHead>
              <TableHead>重试次数</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredLogs.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                  暂无消息日志
                </TableCell>
              </TableRow>
            ) : (
              filteredLogs.map((log) => {
                const statusBadge = getStatusBadge(log.status);
                return (
                  <TableRow key={log.id}>
                    <TableCell className="text-sm text-muted-foreground">
                      {new Date(log.sentTime).toLocaleString('zh-CN')}
                    </TableCell>
                    <TableCell>
                      <Badge className={getTypeBadge(log.type)}>
                        <span className="flex items-center gap-1">
                          {getTypeIcon(log.type)}
                          {getTypeLabel(log.type)}
                        </span>
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <div>
                        <div>{log.recipientName || '-'}</div>
                        <div className="text-xs text-muted-foreground">{log.recipient}</div>
                      </div>
                    </TableCell>
                    <TableCell className="max-w-xs">
                      {log.subject && (
                        <div className="mb-1">{log.subject}</div>
                      )}
                      <div className="text-sm text-muted-foreground truncate">
                        {log.content}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <Badge className={statusBadge.className}>
                          <span className="flex items-center gap-1">
                            {statusBadge.icon}
                            {statusBadge.label}
                          </span>
                        </Badge>
                        {log.status === 'read' && log.readTime && (
                          <p className="text-xs text-muted-foreground mt-1">
                            {new Date(log.readTime).toLocaleString('zh-CN')}
                          </p>
                        )}
                        {log.status === 'failed' && log.failReason && (
                          <p className="text-xs text-red-600 mt-1">{log.failReason}</p>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{log.retryCount}</Badge>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </Card>

      {/* 使用说明 */}
      <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>
  );
}
