import React, { useEffect, useMemo, useState } from 'react';
import {
  Button,
  Divider,
  Form,
  Input,
  InputNumber,
  Pagination,
  Radio,
  Select,
  Space,
  Switch,
  Table,
  Tabs,
  Typography,
  message,
} from 'antd';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import styles from './Sjjy.less';

const { TextArea } = Input;

const ruleTypeOptions = [
  { label: '一致性', value: '一致性' },
  { label: '完整性', value: '完整性' },
  { label: '准确性', value: '准确性' },
  { label: '其他', value: '其他' },
];

const deviceOptions = [
  { label: 'Lucy', value: 'Lucy' },
  { label: '变压器1#', value: '变压器1#' },
  { label: '水表A', value: '水表A' },
];

const paramKeyOptions = [
  { label: '容错率', value: '容错率' },
  { label: '检查周期', value: '检查周期' },
  { label: '异常级别', value: '异常级别' },
];

const seedRules = Array.from({ length: 23 }).map((_, idx) => ({
  id: idx + 1,
  name: '电表巡检检查',
  type: '一致性',
  enabled: true,
  lastRun: '2025-10-15 14:30:00',
}));

const Sjjy = () => {
  const [activeTab, setActiveTab] = useState('rules');
  const [editing, setEditing] = useState(false);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(8);

  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [rules, setRules] = useState(() => seedRules);
  const [activeRuleId, setActiveRuleId] = useState(() => seedRules[0]?.id);
  const [form] = Form.useForm();

  const activeRule = useMemo(() => rules.find((r) => r.id === activeRuleId) || rules[0], [activeRuleId, rules]);

  const pageData = useMemo(() => {
    const start = (page - 1) * pageSize;
    return rules.slice(start, start + pageSize);
  }, [page, pageSize, rules]);

  useEffect(() => {
    if (!activeRule) return;
    form.setFieldsValue({
      ruleName: activeRule.name,
      ruleType: activeRule.type,
      device: 'Lucy',
      ruleLogic: '内容信息',
      params: [
        { key: '容错率', value: 3 },
        { key: '检查周期', value: 3 },
        { key: '异常级别', value: 3 },
      ],
      autoHandle: 'useLast',
      notify: 'system',
    });
  }, [activeRule, form]);

  const handleAdd = () => message.info('新增');
  const handleBatchToggle = () => message.info('批量启用/禁用');
  const handleTemplate = () => message.info('规则模板');

  const columns = useMemo(
    () => [
      {
        title: '规则名称',
        dataIndex: 'name',
        key: 'name',
        width: 220,
        render: (val) => <span className={styles.ruleNameCell}>{val}</span>,
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 110,
      },
      {
        title: '状态',
        dataIndex: 'enabled',
        key: 'enabled',
        width: 110,
        render: (val, record) => (
          <Switch
            checked={val}
            onChange={(checked) => {
              setRules((prev) => prev.map((r) => (r.id === record.id ? { ...r, enabled: checked } : r)));
            }}
          />
        ),
      },
      {
        title: '最后执行',
        dataIndex: 'lastRun',
        key: 'lastRun',
        width: 180,
      },
    ],
    [],
  );

  return (
    <div className={styles.container}>
      <div className={styles.leftPanel}>
        <Tabs
          className={styles.topTabs}
          activeKey={activeTab}
          onChange={setActiveTab}
          items={[
            { key: 'rules', label: '校验规则' },
            { key: 'test', label: '测试规则' },
            { key: 'template', label: '规则模板' },
          ]}
        />

        {activeTab !== 'rules' ? (
          <div className={styles.placeholder}>模块待开发</div>
        ) : (
          <>
            <div className={styles.leftToolbar}>
              <div className={styles.leftToolbarLeft}>
                <Space size={10}>
                  <Button className={styles.primaryBtn} type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    新增
                  </Button>
                  <Button className={styles.ghostBtn} onClick={handleBatchToggle}>
                    批量启用/禁用
                  </Button>
                  <Button className={styles.ghostBtn} onClick={handleTemplate}>
                    规则模板
                  </Button>
                </Space>
              </div>
              <div className={styles.leftToolbarRight}>
                <Typography.Text className={styles.counterText}>当前生效规则(条): 12</Typography.Text>
              </div>
            </div>

            <div className={styles.listWrap}>
              <Table
                rowKey="id"
                size="middle"
                columns={columns}
                dataSource={pageData}
                pagination={false}
                rowSelection={{
                  selectedRowKeys,
                  onChange: (keys) => setSelectedRowKeys(keys),
                  columnWidth: 44,
                }}
                rowClassName={(record) => (record.id === activeRuleId ? styles.rowActive : '')}
                onRow={(record) => ({
                  onClick: () => setActiveRuleId(record.id),
                })}
              />

              <div className={styles.paginationBar}>
                <Pagination
                  current={page}
                  pageSize={pageSize}
                  total={rules.length}
                  showSizeChanger={false}
                  onChange={(nextPage, nextPageSize) => {
                    setPage(nextPage);
                    if (nextPageSize && nextPageSize !== pageSize) setPageSize(nextPageSize);
                  }}
                />
              </div>
            </div>
          </>
        )}
      </div>

      <div className={styles.rightPanel}>
        <div className={styles.rightHeader}>
          <div className={styles.rightTitle}>详情</div>
          <Button
            type="link"
            icon={<EditOutlined />}
            className={styles.editBtn}
            onClick={() => setEditing((v) => !v)}
          >
            编辑
          </Button>
        </div>

        <div className={styles.detailBody}>
          <Form
            form={form}
            className={styles.detailForm}
            layout="horizontal"
            labelCol={{ flex: '92px' }}
            wrapperCol={{ flex: 'auto' }}
            colon={false}
            disabled={!editing}
          >
            <Form.Item label="规则名称" name="ruleName">
              <Input placeholder="请输入" />
            </Form.Item>

            <Form.Item label="规则类型" name="ruleType">
              <Radio.Group options={ruleTypeOptions} />
            </Form.Item>

            <Form.Item label="适用设备" name="device">
              <Select placeholder="请选择" options={deviceOptions} />
            </Form.Item>

            <Form.Item label="校验逻辑" name="ruleLogic">
              <TextArea rows={3} placeholder="请输入" />
            </Form.Item>

            <Form.Item label="参数设置">
              <Form.List name="params">
                {(fields) => (
                  <div className={styles.paramList}>
                    {fields.map((field, index) => (
                      <div key={field.key} className={styles.paramRow}>
                        <div className={styles.paramLabel}>{`参数${index + 1}`}</div>
                        <Space.Compact className={styles.paramCompact}>
                          <Form.Item name={[field.name, 'key']} noStyle>
                            <Select options={paramKeyOptions} className={styles.paramSelect} />
                          </Form.Item>
                          <Form.Item name={[field.name, 'value']} noStyle>
                            <InputNumber min={0} className={styles.paramNumber} />
                          </Form.Item>
                        </Space.Compact>
                      </div>
                    ))}
                  </div>
                )}
              </Form.List>
            </Form.Item>

            <Divider className={styles.divider} />
            <div className={styles.sectionTitle}>异常处理</div>

            <Form.Item label="自动处理" name="autoHandle">
              <Radio.Group
                options={[
                  { label: '使用上次有效值', value: 'useLast' },
                  { label: '重新设置', value: 'reset' },
                ]}
              />
            </Form.Item>

            <Form.Item label="报警方式" name="notify">
              <Radio.Group
                options={[
                  { label: '系统提示', value: 'system' },
                  { label: '邮件', value: 'email' },
                  { label: '短信', value: 'sms' },
                  { label: 'APP推送', value: 'app' },
                ]}
              />
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default Sjjy;
