import { useEffect, useState, useCallback, useMemo } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Popconfirm,
  Tag,
  message,
} from 'antd';
import { PlusOutlined, DeleteOutlined, EditOutlined } from '@ant-design/icons';
import {
  articleTagApi,
  type ArticleTagItem,
  type CreateTagReq,
} from '../../api/health/articles';
import { handleApiError } from '../../api/client';
import { useThemeMode } from '../../hooks/useThemeMode';
import { AuthButton } from '../../components/AuthButton';

export default function ArticleTagManage() {
  const [tags, setTags] = useState<ArticleTagItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<ArticleTagItem | null>(null);
  const [form] = Form.useForm();
  const isDark = useThemeMode();

  const fetchTags = useCallback(async () => {
    setLoading(true);
    try {
      const result = await articleTagApi.list();
      setTags(result);
    } catch {
      message.error('加载标签列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchTags();
  }, [fetchTags]);

  const openCreateModal = () => {
    setEditing(null);
    form.resetFields();
    setModalOpen(true);
  };

  const openEditModal = (record: ArticleTagItem) => {
    setEditing(record);
    form.setFieldsValue({ name: record.name });
    setModalOpen(true);
  };

  const closeModal = () => {
    setModalOpen(false);
    setEditing(null);
    form.resetFields();
  };

  const handleSubmit = async (values: { name: string; slug?: string; color?: string }) => {
    try {
      if (editing) {
        await articleTagApi.update(editing.id, { name: values.name, version: editing.version ?? 0 });
        message.success('标签更新成功');
      } else {
        const req: CreateTagReq = {
          name: values.name,
          slug: values.slug,
          color: values.color,
        };
        await articleTagApi.create(req);
        message.success('标签创建成功');
      }
      closeModal();
      fetchTags();
    } catch (err: unknown) {
      handleApiError(err, editing ? '更新失败' : '创建失败');
    }
  };

  const handleDelete = async (record: ArticleTagItem) => {
    try {
      await articleTagApi.delete(record.id, record.version ?? 0);
      message.success('标签已删除');
      fetchTags();
    } catch {
      message.error('删除失败');
    }
  };

  const columns = useMemo(() => [
    {
      title: '标签名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string, record: ArticleTagItem) => (
        <Tag
          color={record.color || undefined}
          style={{
            fontSize: 13,
            padding: '2px 10px',
            ...(record.color ? {} : {
              background: isDark ? '#0f172a' : '#f0f9ff',
              border: `1px solid ${isDark ? '#1e3a5f' : '#bae6fd'}`,
              color: isDark ? '#7dd3fc' : '#0369a1',
            }),
          }}
        >
          {name}
        </Tag>
      ),
    },
    {
      title: '别名 (Slug)',
      dataIndex: 'slug',
      key: 'slug',
      width: 180,
      render: (v?: string) => v || <span style={{ color: isDark ? '#475569' : '#cbd5e1' }}>-</span>,
    },
    {
      title: '颜色',
      dataIndex: 'color',
      key: 'color',
      width: 100,
      render: (v?: string) =>
        v ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <div
              style={{
                width: 16,
                height: 16,
                borderRadius: 4,
                background: v,
                border: '1px solid rgba(0,0,0,0.1)',
              }}
            />
            <span style={{ fontSize: 12, fontFamily: 'monospace' }}>{v}</span>
          </div>
        ) : (
          <span style={{ color: isDark ? '#475569' : '#cbd5e1' }}>默认</span>
        ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 80,
      render: (_: unknown, record: ArticleTagItem) => (
        <AuthButton code="health.articles.manage">
          <div style={{ display: 'flex', gap: 4 }}>
            <Button size="small" type="text" icon={<EditOutlined />} onClick={() => openEditModal(record)} />
            <Popconfirm
              title="确定删除此标签？"
              description="删除后关联的文章将移除该标签"
              onConfirm={() => handleDelete(record)}
            >
              <Button size="small" type="text" icon={<DeleteOutlined />} danger />
            </Popconfirm>
          </div>
        </AuthButton>
      ),
    },
  ], [isDark, openEditModal, handleDelete]);

  return (
    <div>
      {/* 页面标题和工具栏 */}
      <div className="erp-page-header">
        <div>
          <h4>标签管理</h4>
          <div className="erp-page-subtitle">管理文章标签，用于文章分类和筛选</div>
        </div>
        <AuthButton code="health.articles.manage">
          <Button type="primary" icon={<PlusOutlined />} onClick={openCreateModal}>
            新建标签
          </Button>
        </AuthButton>
      </div>

      {/* 表格容器 */}
      <div
        style={{
          background: isDark ? '#111827' : '#FFFFFF',
          borderRadius: 12,
          border: `1px solid ${isDark ? '#0f172a' : '#f8fafc'}`,
          overflow: 'hidden',
        }}
      >
        <Table
          columns={columns}
          dataSource={tags}
          rowKey="id"
          loading={loading}
          pagination={false}
        />
      </div>

      {/* 新建/编辑标签弹窗 */}
      <Modal
        title={editing ? '编辑标签' : '新建标签'}
        open={modalOpen}
        onCancel={closeModal}
        onOk={() => form.submit()}
        width={440}
      >
        <Form
          form={form}
          onFinish={handleSubmit}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Form.Item
            name="name"
            label="标签名称"
            rules={[{ required: true, message: '请输入标签名称' }]}
          >
            <Input placeholder="请输入标签名称" maxLength={30} />
          </Form.Item>
          <Form.Item name="slug" label="别名 (Slug)">
            <Input placeholder="例如: diabetes（留空则自动生成）" />
          </Form.Item>
          <Form.Item name="color" label="颜色">
            <Input
              type="color"
              style={{ width: 60, height: 36, padding: 2, cursor: 'pointer' }}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
