import React, { useMemo, useState } from 'react';
import { Button, Checkbox, DatePicker, message, Popconfirm, Select, Space, Table } from 'antd';
import {
  DeleteOutlined,
  DownloadOutlined,
  EyeOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import styles from './Cjrz.less';

const { RangePicker } = DatePicker;

const Cjrz = () => {
  const [levelAll, setLevelAll] = useState(true);
  const [levels, setLevels] = useState(['信息', '警告']);
  const [deviceType, setDeviceType] = useState('全部');
  const [meterAll, setMeterAll] = useState(true);
  const [meterTypes, setMeterTypes] = useState(['电表']);
  const [taskAll, setTaskAll] = useState(true);
  const [taskTypes, setTaskTypes] = useState(['自动']);
  const [timeRangePreset, setTimeRangePreset] = useState('本月');

  const [timeRange, setTimeRange] = useState(null);

  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });

  const levelOptions = useMemo(() => ['信息', '警告', '错误', '严重'], []);
  const meterOptions = useMemo(() => ['电表', '水表', '燃气表'], []);
  const taskOptions = useMemo(() => ['自动', '手工'], []);

  const rows = useMemo(
    () => [
      {
        id: 1,
        time: '2025-11-25 01:07:46',
        level: '信息',
        device: '变压器1#',
        opType: '自动采集',
        detail: 'xxxxxxxxxxxxxxxxxxxx',
      },
      {
        id: 2,
        time: '2025-11-29 01:15:57',
        level: '信息',
        device: 'SCADA',
        opType: '自动采集',
        detail: 'xxxxxxxxxxxxxxxxxxxx',
      },
      {
        id: 3,
        time: '2025-11-30 02:21:41',
        level: '信息',
        device: '燃气表B',
        opType: '自动采集',
        detail: 'xxxxxxxxxxxxxxxxxxxx',
      },
      {
        id: 4,
        time: '2025-12-04 20:10:27',
        level: '警告',
        device: '水表A',
        opType: '手动录入',
        detail: 'xxxxxxxxxxxxxxxxxxxx',
      },
      {
        id: 5,
        time: '2025-12-12 04:35:20',
        level: '警告',
        device: '数据校验',
        opType: '手动录入',
        detail: 'xxxxxxxxxxxxxxxxxxxx',
      },
    ],
    [],
  );

  const filteredRows = useMemo(() => {
    return rows
      .filter((r) => (levelAll ? true : levels.includes(r.level)))
      .filter((r) => (deviceType === '全部' ? true : r.device.includes(deviceType)))
      .filter((r) => (meterAll ? true : meterTypes.some((m) => r.device.includes(m))))
      .filter((r) => (taskAll ? true : taskTypes.some((t) => r.opType.includes(t))));
  }, [deviceType, levelAll, levels, meterAll, meterTypes, rows, taskAll, taskTypes]);

  const handleQuery = () => message.info('查询');
  const handleReset = () => {
    setLevelAll(true);
    setLevels(['信息', '警告']);
    setDeviceType('全部');
    setMeterAll(true);
    setMeterTypes(['电表']);
    setTaskAll(true);
    setTaskTypes(['自动']);
    setTimeRangePreset('本月');
    setTimeRange(null);
    setPagination({ current: 1, pageSize: pagination.pageSize });
    message.success('已重置');
  };

  const handleAdd = () => message.info('新增');
  const handleUpload = () => message.info('上传');
  const handleBatchDownload = () => message.info('批量下载');

  const handleView = (record) => message.info(`查看：${record.device}`);
  const handleDelete = (record) => message.success(`已删除：${record.device}`);

  const columns = useMemo(
    () => [
      {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        width: 70,
        align: 'center',
      },
      {
        title: '时间',
        dataIndex: 'time',
        key: 'time',
        sorter: (a, b) => String(a.time).localeCompare(String(b.time)),
        width: 180,
      },
      {
        title: '级别',
        dataIndex: 'level',
        key: 'level',
        width: 90,
      },
      {
        title: '设备',
        dataIndex: 'device',
        key: 'device',
        width: 160,
      },
      {
        title: '操作类型',
        dataIndex: 'opType',
        key: 'opType',
        width: 130,
        filters: [
          { text: '自动采集', value: '自动采集' },
          { text: '手动录入', value: '手动录入' },
        ],
        onFilter: (value, record) => String(record.opType).includes(String(value)),
      },
      {
        title: '详情',
        dataIndex: 'detail',
        key: 'detail',
      },
      {
        title: '操作',
        key: 'action',
        width: 110,
        align: 'center',
        render: (_, record) => (
          <Space size={12} className={styles.actionCell}>
            <Button
              type="text"
              size="small"
              className={styles.actionBtnView}
              icon={<EyeOutlined />}
              onClick={() => handleView(record)}
            />
            <Popconfirm
              title="确认删除这条记录？"
              okText="删除"
              cancelText="取消"
              onConfirm={() => handleDelete(record)}
            >
              <Button
                type="text"
                size="small"
                danger
                className={styles.actionBtnDelete}
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </Space>
        ),
      },
    ],
    [],
  );

  return (
    <div className={styles.container}>
      <div className={styles.panel}>
        <div className={styles.rowTop}>
          <div className={styles.filters}>
            <div className={styles.filterItem}>
              <div className={styles.filterLabel}>日志级别</div>
              <div className={styles.checkGroup}>
                <Checkbox checked={levelAll} onChange={(e) => setLevelAll(e.target.checked)}>
                  全部
                </Checkbox>
                <Checkbox.Group
                  options={levelOptions}
                  value={levels}
                  disabled={levelAll}
                  onChange={(next) => setLevels(next)}
                />
              </div>
            </div>

            <div className={styles.filterItem}>
              <div className={styles.filterLabel}>设备类型</div>
              <Select
                className={styles.pillSelect}
                value={deviceType}
                onChange={setDeviceType}
                options={[
                  { label: '全部', value: '全部' },
                  { label: '电表', value: '电表' },
                  { label: '水表', value: '水表' },
                  { label: '燃气表', value: '燃气表' },
                ]}
              />
            </div>

            <div className={styles.filterItem}>
              <div className={styles.filterLabel}>电表</div>
              <div className={styles.checkGroup}>
                <Checkbox checked={meterAll} onChange={(e) => setMeterAll(e.target.checked)}>
                  全部
                </Checkbox>
                <Checkbox.Group
                  options={meterOptions}
                  value={meterTypes}
                  disabled={meterAll}
                  onChange={(next) => setMeterTypes(next)}
                />
              </div>
            </div>

            <div className={styles.filterItem}>
              <div className={styles.filterLabel}>任务状态</div>
              <div className={styles.checkGroup}>
                <Checkbox checked={taskAll} onChange={(e) => setTaskAll(e.target.checked)}>
                  全部
                </Checkbox>
                <Checkbox.Group
                  options={taskOptions}
                  value={taskTypes}
                  disabled={taskAll}
                  onChange={(next) => setTaskTypes(next)}
                />
              </div>
            </div>
          </div>

          <div className={styles.topActions}>
            <Button
              type="primary"
              icon={<SearchOutlined />}
              className={styles.queryBtn}
              onClick={handleQuery}
            >
              查询
            </Button>
            <Button icon={<ReloadOutlined />} className={styles.resetBtn} onClick={handleReset}>
              重置
            </Button>
          </div>
        </div>

        <div className={styles.rowSecond}>
          <div className={styles.toolbarLeft}>
            <Button type="primary" icon={<PlusOutlined />} className={styles.primaryBtn} onClick={handleAdd}>
              新增
            </Button>
            <Button icon={<UploadOutlined />} className={styles.ghostBtn} onClick={handleUpload}>
              上传
            </Button>
            <Button icon={<DownloadOutlined />} className={styles.ghostBtn} onClick={handleBatchDownload}>
              批量下载
            </Button>
          </div>

          <div className={styles.timeRange}>
            <div className={styles.filterLabel}>时间范围</div>
            <Select
              className={styles.presetSelect}
              value={timeRangePreset}
              onChange={setTimeRangePreset}
              options={[
                { label: '本月', value: '本月' },
                { label: '本周', value: '本周' },
                { label: '今日', value: '今日' },
              ]}
            />
            <RangePicker
              className={styles.pillRange}
              value={timeRange}
              onChange={setTimeRange}
              placeholder={['开始日期', '结束日期']}
            />
          </div>
        </div>
      </div>

      <div className={styles.tableWrap}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={filteredRows}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: filteredRows.length,
            showSizeChanger: true,
            showQuickJumper: false,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (current, pageSize) => setPagination({ current, pageSize }),
          }}
        />
      </div>
    </div>
  );
};

export default Cjrz;
