import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Search, RotateCcw, Eye } from 'lucide-react';
import { Button as AntButton, Modal, Input, Select, DatePicker, Tooltip, Descriptions, Table as AntdTable, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { Button } from './ui/button';
import { toast } from 'sonner';
import dayjs, { Dayjs } from 'dayjs';
import { smsLogApi, type SmsLogVO, type SmsLogQueryParams } from '../api/notification/sms';
import { dateFormatter } from '../utils/formatTime';
import { PageResponse } from '../api/user';

interface SmsLogItem extends SmsLogVO {
  index?: number; // 序号
}

export default function SmsMessage() {
  const { t } = useTranslation();
  const [mobile, setMobile] = useState<string>('');
  const [channelId, setChannelId] = useState<number | undefined>(undefined);
  const [templateId, setTemplateId] = useState<number | undefined>(undefined);
  const [sendStatus, setSendStatus] = useState<number | undefined>(undefined);
  const [receiveStatus, setReceiveStatus] = useState<number | undefined>(undefined);
  const [startDate, setStartDate] = useState<Dayjs | null>(null);
  const [endDate, setEndDate] = useState<Dayjs | null>(null);
  const [smsLogs, setSmsLogs] = useState<SmsLogItem[]>([]);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
  const [detailSmsLog, setDetailSmsLog] = useState<SmsLogItem | null>(null);
  const pageSize = 10;
  const totalPages = Math.ceil(total / pageSize);
  const isSearchingRef = React.useRef(false);

  // 获取短信日志列表
  const fetchSmsLogs = async (searchParams?: {
    mobile?: string;
    channelId?: number;
    templateId?: number;
    sendStatus?: number;
    receiveStatus?: number;
    startDate?: Dayjs | null;
    endDate?: Dayjs | null;
    page?: number;
  }) => {
    setLoading(true);
    try {
      const params: SmsLogQueryParams = {
        pageNo: searchParams?.page !== undefined ? searchParams.page : currentPage,
        pageSize: pageSize,
      };

      if (searchParams?.mobile !== undefined ? searchParams.mobile : mobile) {
        params.mobile = searchParams?.mobile !== undefined ? searchParams.mobile : mobile;
      }
      if (searchParams?.channelId !== undefined ? searchParams.channelId : channelId) {
        params.channelId = searchParams?.channelId !== undefined ? searchParams.channelId : channelId;
      }
      if (searchParams?.templateId !== undefined ? searchParams.templateId : templateId) {
        params.templateId = searchParams?.templateId !== undefined ? searchParams.templateId : templateId;
      }
      if (searchParams?.sendStatus !== undefined ? searchParams.sendStatus : sendStatus !== undefined) {
        params.sendStatus = searchParams?.sendStatus !== undefined ? searchParams.sendStatus : sendStatus;
      }
      if (searchParams?.receiveStatus !== undefined ? searchParams.receiveStatus : receiveStatus !== undefined) {
        params.receiveStatus = searchParams?.receiveStatus !== undefined ? searchParams.receiveStatus : receiveStatus;
      }

      const start = searchParams?.startDate !== undefined ? searchParams.startDate : startDate;
      const end = searchParams?.endDate !== undefined ? searchParams.endDate : endDate;
      if (start) {
        const startStr = start.format('YYYY-MM-DD 00:00:00');
        params['createTime[0]'] = startStr;
        // 兼容：短信日志很多是按发送时间筛选
        params['sendTime[0]'] = startStr;
      }
      if (end) {
        const endStr = end.format('YYYY-MM-DD 23:59:59');
        params['createTime[1]'] = endStr;
        params['sendTime[1]'] = endStr;
      }

      const response = await smsLogApi.getSmsLogPage(params);
      const logList = (response.list || []).map((item, index) => ({
        ...item,
        index: (currentPage - 1) * pageSize + index + 1,
      }));
      setSmsLogs(logList);
      setTotal(response.total || 0);
    } catch (error: any) {
      console.error('获取短信日志列表失败:', error);
      toast.error(error?.response?.data?.message || t('notificationManagement.getSmsListFailed'));
      setSmsLogs([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和分页变化时重新获取数据
  useEffect(() => {
    if (isSearchingRef.current) {
      isSearchingRef.current = false;
      return;
    }
    fetchSmsLogs();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage]);

  // 搜索
  const handleSearch = () => {
    isSearchingRef.current = true;
    const targetPage = 1;
    setCurrentPage(targetPage);
    fetchSmsLogs({
      mobile,
      channelId,
      templateId,
      sendStatus,
      receiveStatus,
      startDate,
      endDate,
      page: targetPage,
    });
  };

  // 重置
  const handleReset = () => {
    isSearchingRef.current = true;
    setMobile('');
    setChannelId(undefined);
    setTemplateId(undefined);
    setSendStatus(undefined);
    setReceiveStatus(undefined);
    setStartDate(null);
    setEndDate(null);
    setCurrentPage(1);
    setSmsLogs([]);
    setTotal(0);
    fetchSmsLogs({
      mobile: '',
      channelId: undefined,
      templateId: undefined,
      sendStatus: undefined,
      receiveStatus: undefined,
      startDate: null,
      endDate: null,
      page: 1,
    });
  };

  // 查看详情
  const handleViewDetail = (record: SmsLogItem) => {
    setDetailSmsLog(record);
    setDetailModalVisible(true);
  };

  // 获取发送状态文本
  const getSendStatusText = (status?: number) => {
    switch (status) {
      case 10:
        return t('notificationManagement.sendSuccess');
      case 20:
        return t('notificationManagement.sendFailed');
      default:
        return t('notificationManagement.unknown');
    }
  };

  // 获取接收状态文本
  const getReceiveStatusText = (status?: number) => {
    switch (status) {
      case 0:
        return t('notificationManagement.notReceived');
      case 10:
        return t('notificationManagement.receiveSuccess');
      case 20:
        return t('notificationManagement.receiveFailed');
      default:
        return t('notificationManagement.unknown');
    }
  };

  // 定义表格列
  const columns: ColumnsType<SmsLogItem> = [
    {
      title: t('common.serialNumber'),
      dataIndex: 'index',
      key: 'index',
      width: '8%',
      render: (index: number) => <span className="text-sm text-gray-900">{index}</span>,
    },
    {
      title: t('notificationManagement.receiver'),
      dataIndex: 'nickname',
      key: 'nickname',
      width: '10%',
      render: (text: string) => <span className="text-sm text-gray-900">{text || '-'}</span>,
    },
    {
      title: t('notificationManagement.receiverMobile'),
      dataIndex: 'mobile',
      key: 'mobile',
      width: '12%',
      render: (text: string) => <span className="text-sm text-gray-900">{text || '-'}</span>,
    },
    {
      title: t('notificationManagement.smsContent'),
      dataIndex: 'templateContent',
      key: 'templateContent',
      width: '30%',
      render: (content: string) => {
        const contentText = content || '-';
        const maxLength = 30;
        const shouldTruncate = contentText.length > maxLength;
        const displayText = shouldTruncate ? contentText.slice(0, maxLength) + '...' : contentText;
        
        return (
          <Tooltip placement="topLeft" title={contentText}>
            <span className="text-sm text-gray-900">{displayText}</span>
          </Tooltip>
        );
      },
    },
    {
      title: t('notificationManagement.sendTime'),
      dataIndex: 'sendTime',
      key: 'sendTime',
      width: '15%',
      render: (sendTime: number | string | undefined) => {
        return <span className="text-sm text-gray-900">{sendTime ? dateFormatter(sendTime) : '-'}</span>;
      },
    },
    {
      title: t('notificationManagement.sendStatus'),
      dataIndex: 'sendStatus',
      key: 'sendStatus',
      width: '10%',
      render: (status: number | undefined) => {
        const statusText = getSendStatusText(status);
        return status === 10 ? (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-green-100 text-green-700">
            {statusText}
          </span>
        ) : status === 20 ? (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700">
            {statusText}
          </span>
        ) : (
          <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700">
            {statusText}
          </span>
        );
      },
    },
    {
      title: t('notificationManagement.retryCount'),
      dataIndex: 'apiSerialNo',
      key: 'apiSerialNo',
      width: '8%',
      render: (apiSerialNo: string | undefined) => {
        // 从 apiSerialNo 中提取重发次数，格式如 "664518767684851388^0"
        if (apiSerialNo && apiSerialNo.includes('^')) {
          const retryCount = apiSerialNo.split('^')[1];
          return <span className="text-sm text-gray-900">{retryCount || '0'}</span>;
        }
        return <span className="text-sm text-gray-900">0</span>;
      },
    },
    {
      title: t('common.operation'),
      key: 'action',
      width: '7%',
      align: 'center',
      render: (_: any, record: SmsLogItem) => {
        return (
          <Button 
            variant="ghost"
            size="sm"
            onClick={() => handleViewDetail(record)}
            className="h-8 px-2 transition-colors"
            style={{ color: '#000000' }}
            onMouseEnter={(e) => {
              e.currentTarget.style.color = '#1677ff';
              e.currentTarget.style.textDecoration = 'underline';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = '#000000';
              e.currentTarget.style.textDecoration = 'none';
            }}
          >
            <Eye className="w-4 h-4 mr-1" />
            <span>{t('common.detail')}</span>
          </Button>
        );
      },
    },
  ];

  return (
    <div className="space-y-6">
      {/* 操作栏和表格容器 */}
      <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
        {/* 查询与操作栏 */}
        <div className="p-4 lg:p-5 border-b border-gray-200/50">
          <div className="flex flex-wrap items-center justify-between gap-3">
            {/* 搜索条件 + 搜索、重置紧跟其后 */}
            <div className="flex flex-wrap items-center gap-3">
              {/* 接收手机号 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.receiverMobile')}：</label>
                <Input
                  placeholder={t('notificationManagement.placeholderMobile')}
                  value={mobile}
                  onChange={(e) => setMobile(e.target.value)}
                  onPressEnter={handleSearch}
                  allowClear
                  style={{ width: 200 }}
                />
              </div>

              {/* 发送状态 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.sendStatus')}：</label>
                <Select
                  value={sendStatus}
                  onChange={setSendStatus}
                  placeholder={t('common.pleaseSelect')}
                  style={{ width: 120 }}
                  allowClear
                >
                  <Select.Option value={10}>{t('notificationManagement.sendSuccess')}</Select.Option>
                  <Select.Option value={20}>{t('notificationManagement.sendFailed')}</Select.Option>
                </Select>
              </div>

              {/* 接收状态 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.receiveStatus')}：</label>
                <Select
                  value={receiveStatus}
                  onChange={setReceiveStatus}
                  placeholder={t('common.pleaseSelect')}
                  style={{ width: 120 }}
                  allowClear
                >
                  <Select.Option value={0}>{t('notificationManagement.notReceived')}</Select.Option>
                  <Select.Option value={10}>{t('notificationManagement.receiveSuccess')}</Select.Option>
                  <Select.Option value={20}>{t('notificationManagement.receiveFailed')}</Select.Option>
                </Select>
              </div>

              {/* 发送时间 */}
              <div className="flex items-center gap-2">
                <label className="text-sm text-gray-700 whitespace-nowrap">{t('notificationManagement.time')}：</label>
                <DatePicker
                  placeholder={t('common.startDate')}
                  value={startDate}
                  onChange={setStartDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
                <span className="text-gray-400">-</span>
                <DatePicker
                  placeholder={t('common.endDate')}
                  value={endDate}
                  onChange={setEndDate}
                  format="YYYY-MM-DD"
                  style={{ width: 140 }}
                />
              </div>
              <Space size="small">
                <AntButton
                  type="primary"
                  icon={<Search className="w-4 h-4" />}
                  onClick={handleSearch}
                  disabled={loading}
                >
                  {t('common.search')}
                </AntButton>
                <AntButton
                  icon={<RotateCcw className="w-4 h-4" />}
                  onClick={handleReset}
                >
                  {t('common.reset')}
                </AntButton>
              </Space>
            </div>
          </div>
        </div>

        {/* 表格容器 */}
        <div className="overflow-hidden min-w-0">
          <AntdTable
            loading={loading}
            columns={columns}
            dataSource={smsLogs}
            rowKey={(record) => record.id}
            pagination={false}
            scroll={{ x: 'max-content' }}
            locale={{
              emptyText: t('common.noData'),
            }}
          />
        </div>
      </div>

      {/* 分页 */}
      {total > 0 && (
        <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
          <div className="flex items-center justify-between">
            <div className="text-sm text-gray-600">
              {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
            </div>
            <div className="flex gap-2">
              <AntButton
                onClick={() => {
                  const newPage = Math.max(1, currentPage - 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage === 1 || loading}
              >
                {t('common.prevPage')}
              </AntButton>
              <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
                {currentPage} / {totalPages || 1}
              </span>
              <AntButton
                onClick={() => {
                  const newPage = Math.min(totalPages, currentPage + 1);
                  setCurrentPage(newPage);
                }}
                disabled={currentPage >= totalPages || loading || totalPages === 0}
              >
                {t('common.nextPage')}
              </AntButton>
            </div>
          </div>
        </div>
      )}

      {/* 短信详情弹窗 */}
      <Modal
        title={t('notificationManagement.smsDetail')}
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setDetailSmsLog(null);
        }}
        footer={[
          <AntButton key="close" onClick={() => {
            setDetailModalVisible(false);
            setDetailSmsLog(null);
          }}>
            {t('notificationManagement.close')}
          </AntButton>
        ]}
        width={800}
        style={{ top: 50 }}
        bodyStyle={{ maxHeight: '70vh', overflowY: 'auto', padding: '24px' }}
      >
        {detailSmsLog ? (
          <Descriptions 
            column={1} 
            bordered
            labelStyle={{ whiteSpace: 'nowrap', width: '120px' }}
          >
            <Descriptions.Item label={t('notificationManagement.receiver')}>
              {detailSmsLog.nickname || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.receiverMobile')}>
              {detailSmsLog.mobile || '-'}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.smsContent')}>
              <div className="text-sm text-gray-900 bg-gray-50 p-3 rounded-lg border border-gray-200 min-h-[80px] whitespace-pre-wrap">
                {detailSmsLog.templateContent || '-'}
              </div>
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.sendTime')}>
              {detailSmsLog.sendTime ? dateFormatter(detailSmsLog.sendTime) : '-'}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.receiveTime')}>
              {detailSmsLog.receiveTime ? dateFormatter(detailSmsLog.receiveTime) : '-'}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.sendStatus')}>
              {(() => {
                const statusText = getSendStatusText(detailSmsLog.sendStatus);
                return detailSmsLog.sendStatus === 10 ? (
                  <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-green-100 text-green-700 border border-green-200">
                    {statusText}
                  </span>
                ) : detailSmsLog.sendStatus === 20 ? (
                  <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700 border border-red-200">
                    {statusText}
                  </span>
                ) : (
                  <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700 border border-gray-200">
                    {statusText}
                  </span>
                );
              })()}
            </Descriptions.Item>
            <Descriptions.Item label={t('notificationManagement.receiveStatus')}>
              {(() => {
                const statusText = getReceiveStatusText(detailSmsLog.receiveStatus);
                return detailSmsLog.receiveStatus === 10 ? (
                  <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-green-100 text-green-700 border border-green-200">
                    {statusText}
                  </span>
                ) : detailSmsLog.receiveStatus === 20 ? (
                  <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-red-100 text-red-700 border border-red-200">
                    {statusText}
                  </span>
                ) : (
                  <span className="inline-flex px-3 py-1 rounded-lg text-xs bg-gray-100 text-gray-700 border border-gray-200">
                    {statusText}
                  </span>
                );
              })()}
            </Descriptions.Item>
            {detailSmsLog.apiRequestId && (
              <Descriptions.Item label={t('notificationManagement.apiRequestId')}>
                {detailSmsLog.apiRequestId}
              </Descriptions.Item>
            )}
            {detailSmsLog.apiSerialNo && (
              <Descriptions.Item label={t('notificationManagement.apiSerialNo')}>
                {detailSmsLog.apiSerialNo}
              </Descriptions.Item>
            )}
            {detailSmsLog.apiTemplateId && (
              <Descriptions.Item label={t('notificationManagement.apiTemplateId')}>
                {detailSmsLog.apiTemplateId}
              </Descriptions.Item>
            )}
            {detailSmsLog.apiSendCode && (
              <Descriptions.Item label={t('notificationManagement.apiSendCode')}>
                {detailSmsLog.apiSendCode}
              </Descriptions.Item>
            )}
            {detailSmsLog.apiSendMsg && (
              <Descriptions.Item label={t('notificationManagement.apiSendMsg')}>
                {detailSmsLog.apiSendMsg}
              </Descriptions.Item>
            )}
            {detailSmsLog.apiReceiveCode && (
              <Descriptions.Item label={t('notificationManagement.apiReceiveCode')}>
                {detailSmsLog.apiReceiveCode}
              </Descriptions.Item>
            )}
            {detailSmsLog.apiReceiveMsg && (
              <Descriptions.Item label={t('notificationManagement.apiReceiveMsg')}>
                {detailSmsLog.apiReceiveMsg}
              </Descriptions.Item>
            )}
            {detailSmsLog.channelCode && (
              <Descriptions.Item label={t('notificationManagement.channelCode')}>
                {detailSmsLog.channelCode}
              </Descriptions.Item>
            )}
            {detailSmsLog.templateCode && (
              <Descriptions.Item label={t('notificationManagement.templateCode')}>
                {detailSmsLog.templateCode}
              </Descriptions.Item>
            )}
            {detailSmsLog.templateParams && (
              <Descriptions.Item label={t('notificationManagement.templateParams')}>
                <div className="text-sm text-gray-900 bg-gray-50 p-3 rounded-lg border border-gray-200">
                  {JSON.stringify(detailSmsLog.templateParams, null, 2)}
                </div>
              </Descriptions.Item>
            )}
          </Descriptions>
        ) : null}
      </Modal>
    </div>
  );
}

