/**
 * 操作日志页面
 *
 * - 顶部过滤：用户下拉 + 操作类型 + 时间范围
 * - 列表：分页展示操作日志
 */

import { useState, useEffect, useCallback } from 'react';
import {
  Button,
  Card,
  DatePicker,
  Message,
  Select,
  Space,
  Table,
  Typography,
} from '@arco-design/web-react';
import { IconSearch, IconRefresh } from '@arco-design/web-react/icon';
import { api } from '@/api/request';
import { fetchOperationLogs } from '@/api/user';
import type { OperationLog } from '@/api/user';

const { RangePicker } = DatePicker;

/** 操作类型选项 */
const ACTION_OPTIONS = [
  { label: '全部', value: '' },
  { label: '登录', value: 'login' },
  { label: '创建', value: 'create' },
  { label: '编辑', value: 'edit' },
  { label: '删除', value: 'delete' },
  { label: '控制设备', value: 'device:operate' },
];

/** 用户下拉选项 */
interface UserOption {
  id: number;
  name: string | null;
  phone: string;
}

export default function OperationLogsPage() {
  // 过滤条件
  const [userId, setUserId] = useState<number | undefined>();
  const [action, setAction] = useState('');
  const [timeRange, setTimeRange] = useState<string[]>([]);

  // 用户下拉数据
  const [userOptions, setUserOptions] = useState<UserOption[]>([]);

  // 列表数据
  const [data, setData] = useState<OperationLog[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [loading, setLoading] = useState(false);

  /** 加载用户下拉 */
  useEffect(() => {
    api
      .get<{ list: UserOption[] }>('/users?page_size=200')
      .then((res) => setUserOptions(res.data.list || []))
      .catch(() => {});
  }, []);

  /** 构建查询参数 */
  const buildQuery = useCallback(() => {
    const params: Record<string, string | number | undefined> = { page, page_size: pageSize };
    if (userId) params.user_id = userId;
    if (action) params.action = action;
    if (timeRange[0]) params.start_time = timeRange[0];
    if (timeRange[1]) params.end_time = timeRange[1];
    return params as Record<string, string | number>;
  }, [userId, action, timeRange, page, pageSize]);

  /** 加载列表数据 */
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetchOperationLogs(buildQuery());
      setData(res.list);
      setTotal(res.total);
    } catch {
      Message.error('加载操作日志失败');
    } finally {
      setLoading(false);
    }
  }, [buildQuery]);

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

  /** 查询 */
  const handleSearch = () => {
    setPage(1);
    fetchData();
  };

  /** 重置 */
  const handleReset = () => {
    setUserId(undefined);
    setAction('');
    setTimeRange([]);
    setPage(1);
  };

  /** 操作类型显示映射 */
  const actionLabelMap: Record<string, string> = {
    login: '登录',
    create: '创建',
    edit: '编辑',
    delete: '删除',
    'device:operate': '控制设备',
  };

  /** 表格列 */
  const columns = [
    {
      title: '用户',
      dataIndex: 'user_name',
      width: 130,
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      render: (act: string) => actionLabelMap[act] || act,
    },
    {
      title: '对象类型',
      dataIndex: 'target_type',
      width: 100,
      render: (v: string | null) => v || '-',
    },
    {
      title: '对象',
      dataIndex: 'target_id',
      width: 120,
      render: (v: number | null, record: OperationLog) => {
        if (v == null) return '-';
        const type = record.target_type;
        if (type === 'user') return `用户#${v}`;
        if (type === 'cabinet') return `柜#${v}`;
        return `#${v}`;
      },
    },
    {
      title: '详情',
      dataIndex: 'detail',
      render: (v: string | null) => v || '-',
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      width: 170,
    },
  ];

  return (
    <Card>
      <Space direction="vertical" style={{ width: '100%' }}>
        {/* 标题 */}
        <Typography.Title heading={4} style={{ margin: 0 }}>
          操作日志
        </Typography.Title>

        {/* 过滤区域 */}
        <Space wrap>
          <Select
            placeholder="选择用户"
            allowClear
            showSearch
            style={{ width: 200 }}
            value={userId}
            onChange={(v) => setUserId(v as number | undefined)}
            options={userOptions.map((u) => ({
              label: `${u.name || u.phone}`,
              value: u.id,
            }))}
            // ponytail: Arco Select filterOption 的 option 参数类型为 ReactElement，需要断言访问 label
            filterOption={(input, option) =>
              ((option as { label?: string })?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
          />
          <Select
            placeholder="操作类型"
            allowClear
            style={{ width: 140 }}
            value={action || undefined}
            onChange={(v) => setAction((v as string) || '')}
            options={ACTION_OPTIONS.filter((o) => o.value !== '')}
          />
          {/* RangePicker onChange 第一个参数即为 string[]，无需从 Dayjs[] 转换 */}
          <RangePicker
            onChange={(dateString) => {
              setTimeRange(dateString);
            }}
          />
          <Button type="primary" icon={<IconSearch />} onClick={handleSearch}>
            查询
          </Button>
          <Button icon={<IconRefresh />} onClick={handleReset}>
            重置
          </Button>
        </Space>

        {/* 表格 */}
        <Table
          rowKey="id"
          columns={columns}
          data={data}
          loading={loading}
          pagination={{
            current: page,
            total,
            pageSize,
            onChange: setPage,
            showTotal: true,
          }}
          // ponytail: Arco Table size 不支持 "medium"，使用等效的 "default"
          size="default"
        />
      </Space>
    </Card>
  );
}
