import {
  PageContainer,
  type ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { Col, Row } from 'antd';
import React, { useEffect, useState } from 'react';
import useRuleMeta from '@/pages/rules/hooks/useRuleMeta';
import { getOperLogAction, getOperLogPages } from '@/services/api';
import { $t } from '@/utils/i18n';

const OperLog: React.FC = () => {
  const [actionList, setActionList] = useState([]);
  const { ruleBaseMeta } = useRuleMeta();

  useEffect(() => {
    getOperLogAction().then(({ data: { data } }) => {
      setActionList(data || []);
    });
  }, []);

  const alertActionType: Record<string, string> = {
    '2': $t('table.viewed'),
    '3': $t('table.ignored'),
  };
  const ruleActionType: Record<string, string> = {
    '1': $t('pages.rules.enable'),
    '2': $t('pages.rules.disable'),
    '4': $t('table.action.delete'),
  };

  const actionMap: Record<string, (item: API.OperLogListItem) => string> = {
    'alert record edit': (item) => {
      const matched = item.operParam.match(/status=(?<status>\d+)/);
      const status = matched?.groups?.status || '';
      return `Handle Alert Record : ${alertActionType[status] || 'unknown'}`;
    },
    login: (item) => {
      return `'${item.operName || '-'}' Login`;
    },
    'alert record excel export': () => {
      return `Export Alert Record`;
    },
    'user logout': (item) => {
      return `'${item.operName || '-'}' Logout`;
    },
    'data-source insert': (item) => {
      const operParam = parseOperParam(item);
      return `Add Data Source: '${operParam.sourceName || '-'}'`;
    },
    'rule insert': (item) => {
      const operParam = parseOperParam(item);
      return `Add Rule: '${ruleBaseMeta[operParam.type].title || '-'}'`;
    },
    'rule update': (item) => {
      const operParam = parseOperParam(item);
      return `Update Rule: '${ruleBaseMeta[operParam.type].title || '-'}'`;
    },
    'rule update status': (item) => {
      const matched = item.operParam.match(/status=(?<status>\d+)/);
      const status = matched?.groups?.status || '';
      return `Handle Rule : ${ruleActionType[status] || 'unknown'}`;
    },
  };

  function parseOperParam(item: API.OperLogListItem) {
    try {
      return JSON.parse(item.operParam || '{}');
    } catch (error) {
      console.error('parse operParam error', error);
      return {};
    }
  }

  const columns: ProColumns<API.OperLogListItem>[] = [
    {
      title: $t('table.time'),
      dataIndex: 'operTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: $t('table.operator'),
      dataIndex: 'operName',
      hideInSearch: true,
    },
    {
      title: $t('table.os'),
      dataIndex: 'os',
      hideInSearch: true,
    },
    {
      title: $t('table.browser'),
      dataIndex: 'browser',
      hideInSearch: true,
    },
    {
      title: $t('table.actionType'),
      dataIndex: 'title',
      valueType: 'select',
      fieldProps: {
        defaultValue: '',
        options: [
          {
            label: $t('table.all'),
            value: '',
          },
          ...actionList.map((item: string) => ({
            label: item?.toUpperCase() || '',
            value: item,
          })),
        ],
      },
      renderText: (_, { title }) => title?.toUpperCase() || '-',
      search: {
        transform: (value) => ({
          titles: value,
        }),
      },
    },
    {
      title: $t('table.description'),
      dataIndex: 'title',
      hideInSearch: true,
      ellipsis: true,
      width: 'auto',
      renderText: (_, item) => actionMap[item.title]?.(item) || '-',
    },
    {
      title: $t('table.ipAddress'),
      dataIndex: 'operIp',
      hideInSearch: true,
      renderText: (_, { operIp }) => operIp || '-',
    },
  ];
  return (
    <PageContainer>
      <Row gutter={[16, 16]}>
        <Col span={24}>
          <ProTable
            scroll={{ x: true }}
            columns={columns}
            size="small"
            search={{
              labelWidth: 'auto',
            }}
            request={async (params) => {
              const { data } = await getOperLogPages({
                pageNum: params.current,
                ...params,
              });
              return {
                data: data?.data?.list || [],
                success: true,
                total: data?.data?.total || 0,
              };
            }}
            rowKey="operId"
          />
        </Col>
      </Row>
    </PageContainer>
  );
};

export default OperLog;
