import { useEffect, useState, useMemo, useCallback, useRef } from 'react';
import { Table, Button, Tag, Space, Modal, Typography, Popconfirm, Card, message } from 'antd';
import { CheckOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { listMessages, markRead, markAllRead, deleteMessage, type MessageInfo, type MessageQuery } from '../../api/messages';
import { AuthButton } from '../../components/AuthButton';

const { Paragraph } = Typography;

function formatDateTime(value: string): string {
  return new Date(value).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  });
}

interface Props {
  queryFilter?: MessageQuery;
}

const priorityStyles: Record<string, { bg: string; color: string; text: string }> = {
  urgent: { bg: '#FEF2F2', color: '#dc2626', text: '紧急' },
  important: { bg: '#FFFBEB', color: '#d97706', text: '重要' },
  normal: { bg: '#eff6ff', color: '#2563eb', text: '普通' },
};

export default function NotificationList({ queryFilter }: Props) {
  const [data, setData] = useState<MessageInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);

  const fetchData = useCallback(async (p = page, filter?: MessageQuery) => {
    setLoading(true);
    try {
      const result = await listMessages({ page: p, page_size: 20, ...filter });
      setData(result.data);
      setTotal(result.total);
    } catch {
      message.error('加载消息列表失败');
    } finally {
      setLoading(false);
    }
  }, [page]);

  const filterKey = useMemo(() => JSON.stringify(queryFilter), [queryFilter]);
  const isFirstRender = useRef(true);

  useEffect(() => {
    if (isFirstRender.current) {
      isFirstRender.current = false;
      fetchData(1, queryFilter);
    }
  }, [filterKey, fetchData, queryFilter]);

  const handleMarkRead = async (id: string) => {
    try {
      await markRead(id);
      fetchData(page, queryFilter);
    } catch {
      message.error('操作失败');
    }
  };

  const handleMarkAllRead = async () => {
    try {
      await markAllRead();
      fetchData(page, queryFilter);
      message.success('已全部标记为已读');
    } catch {
      message.error('操作失败');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteMessage(id);
      fetchData(page, queryFilter);
      message.success('已删除');
    } catch {
      message.error('删除失败');
    }
  };

  const showDetail = (record: MessageInfo) => {
    Modal.info({
      title: record.title,
      width: 520,
      content: (
        <div>
          <Paragraph>{record.body}</Paragraph>
          <div style={{ marginTop: 8, color: 'var(--ant-color-text-secondary)', fontSize: 12 }}>
            {formatDateTime(record.created_at)}
          </div>
        </div>
      ),
    });
    if (!record.is_read) {
      handleMarkRead(record.id);
    }
  };

  const columns: ColumnsType<MessageInfo> = [
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record) => (
        <span
          style={{
            fontWeight: record.is_read ? 400 : 600,
            cursor: 'pointer',
            color: record.is_read ? 'var(--ant-color-text-secondary)' : 'inherit',
          }}
          onClick={() => showDetail(record)}
        >
          {!record.is_read && (
            <span style={{
              display: 'inline-block',
              width: 6,
              height: 6,
              borderRadius: '50%',
              background: '#2563eb',
              marginRight: 8,
            }} />
          )}
          {text}
        </span>
      ),
    },
    {
      title: '优先级',
      dataIndex: 'priority',
      key: 'priority',
      width: 90,
      render: (p: string) => {
        const info = priorityStyles[p] || { bg: '#f8fafc', color: '#475569', text: p };
        return (
          <Tag style={{
            background: info.bg,
            border: 'none',
            color: info.color,
            fontWeight: 500,
          }}>
            {info.text}
          </Tag>
        );
      },
    },
    {
      title: '发送者',
      dataIndex: 'sender_type',
      key: 'sender_type',
      width: 80,
      render: (s: string) => <span style={{ color: 'var(--ant-color-text-secondary)' }}>{s === 'system' ? '系统' : '用户'}</span>,
    },
    {
      title: '状态',
      dataIndex: 'is_read',
      key: 'is_read',
      width: 80,
      render: (r: boolean) => (
        <Tag style={{
          background: r ? 'var(--ant-color-fill-quaternary)' : '#eff6ff',
          border: 'none',
          color: r ? 'var(--ant-color-text-secondary)' : '#2563eb',
          fontWeight: 500,
        }}>
          {r ? '已读' : '未读'}
        </Tag>
      ),
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (v: string) => (
        <span style={{ color: 'var(--ant-color-text-secondary)', fontSize: 13 }}>{formatDateTime(v)}</span>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 120,
      render: (_: unknown, record) => (
        <Space size={4}>
          {!record.is_read && (
            <Button
              type="text"
              size="small"
              icon={<CheckOutlined />}
              onClick={() => handleMarkRead(record.id)}
              style={{ color: '#2563eb' }}
            />
          )}
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => showDetail(record)}
            style={{ color: 'var(--ant-color-text-secondary)' }}
          />
          <AuthButton code="message.manage">
            <Popconfirm
              title="确定删除此消息？"
              onConfirm={() => handleDelete(record.id)}
            >
              <Button
                type="text"
                size="small"
                danger
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </AuthButton>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 16,
      }}>
        <span style={{ fontSize: 13, color: 'var(--ant-color-text-secondary)' }}>
          共 {total} 条消息
        </span>
        <AuthButton code="message.manage">
          <Button icon={<CheckOutlined />} onClick={handleMarkAllRead}>
            全部标记已读
          </Button>
        </AuthButton>
      </div>

      <Card styles={{ body: { padding: 0 } }}>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            total,
            pageSize: 20,
            onChange: (p) => { setPage(p); fetchData(p, queryFilter); },
            showTotal: (t) => `共 ${t} 条记录`,
          }}
        />
      </Card>
    </div>
  );
}
