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

const { Text } = Typography;

const ruleTypeLabel = {
  consistency: '一致性',
  completeness: '完整性',
  accuracy: '准确性',
  other: '其他',
};

const Zdcj = () => {
  const [activeTab, setActiveTab] = useState('rules');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRuleId, setSelectedRuleId] = useState('r-4');
  const [form] = Form.useForm();

  const ruleList = useMemo(
    () =>
      new Array(9).fill(0).map((_, idx) => {
        const id = `r-${idx + 1}`;
        return {
          id,
          name: '电表漏电增值查',
          type: 'consistency',
          enabled: idx !== 1,
          lastRun: '2025-10-15 14:30:00',
          device: 'Lucy',
          logic: '内容信息',
          params: [
            { key: '告警阈值', value: 3 },
            { key: '检查周期', value: 3 },
            { key: '异常级别', value: 3 },
          ],
          autoAction: 'lastValid',
          notify: ['system'],
        };
      }),
    [],
  );

  const currentRule = useMemo(
    () => ruleList.find((r) => r.id === selectedRuleId) || ruleList[0],
    [ruleList, selectedRuleId],
  );

  useEffect(() => {
    if (!currentRule) return;
    form.setFieldsValue({
      ruleName: currentRule.name,
      ruleType: currentRule.type,
      applyDevice: currentRule.device,
      checkLogic: currentRule.logic,
      params: currentRule.params,
      autoAction: currentRule.autoAction,
      notify: currentRule.notify,
    });
  }, [currentRule, form]);

  const columns = useMemo(
    () => [
      {
        title: '规则名称',
        dataIndex: 'name',
        key: 'name',
        ellipsis: true,
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 100,
        render: (v) => ruleTypeLabel[v] || '--',
      },
      {
        title: '状态',
        dataIndex: 'enabled',
        key: 'enabled',
        width: 90,
        align: 'center',
        render: (v) => <Switch size="small" checked={!!v} onClick={(e) => e?.stopPropagation?.()} />,
      },
      {
        title: '最后执行',
        dataIndex: 'lastRun',
        key: 'lastRun',
        width: 170,
      },
    ],
    [],
  );

  const leftContent = useMemo(() => {
    if (activeTab !== 'rules') {
      return <div className={styles.placeholder}>该功能待接入接口/页面</div>;
    }

    return (
      <>
        <div className={styles.leftToolbar}>
          <Space size={10} wrap>
            <Button type="primary" icon={<PlusOutlined />}>
              新增
            </Button>
            <Button>批量启用/禁用</Button>
            <Button>规则模板</Button>
          </Space>
          <Text type="secondary">当前生效规则/总计：12</Text>
        </div>

        <div className={styles.tableWrap}>
          <Table
            rowKey="id"
            size="middle"
            columns={columns}
            dataSource={ruleList}
            pagination={{ pageSize: 8, showSizeChanger: false }}
            rowSelection={{
              selectedRowKeys,
              onChange: (keys) => setSelectedRowKeys(keys),
              columnWidth: 44,
            }}
            rowClassName={(record) =>
              record.id === selectedRuleId ? styles.selectedRow : ''
            }
            onRow={(record) => ({
              onClick: () => setSelectedRuleId(record.id),
            })}
          />
        </div>
      </>
    );
  }, [activeTab, columns, ruleList, selectedRowKeys, selectedRuleId]);

  return (
    <div className={styles.container}>
      <div className={styles.layout}>
        <div className={styles.leftPane}>
          <Card
            className={styles.panelCard}
            bodyStyle={{ padding: 12 }}
            title={
              <Tabs
                activeKey={activeTab}
                onChange={setActiveTab}
                items={[
                  { key: 'rules', label: '校验规则' },
                  { key: 'test', label: '测试规则' },
                  { key: 'template', label: '规则模板' },
                ]}
              />
            }
          >
            {leftContent}
          </Card>
        </div>

        <div className={styles.rightPane}>
          <Card
            className={styles.panelCard}
            title={<span className={styles.panelTitle}>详情</span>}
            extra={
              <Button type="link" className={styles.editLink}>
                编辑
              </Button>
            }
            bodyStyle={{ padding: 16 }}
          >
            <Form
              form={form}
              layout="horizontal"
              labelCol={{ flex: '86px' }}
              wrapperCol={{ flex: 1 }}
              colon={false}
              className={styles.detailForm}
            >
              <Form.Item label="规则名称" name="ruleName">
                <Input placeholder="请输入" />
              </Form.Item>

              <Form.Item label="规则类型" name="ruleType">
                <Radio.Group>
                  <Radio value="consistency">一致性</Radio>
                  <Radio value="completeness">完整性</Radio>
                  <Radio value="accuracy">准确性</Radio>
                  <Radio value="other">其他</Radio>
                </Radio.Group>
              </Form.Item>

              <Form.Item label="适用设备" name="applyDevice">
                <Select
                  options={[
                    { value: 'Lucy', label: 'Lucy' },
                    { value: 'Tom', label: 'Tom' },
                    { value: 'A-01', label: 'A-01' },
                  ]}
                />
              </Form.Item>

              <Form.Item label="校验逻辑" name="checkLogic">
                <Input placeholder="内容信息" />
              </Form.Item>

              <div className={styles.sectionTitle}>参数设置</div>
              {[0, 1, 2].map((idx) => (
                <div className={styles.paramRow} key={idx}>
                  <div className={styles.paramLabel}>{`参数${idx + 1}：`}</div>
                  <div className={styles.paramControl}>
                    <Space size={10}>
                      <Form.Item name={['params', idx, 'key']} noStyle>
                        <Select
                          style={{ width: 120 }}
                          placeholder="请选择"
                          options={[
                            { value: '告警阈值', label: '告警阈值' },
                            { value: '检查周期', label: '检查周期' },
                            { value: '异常级别', label: '异常级别' },
                          ]}
                        />
                      </Form.Item>
                      <Form.Item name={['params', idx, 'value']} noStyle>
                        <InputNumber style={{ width: 72 }} min={0} />
                      </Form.Item>
                    </Space>
                  </div>
                </div>
              ))}

              <div className={styles.sectionTitle}>异常处理</div>
              <Form.Item label="自动处理" name="autoAction">
                <Radio.Group>
                  <Radio value="lastValid">使用上次有效值</Radio>
                  <Radio value="reset">重新设置</Radio>
                </Radio.Group>
              </Form.Item>

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

export default Zdcj;
