import {
  Table,
  Button,
  Space,
  Form,
  Input,
  InputNumber,
  Select,
  Popconfirm,
  Typography,
} from 'antd';
import { PlusOutlined, NumberOutlined } from '@ant-design/icons';
import {
  listNumberingRules,
  createNumberingRule,
  updateNumberingRule,
  deleteNumberingRule,
  generateNumber,
  type NumberingRuleInfo,
  type CreateNumberingRuleRequest,
  type UpdateNumberingRuleRequest,
} from '../../api/numberingRules';
import { useListData } from '../../hooks/useListData';
import { useCrudDrawer } from '../../hooks/useCrudDrawer';
import { DrawerForm } from '../../components/DrawerForm';
import { useApiRequest } from '../../hooks/useApiRequest';
import { message } from 'antd';

type NumberingRule = NumberingRuleInfo;

const RESET_CYCLE_OPTIONS = [
  { label: '不重置', value: 'never' },
  { label: '每天', value: 'daily' },
  { label: '每月', value: 'monthly' },
  { label: '每年', value: 'yearly' },
];

const RESET_CYCLE_LABELS: Record<string, string> = {
  never: '不重置',
  daily: '每天',
  monthly: '每月',
  yearly: '每年',
};

export default function NumberingRules() {
  const { data: rules, loading, refresh } = useListData<NumberingRule>(async () => {
    const result = await listNumberingRules();
    return Array.isArray(result) ? result : result.data ?? [];
  });

  const { execute } = useApiRequest();

  const drawer = useCrudDrawer<NumberingRule>({
    getId: (r) => r.id,
    onCreate: async (values) => {
      await createNumberingRule(values as unknown as CreateNumberingRuleRequest);
    },
    onUpdate: async (id, values) => {
      await updateNumberingRule(id, values as unknown as UpdateNumberingRuleRequest);
    },
    onSuccess: refresh,
  });

  const handleDelete = async (id: string, version: number) => {
    await execute(() => deleteNumberingRule(id, version), '删除成功');
    refresh();
  };

  const handleGenerate = async (rule: NumberingRule) => {
    await execute(async () => {
      const result = await generateNumber(rule.id);
      message.success(`生成编号: ${result.number}`);
    }, undefined, '生成编号失败');
  };

  const columns = [
    { title: '名称', dataIndex: 'name', key: 'name' },
    { title: '编码', dataIndex: 'code', key: 'code' },
    {
      title: '前缀',
      dataIndex: 'prefix',
      key: 'prefix',
      render: (v?: string) => v || '-',
    },
    {
      title: '日期格式',
      dataIndex: 'date_format',
      key: 'date_format',
      render: (v?: string) => v || '-',
    },
    {
      title: '序列长度',
      dataIndex: 'seq_length',
      key: 'seq_length',
      width: 90,
    },
    {
      title: '当前值',
      dataIndex: 'current_value',
      key: 'current_value',
      width: 90,
    },
    {
      title: '重置周期',
      dataIndex: 'reset_cycle',
      key: 'reset_cycle',
      width: 100,
      render: (v: string) => RESET_CYCLE_LABELS[v] ?? v,
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: unknown, record: NumberingRule) => (
        <Space>
          <Button
            size="small"
            icon={<NumberOutlined />}
            onClick={() => handleGenerate(record)}
          >
            生成编号
          </Button>
          <Button size="small" onClick={() => drawer.openEdit(record, (r) => ({
            name: r.name,
            code: r.code,
            prefix: r.prefix,
            date_format: r.date_format,
            seq_length: r.seq_length,
            seq_start: r.seq_start,
            separator: r.separator,
            reset_cycle: r.reset_cycle,
          }))}>
            编辑
          </Button>
          <Popconfirm
            title="确定删除此编号规则？"
            onConfirm={() => handleDelete(record.id, record.version)}
          >
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <Typography.Title level={5} style={{ margin: 0 }}>
          编号规则管理
        </Typography.Title>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => drawer.openCreate({
            seq_length: 4, seq_start: 1, separator: '-', reset_cycle: 'never',
          })}
        >
          新建规则
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={rules}
        rowKey="id"
        loading={loading}
        pagination={{ pageSize: 20 }}
      />

      <DrawerForm
        title={drawer.editingRecord ? '编辑编号规则' : '新建编号规则'}
        open={drawer.open}
        onClose={drawer.close}
        onSubmit={drawer.handleSubmit}
        initialValues={drawer.initialValues}
        loading={drawer.loading}
        width={520}
        columns={1}
      >
        <Form.Item name="name" label="名称" rules={[{ required: true, message: '请输入规则名称' }]}>
          <Input />
        </Form.Item>
        <Form.Item name="code" label="编码" rules={[{ required: true, message: '请输入规则编码' }]}>
          <Input disabled={!!drawer.editingRecord} />
        </Form.Item>
        <Form.Item name="prefix" label="前缀">
          <Input placeholder="如 PO、SO" />
        </Form.Item>
        <Form.Item name="date_format" label="日期格式">
          <Input placeholder="如 YYYYMMDD" />
        </Form.Item>
        <Form.Item name="separator" label="分隔符">
          <Input placeholder="默认 -" />
        </Form.Item>
        <Form.Item name="seq_length" label="序列长度" rules={[{ required: true, message: '请输入序列长度' }]}>
          <InputNumber min={1} max={20} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="seq_start" label="起始值" initialValue={1}>
          <InputNumber min={1} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="reset_cycle" label="重置周期" rules={[{ required: true, message: '请选择重置周期' }]}>
          <Select options={RESET_CYCLE_OPTIONS} />
        </Form.Item>
      </DrawerForm>
    </div>
  );
}
