import {
  DeleteOutlined,
  DesktopOutlined,
  HistoryOutlined,
  MobileOutlined,
  TabletOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import {
  App,
  Badge,
  Button,
  Card,
  Col,
  DatePicker,
  Empty,
  Popconfirm,
  Row,
  Select,
  Space,
  Spin,
  Table,
  Tabs,
  Tag,
  Tooltip,
  Typography,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import {
  getLoginHistory,
  getSessions,
  revokeOtherSessions,
  revokeSession,
} from '@/services/auth/api';

const { Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;

const SessionsView: React.FC = () => {
  const intl = useIntl();
  const { message, modal } = App.useApp();

  // 会话列表状态
  const [sessionsLoading, setSessionsLoading] = useState(true);
  const [sessions, setSessions] = useState<AuthAPI.SessionInfo[]>([]);
  const [sessionsPagination, setSessionsPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 登录历史状态
  const [historyLoading, setHistoryLoading] = useState(false);
  const [historyRecords, setHistoryRecords] = useState<
    AuthAPI.LoginHistoryRecord[]
  >([]);
  const [historyPagination, setHistoryPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [historyFilters, setHistoryFilters] = useState<{
    status?: 'success' | 'failed';
    dateRange?: [dayjs.Dayjs, dayjs.Dayjs];
  }>({});

  // 加载会话列表
  const loadSessions = async (page = 1, pageSize = 10) => {
    setSessionsLoading(true);
    try {
      const response = await getSessions({ page, pageSize, active: true });
      if (response.success && response.data) {
        setSessions(response.data.sessions || []);
        setSessionsPagination({
          current: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total,
        });
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.sessions.loadFailed',
              defaultMessage: '加载失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.sessions.loadFailed',
            defaultMessage: '加载失败',
          }),
      );
    } finally {
      setSessionsLoading(false);
    }
  };

  // 加载登录历史
  const loadHistory = async (page = 1, pageSize = 10) => {
    setHistoryLoading(true);
    try {
      const params: AuthAPI.GetLoginHistoryParams = { page, pageSize };
      if (historyFilters.status) {
        params.status = historyFilters.status;
      }
      if (historyFilters.dateRange) {
        params.startDate = historyFilters.dateRange[0].format('YYYY-MM-DD');
        params.endDate = historyFilters.dateRange[1].format('YYYY-MM-DD');
      }

      const response = await getLoginHistory(params);
      if (response.success && response.data) {
        setHistoryRecords(response.data.records || []);
        setHistoryPagination({
          current: response.data.page,
          pageSize: response.data.pageSize,
          total: response.data.total,
        });
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.sessions.loadFailed',
              defaultMessage: '加载失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.sessions.loadFailed',
            defaultMessage: '加载失败',
          }),
      );
    } finally {
      setHistoryLoading(false);
    }
  };

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

  // 撤销指定会话
  const handleRevokeSession = async (id: string) => {
    try {
      const response = await revokeSession(id);
      if (response.success) {
        message.success(
          intl.formatMessage({
            id: 'pages.account.settings.sessions.revokeSuccess',
            defaultMessage: '设备已下线',
          }),
        );
        loadSessions(sessionsPagination.current, sessionsPagination.pageSize);
      } else {
        message.error(
          response.message ||
            intl.formatMessage({
              id: 'pages.account.settings.sessions.revokeFailed',
              defaultMessage: '下线失败',
            }),
        );
      }
    } catch (error: any) {
      message.error(
        error?.message ||
          intl.formatMessage({
            id: 'pages.account.settings.sessions.revokeFailed',
            defaultMessage: '下线失败',
          }),
      );
    }
  };

  // 下线所有其他设备
  const handleRevokeOthers = () => {
    modal.confirm({
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.revokeOthersConfirmTitle',
        defaultMessage: '下线所有其他设备',
      }),
      content: intl.formatMessage({
        id: 'pages.account.settings.sessions.revokeOthersConfirmContent',
        defaultMessage:
          '确定要下线除当前设备外的所有其他设备吗？此操作不可撤销。',
      }),
      okText: intl.formatMessage({
        id: 'pages.account.settings.sessions.confirm',
        defaultMessage: '确定',
      }),
      cancelText: intl.formatMessage({
        id: 'pages.account.settings.sessions.cancel',
        defaultMessage: '取消',
      }),
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          const response = await revokeOtherSessions();
          if (response.success) {
            message.success(
              intl.formatMessage(
                {
                  id: 'pages.account.settings.sessions.revokeOthersSuccess',
                  defaultMessage: '已下线 {count} 个设备',
                },
                { count: response.data?.revokedCount || 0 },
              ),
            );
            loadSessions(1, sessionsPagination.pageSize);
          } else {
            message.error(
              response.message ||
                intl.formatMessage({
                  id: 'pages.account.settings.sessions.revokeOthersFailed',
                  defaultMessage: '下线失败',
                }),
            );
          }
        } catch (error: any) {
          message.error(
            error?.message ||
              intl.formatMessage({
                id: 'pages.account.settings.sessions.revokeOthersFailed',
                defaultMessage: '下线失败',
              }),
          );
        }
      },
    });
  };

  // 获取设备图标
  const getDeviceIcon = (deviceType: string) => {
    switch (deviceType) {
      case 'desktop':
        return <DesktopOutlined />;
      case 'mobile':
        return <MobileOutlined />;
      case 'tablet':
        return <TabletOutlined />;
      default:
        return <DesktopOutlined />;
    }
  };

  // 获取设备类型文本
  const getDeviceTypeText = (deviceType: string) => {
    switch (deviceType) {
      case 'desktop':
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.device.desktop',
          defaultMessage: '桌面端',
        });
      case 'mobile':
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.device.mobile',
          defaultMessage: '移动端',
        });
      case 'tablet':
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.device.tablet',
          defaultMessage: '平板',
        });
      default:
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.device.unknown',
          defaultMessage: '未知',
        });
    }
  };

  // 获取登录方式文本
  const getLoginMethodText = (method: string) => {
    switch (method) {
      case 'password':
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.loginMethod.password',
          defaultMessage: '密码登录',
        });
      case 'google':
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.loginMethod.google',
          defaultMessage: 'Google 登录',
        });
      case 'apikey':
        return intl.formatMessage({
          id: 'pages.account.settings.sessions.loginMethod.apikey',
          defaultMessage: 'API Key',
        });
      default:
        return method;
    }
  };

  // 会话列表列定义
  const sessionColumns: ColumnsType<AuthAPI.SessionInfo> = [
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.device',
        defaultMessage: '设备',
      }),
      key: 'device',
      width: 250,
      render: (_, record) => (
        <Space>
          <span style={{ fontSize: 20 }}>
            {getDeviceIcon(record.deviceInfo.deviceType)}
          </span>
          <div>
            <div>
              <Text strong>
                {record.deviceInfo.deviceName ||
                  `${record.deviceInfo.os} - ${record.deviceInfo.browser}`}
              </Text>
              {record.isCurrent && (
                <Tag color="green" style={{ marginLeft: 8 }}>
                  {intl.formatMessage({
                    id: 'pages.account.settings.sessions.currentDevice',
                    defaultMessage: '当前设备',
                  })}
                </Tag>
              )}
            </div>
            <Text type="secondary" style={{ fontSize: 12 }}>
              {record.deviceInfo.deviceName
                ? `${record.deviceInfo.os}${record.deviceInfo.osVersion ? ` ${record.deviceInfo.osVersion}` : ''} · ${record.deviceInfo.browser}${record.deviceInfo.browserVersion ? ` ${record.deviceInfo.browserVersion}` : ''}`
                : `${getDeviceTypeText(record.deviceInfo.deviceType)}${record.deviceInfo.browserVersion ? ` v${record.deviceInfo.browserVersion}` : ''}`}
            </Text>
          </div>
        </Space>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.location',
        defaultMessage: '位置',
      }),
      key: 'location',
      width: 180,
      render: (_, record) => {
        const locationParts = [
          record.location?.city,
          record.location?.region,
          record.location?.country,
        ].filter(Boolean);
        const locationStr = locationParts.join(', ');

        return (
          <div>
            {locationStr ? (
              <>
                <div>{locationStr}</div>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {record.ipAddress}
                </Text>
              </>
            ) : (
              <div>{record.ipAddress}</div>
            )}
          </div>
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.loginMethod',
        defaultMessage: '登录方式',
      }),
      dataIndex: 'loginMethod',
      key: 'loginMethod',
      width: 120,
      render: (method: string) => <Tag>{getLoginMethodText(method)}</Tag>,
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.lastActive',
        defaultMessage: '最后活跃',
      }),
      dataIndex: 'lastActiveAt',
      key: 'lastActiveAt',
      width: 180,
      render: (text: string) => (
        <Tooltip title={dayjs(text).format('YYYY-MM-DD HH:mm:ss')}>
          {dayjs(text).fromNow()}
        </Tooltip>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.action',
        defaultMessage: '操作',
      }),
      key: 'action',
      width: 100,
      render: (_, record) =>
        record.isCurrent ? (
          <Text type="secondary">-</Text>
        ) : (
          <Popconfirm
            title={intl.formatMessage({
              id: 'pages.account.settings.sessions.revokeConfirm',
              defaultMessage: '确定要下线此设备吗？',
            })}
            onConfirm={() => handleRevokeSession(record.id)}
            okText={intl.formatMessage({
              id: 'pages.account.settings.sessions.confirm',
              defaultMessage: '确定',
            })}
            cancelText={intl.formatMessage({
              id: 'pages.account.settings.sessions.cancel',
              defaultMessage: '取消',
            })}
          >
            <Button type="link" danger size="small" icon={<DeleteOutlined />}>
              {intl.formatMessage({
                id: 'pages.account.settings.sessions.revoke',
                defaultMessage: '下线',
              })}
            </Button>
          </Popconfirm>
        ),
    },
  ];

  // 登录历史列定义
  const historyColumns: ColumnsType<AuthAPI.LoginHistoryRecord> = [
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.time',
        defaultMessage: '时间',
      }),
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 180,
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.status',
        defaultMessage: '状态',
      }),
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) =>
        status === 'success' ? (
          <Badge
            status="success"
            text={intl.formatMessage({
              id: 'pages.account.settings.sessions.status.success',
              defaultMessage: '成功',
            })}
          />
        ) : (
          <Badge
            status="error"
            text={intl.formatMessage({
              id: 'pages.account.settings.sessions.status.failed',
              defaultMessage: '失败',
            })}
          />
        ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.device',
        defaultMessage: '设备',
      }),
      key: 'device',
      width: 200,
      render: (_, record) => (
        <Space>
          {getDeviceIcon(record.deviceInfo.deviceType)}
          <span>
            {record.deviceInfo.deviceName ||
              `${record.deviceInfo.os} - ${record.deviceInfo.browser}`}
          </span>
        </Space>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.location',
        defaultMessage: '位置',
      }),
      key: 'location',
      width: 180,
      render: (_, record) => {
        const locationParts = [
          record.location?.city,
          record.location?.country,
        ].filter(Boolean);
        const locationStr = locationParts.join(', ');

        return (
          <div>
            {locationStr ? (
              <>
                <div>{locationStr}</div>
                <Text type="secondary" style={{ fontSize: 12 }}>
                  {record.ipAddress}
                </Text>
              </>
            ) : (
              <div>{record.ipAddress}</div>
            )}
          </div>
        );
      },
    },
    {
      title: intl.formatMessage({
        id: 'pages.account.settings.sessions.column.loginMethod',
        defaultMessage: '登录方式',
      }),
      dataIndex: 'loginMethod',
      key: 'loginMethod',
      width: 120,
      render: (method: string) => <Tag>{getLoginMethodText(method)}</Tag>,
    },
  ];

  // 渲染会话列表
  const renderSessionsTab = () => (
    <div>
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Col>
          <Paragraph type="secondary" style={{ margin: 0 }}>
            {intl.formatMessage({
              id: 'pages.account.settings.sessions.description',
              defaultMessage:
                '管理您当前登录的设备，可随时下线可疑设备以保护账户安全。',
            })}
          </Paragraph>
        </Col>
        <Col>
          <Button
            danger
            onClick={handleRevokeOthers}
            disabled={sessions.length <= 1}
          >
            <WarningOutlined />
            {intl.formatMessage({
              id: 'pages.account.settings.sessions.revokeOthers',
              defaultMessage: '下线所有其他设备',
            })}
          </Button>
        </Col>
      </Row>

      {sessionsLoading ? (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Spin size="large" />
        </div>
      ) : sessions.length === 0 ? (
        <Empty
          description={intl.formatMessage({
            id: 'pages.account.settings.sessions.empty',
            defaultMessage: '暂无会话',
          })}
        />
      ) : (
        <Table
          columns={sessionColumns}
          dataSource={sessions}
          rowKey="id"
          pagination={{
            ...sessionsPagination,
            showSizeChanger: true,
            showTotal: (total) =>
              intl.formatMessage(
                {
                  id: 'pages.account.settings.sessions.total',
                  defaultMessage: '共 {total} 个设备',
                },
                { total },
              ),
            onChange: (page, pageSize) => loadSessions(page, pageSize),
          }}
          scroll={{ x: 800 }}
        />
      )}
    </div>
  );

  // 渲染登录历史
  const renderHistoryTab = () => (
    <div>
      <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
        <Col>
          <Paragraph type="secondary" style={{ margin: 0 }}>
            {intl.formatMessage({
              id: 'pages.account.settings.sessions.historyDescription',
              defaultMessage: '查看您的登录历史记录，记录保留 90 天。',
            })}
          </Paragraph>
        </Col>
        <Col>
          <Space>
            <Select
              placeholder={intl.formatMessage({
                id: 'pages.account.settings.sessions.filterStatus',
                defaultMessage: '筛选状态',
              })}
              allowClear
              style={{ width: 120 }}
              value={historyFilters.status}
              onChange={(value) => {
                setHistoryFilters({ ...historyFilters, status: value });
              }}
              options={[
                {
                  label: intl.formatMessage({
                    id: 'pages.account.settings.sessions.status.success',
                    defaultMessage: '成功',
                  }),
                  value: 'success',
                },
                {
                  label: intl.formatMessage({
                    id: 'pages.account.settings.sessions.status.failed',
                    defaultMessage: '失败',
                  }),
                  value: 'failed',
                },
              ]}
            />
            <RangePicker
              value={historyFilters.dateRange}
              onChange={(dates) => {
                setHistoryFilters({
                  ...historyFilters,
                  dateRange: dates as [dayjs.Dayjs, dayjs.Dayjs],
                });
              }}
            />
            <Button
              type="primary"
              onClick={() => loadHistory(1, historyPagination.pageSize)}
            >
              {intl.formatMessage({
                id: 'pages.account.settings.sessions.search',
                defaultMessage: '查询',
              })}
            </Button>
          </Space>
        </Col>
      </Row>

      {historyLoading ? (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <Spin size="large" />
        </div>
      ) : historyRecords.length === 0 ? (
        <Empty
          description={intl.formatMessage({
            id: 'pages.account.settings.sessions.historyEmpty',
            defaultMessage: '暂无登录记录',
          })}
        />
      ) : (
        <Table
          columns={historyColumns}
          dataSource={historyRecords}
          rowKey="id"
          pagination={{
            ...historyPagination,
            showSizeChanger: true,
            showTotal: (total) =>
              intl.formatMessage(
                {
                  id: 'pages.account.settings.sessions.historyTotal',
                  defaultMessage: '共 {total} 条记录',
                },
                { total },
              ),
            onChange: (page, pageSize) => loadHistory(page, pageSize),
          }}
          scroll={{ x: 800 }}
        />
      )}
    </div>
  );

  return (
    <Card
      title={
        <Space>
          <DesktopOutlined />
          <span>
            {intl.formatMessage({
              id: 'pages.account.settings.sessions.title',
              defaultMessage: '会话管理',
            })}
          </span>
        </Space>
      }
    >
      <Tabs
        defaultActiveKey="sessions"
        items={[
          {
            key: 'sessions',
            label: (
              <Space>
                <DesktopOutlined />
                {intl.formatMessage({
                  id: 'pages.account.settings.sessions.tab.devices',
                  defaultMessage: '登录设备',
                })}
              </Space>
            ),
            children: renderSessionsTab(),
          },
          {
            key: 'history',
            label: (
              <Space>
                <HistoryOutlined />
                {intl.formatMessage({
                  id: 'pages.account.settings.sessions.tab.history',
                  defaultMessage: '登录历史',
                })}
              </Space>
            ),
            children: renderHistoryTab(),
          },
        ]}
        onChange={(key) => {
          if (key === 'history' && historyRecords.length === 0) {
            loadHistory();
          }
        }}
      />
    </Card>
  );
};

export default SessionsView;
