'use client';

import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Download, MessageSquare, RefreshCw } from 'lucide-react';
import { MessageLogStats } from './components/MessageLogStats';
import { MessageLogFilter } from './components/MessageLogFilter';
import { MessageLogTable } from './components/MessageLogTable';
import { MessageLog } from '@/types/message';
import { mockMessageLogs } from './mock/mockData';

export default function MessageLogPage() {
  const [logs, setLogs] = useState<MessageLog[]>([]);
  const [filteredLogs, setFilteredLogs] = useState<MessageLog[]>([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [loading, setLoading] = useState(false);

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

  useEffect(() => {
    applyFilters();
  }, [logs, searchKeyword, typeFilter, statusFilter]);

  const loadLogs = async () => {
    setLoading(true);
    try {
      // 模拟API延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      setLogs(mockMessageLogs);
    } catch (error) {
      console.error('Failed to load message logs:', error);
      toast.error('加载消息日志失败');
    } finally {
      setLoading(false);
    }
  };

  const applyFilters = () => {
    let filtered = logs;

    // 调试信息
    console.log('All logs:', logs);
    console.log('Filters:', { searchKeyword, typeFilter, statusFilter });

    if (searchKeyword) {
      filtered = filtered.filter(log =>
        (log.recipientName && log.recipientName.includes(searchKeyword)) ||
        log.recipient.includes(searchKeyword) ||
        log.content.includes(searchKeyword)
      );
    }

    if (typeFilter !== 'all') {
      filtered = filtered.filter(log => log.type === typeFilter);
    }

    if (statusFilter !== 'all') {
      filtered = filtered.filter(log => log.status === statusFilter);
    }

    filtered.sort((a, b) => b.sentTime.localeCompare(a.sentTime));

    setFilteredLogs(filtered);
  };

  const handleExport = async () => {
    try {
      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('导出成功');
    } catch (error) {
      console.error('Failed to export logs:', error);
      toast.error('导出失败');
    }
  };

  const handleRefresh = () => {
    loadLogs();
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-green-800 text-2xl font-bold">消息日志</h2>
          <p className="text-muted-foreground">完整记录所有通过系统发送的消息流水</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={handleRefresh} disabled={loading}>
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新
          </Button>
          <Button onClick={handleExport} disabled={loading}>
            <Download className="w-4 h-4 mr-2" />
            导出日志
          </Button>
        </div>
      </div>

      <MessageLogStats logs={filteredLogs} />

      <MessageLogFilter
        searchKeyword={searchKeyword}
        typeFilter={typeFilter}
        statusFilter={statusFilter}
        onSearchChange={setSearchKeyword}
        onTypeChange={setTypeFilter}
        onStatusChange={setStatusFilter}
      />

      <MessageLogTable logs={filteredLogs} />

      <Card className="p-4 bg-blue-50 border-blue-200">
        <h4 className="text-blue-900 mb-2 font-semibold">
          <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>
  );
}