import {
  siteapicontrollerDeletereview,
  siteapicontrollerGetreviews,
} from '@/servers/api/siteApi';
import {
  ActionType,
  ProCard,
  ProColumns,
  ProTable,
} from '@ant-design/pro-components';
import { useParams } from '@umijs/max';
import { Button, message, Popconfirm, Space } from 'antd';
import React, { useRef, useState } from 'react';
import ReviewForm from './ReviewForm';

const ReviewsPage: React.FC = () => {
  const params = useParams();
  const siteId = Number(params.siteId);
  const actionRef = useRef<ActionType>();
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<any>(null);

  const columns: ProColumns<API.UnifiedReviewDTO>[] = [
    { title: 'ID', dataIndex: 'id', key: 'id', width: 50 },
    { title: '产品ID', dataIndex: 'product_id', key: 'product_id', width: 80 },
    { title: '作者', dataIndex: 'author', key: 'author' },
    { title: '评分', dataIndex: 'rating', key: 'rating', width: 80 },
    { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
    {
      title: '创建时间',
      dataIndex: 'date_created',
      key: 'date_created',
      valueType: 'dateTime',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            style={{ padding: 0 }}
            onClick={() => {
              setEditing(record);
              setOpen(true);
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定删除吗？"
            onConfirm={async () => {
              if (record.id) {
                try {
                  const response = await siteapicontrollerDeletereview({
                    siteId,
                    id: String(record.id),
                  });
                  if (response.success) {
                    message.success('删除成功');
                    actionRef.current?.reload();
                  } else {
                    message.error('删除失败');
                  }
                } catch (error) {
                  message.error('删除失败');
                }
              }
            }}
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <ProCard>
      <ProTable<API.UnifiedReviewDTO>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          try {
            const response = await siteapicontrollerGetreviews({
              ...params,
              siteId,
              page: params.current,
              per_page: params.pageSize,
            });
            // 确保 response.data 存在
            if (!response || !response.data) {
              return {
                data: [],
                success: true,
                total: 0,
              };
            }
            // 确保 response.data.items 是数组
            const items = Array.isArray(response.data.items) ? response.data.items : [];
            // 确保每个 item 有有效的 id
            const processedItems = items.map((item, index) => ({
              ...item,
              // 如果 id 是对象，转换为字符串，否则使用索引作为后备
              id: typeof item.id === 'object' ? JSON.stringify(item.id) : (item.id || index),
              // 如果 product_id 是对象，转换为字符串
              product_id: typeof item.product_id === 'object' ? JSON.stringify(item.product_id) : item.product_id,
            }));
            return {
              data: processedItems,
              success: true,
              total: Number(response.data.total) || 0,
            };
          } catch (error) {
            console.error('获取评论失败:', error);
            return {
              data: [],
              success: true,
              total: 0,
            };
          }
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        headerTitle="评论列表"
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              setEditing(null);
              setOpen(true);
            }}
          >
            新建评论
          </Button>,
        ]}
      />
      <ReviewForm
        open={open}
        editing={editing}
        siteId={siteId}
        onClose={() => setOpen(false)}
        onSuccess={() => {
          setOpen(false);
          actionRef.current?.reload();
        }}
      />
    </ProCard>
  );
};

export default ReviewsPage;
