import { useEffect, useState, useCallback } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Tag, Card } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { listTemplates, createTemplate, type MessageTemplateInfo } from '../../api/messageTemplates';
import { AuthButton } from '../../components/AuthButton';

const channelMap: Record<string, { label: string; color: string }> = {
  in_app: { label: '站内', color: '#2563eb' },
  email: { label: '邮件', color: '#059669' },
  sms: { label: '短信', color: '#d97706' },
  wechat: { label: '微信', color: '#7C3AED' },
};

export default function MessageTemplates() {
  const [data, setData] = useState<MessageTemplateInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [form] = Form.useForm();

  const fetchData = useCallback(async (p = page) => {
    setLoading(true);
    try {
      const result = await listTemplates(p, 20);
      setData(result.data);
      setTotal(result.total);
    } catch {
      message.error('加载模板列表失败');
    } finally {
      setLoading(false);
    }
  }, [page]);

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

  const handleCreate = async () => {
    try {
      const values = await form.validateFields();
      await createTemplate(values);
      message.success('模板创建成功');
      setModalOpen(false);
      form.resetFields();
      fetchData();
    } catch {
      message.error('创建失败');
    }
  };

  const columns: ColumnsType<MessageTemplateInfo> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (v: string) => <span style={{ fontWeight: 500 }}>{v}</span>,
    },
    {
      title: '编码',
      dataIndex: 'code',
      key: 'code',
      render: (v: string) => (
        <Tag style={{
          background: 'var(--ant-color-fill-quaternary)',
          border: 'none',
          color: 'var(--ant-color-text-secondary)',
          fontFamily: 'monospace',
          fontSize: 12,
        }}>
          {v}
        </Tag>
      ),
    },
    {
      title: '通道',
      dataIndex: 'channel',
      key: 'channel',
      width: 90,
      render: (c: string) => {
        const info = channelMap[c] || { label: c, color: '#475569' };
        return (
          <Tag style={{
            background: info.color + '15',
            border: 'none',
            color: info.color,
            fontWeight: 500,
          }}>
            {info.label}
          </Tag>
        );
      },
    },
    {
      title: '标题模板',
      dataIndex: 'title_template',
      key: 'title_template',
      ellipsis: true,
    },
    {
      title: '语言',
      dataIndex: 'language',
      key: 'language',
      width: 80,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (v: string) => (
        <span style={{ color: 'var(--ant-color-text-secondary)', fontSize: 13 }}>{v}</span>
      ),
    },
  ];

  return (
    <div>
      <div style={{
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        marginBottom: 16,
      }}>
        <span style={{ fontSize: 13, color: 'var(--ant-color-text-secondary)' }}>
          共 {total} 个模板
        </span>
        <AuthButton code="message.manage">
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setModalOpen(true)}>
            新建模板
          </Button>
        </AuthButton>
      </div>

      <Card styles={{ body: { padding: 0 } }}>
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={{
            current: page,
            total,
            pageSize: 20,
            onChange: (p) => { setPage(p); fetchData(p); },
            showTotal: (t) => `共 ${t} 条记录`,
          }}
        />
      </Card>

      <Modal
        title="新建消息模板"
        open={modalOpen}
        onOk={handleCreate}
        onCancel={() => { setModalOpen(false); form.resetFields(); }}
        width={520}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 16 }}>
          <Form.Item name="name" label="名称" rules={[{ required: true, message: '请输入名称' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="code" label="编码" rules={[{ required: true, message: '请输入编码' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="channel" label="通道" initialValue="in_app">
            <Select options={[
              { value: 'in_app', label: '站内' },
              { value: 'email', label: '邮件' },
              { value: 'sms', label: '短信' },
              { value: 'wechat', label: '微信' },
            ]} />
          </Form.Item>
          <Form.Item name="title_template" label="标题模板" rules={[{ required: true, message: '请输入标题模板' }]}>
            <Input placeholder="支持 {{variable}} 变量插值" />
          </Form.Item>
          <Form.Item name="body_template" label="内容模板" rules={[{ required: true, message: '请输入内容模板' }]}>
            <Input.TextArea rows={4} placeholder="支持 {{variable}} 变量插值" />
          </Form.Item>
          <Form.Item name="language" label="语言" initialValue="zh-CN">
            <Select options={[
              { value: 'zh-CN', label: '中文' },
              { value: 'en-US', label: '英文' },
            ]} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
