import {
  deleteHealthPromotion,
  getHealthPromotionPage,
} from './service';
import { history, useAccess } from '@umijs/max';
import { Button, Form, Image, Input, Modal, Pagination, Select, Space, Table, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import './style.less';

type SearchValues = {
  keyword?: string;
  status?: number;
};

type PromotionItem = {
  id: number;
  title: string;
  coverImg?: string;
  clickCount?: number;
  sort?: number;
  contentType: number;
  status: number;
  createdAt: string;
};

const contentTypeOptions = [
  { label: '图文', value: 1 },
  { label: '视频', value: 2 },
];

const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 },
];

// 养生科普只有视频内容，固定 contentType=2
const trimSearchValues = (values: SearchValues) => ({
  keyword: values.keyword?.trim() || undefined,
  contentType: 2,
  status: values.status,
});

const contentTypeText = (value?: number) =>
  contentTypeOptions.find((item) => item.value === value)?.label || '-';

const statusText = (value?: number) => (value === 1 ? '启用' : '禁用');

const HealthPromotionPage: React.FC = () => {
  const access = useAccess();
  const [searchForm] = Form.useForm<SearchValues>();
  const [list, setList] = useState<PromotionItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ page: 1, pageSize: 10, total: 0 });

  const canView = access['live:health-promotion:view'];
  const canAdd = access['live:health-promotion:add'];
  const canEdit = access['live:health-promotion:edit'];
  const canDelete = access['live:health-promotion:delete'];
  const refreshKey = history.location.search;

  const loadList = async (page = pagination.page, pageSize = pagination.pageSize) => {
    setLoading(true);
    try {
      const res = await getHealthPromotionPage({
        page,
        pageSize,
        ...trimSearchValues(searchForm.getFieldsValue()),
      });
      setList(res.data.list || []);
      setPagination({
        page: Number(res.data.page || page),
        pageSize: Number(res.data.pageSize || pageSize),
        total: Number(res.data.total || 0),
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!canView) {
      history.replace('/Welcome');
      return;
    }
    loadList(1, 10);
  }, [canView, refreshKey]);

  const handleDelete = (record: PromotionItem) => {
    Modal.confirm({
      title: '确定要删除该养生科普吗？',
      okText: '删除',
      cancelText: '取消',
      onOk: async () => {
        await deleteHealthPromotion(record.id);
        message.success('删除成功');
        const nextPage = list.length === 1 && pagination.page > 1 ? pagination.page - 1 : pagination.page;
        await loadList(nextPage, pagination.pageSize);
      },
    });
  };

  const columns: ColumnsType<PromotionItem> = [
    {
      title: '序号',
      width: 72,
      render: (_, __, index) => (pagination.page - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 320,
      render: (_, record) => (
        <div className="health-promotion-table__title">
          {record.coverImg ? (
            <Image src={record.coverImg} width={64} height={40} preview={false} />
          ) : (
            <div className="health-promotion-table__cover-placeholder">
              {record.title?.slice(0, 2) || '-'}
            </div>
          )}
          <span>{record.title || '-'}</span>
        </div>
      ),
    },
    {
      title: '点击量',
      dataIndex: 'clickCount',
      width: 120,
      render: (value) => value || 0,
    },
    {
      title: '排序',
      dataIndex: 'sort',
      width: 100,
      render: (value) => value ?? 0,
    },
    {
      title: '类型',
      dataIndex: 'contentType',
      width: 100,
      render: (value) => contentTypeText(value),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (value) => statusText(value),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 180,
    },
    {
      title: '操作',
      width: 180,
      render: (_, record) => (
        <Space size={16} className="health-promotion-table__actions">
          {canEdit ? (
            <button
              type="button"
              onClick={() => history.push(`/live/promotion/health-promotion/${record.id}/edit`)}
            >
              编辑
            </button>
          ) : null}
          {canDelete ? (
            <button type="button" onClick={() => handleDelete(record)}>
              删除
            </button>
          ) : null}
        </Space>
      ),
    },
  ];

  return (
    <div className="health-promotion-page">
      <div className="health-promotion-page__panel">
        <div className="health-promotion-page__title">养生科普</div>
        <div className="health-promotion-search-card">
          <Form form={searchForm} layout="horizontal" className="health-promotion-search-form">
            <Form.Item label="标题" name="keyword">
              <Input placeholder="请输入" allowClear />
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select placeholder="全部" allowClear options={statusOptions} />
            </Form.Item>
            <div className="health-promotion-search-form__actions">
              <Button
                onClick={async () => {
                  searchForm.resetFields();
                  await loadList(1, pagination.pageSize);
                }}
              >
                重置
              </Button>
              <Button type="primary" onClick={() => loadList(1, pagination.pageSize)}>
                搜索
              </Button>
            </div>
          </Form>
        </div>

        <div className="health-promotion-toolbar">
          {canAdd ? (
            <Button type="primary" onClick={() => history.push('/live/promotion/health-promotion/create')}>
              添加
            </Button>
          ) : null}
        </div>

        <div className="health-promotion-table-card">
          <Table<PromotionItem>
            rowKey="id"
            columns={columns}
            dataSource={list}
            loading={loading}
            pagination={false}
            scroll={{ x: 980 }}
          />
          <div className="health-promotion-pagination">
            <Pagination
              current={pagination.page}
              pageSize={pagination.pageSize}
              total={pagination.total}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `共 ${total} 条`}
              onChange={(page, pageSize) => loadList(page, pageSize)}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default HealthPromotionPage;
