import React, { useState, useEffect } from 'react';
import { Table, Card, Rate, Image, Tag, Space, Button, message, Modal, Input, Select } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getReviews, approveReview, rejectReview } from '@/api/review';
import dayjs from 'dayjs';

const { TextArea } = Input;
const { Option } = Select;

const statusMap: Record<string, { color: string; label: string }> = {
  pending: { color: 'orange', label: '待审核' },
  visible: { color: 'green', label: '已通过' },
  hidden: { color: 'red', label: '已隐藏' },
};

const ReviewManage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [reviews, setReviews] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [status, setStatus] = useState<string>('');
  const [rejectModal, setRejectModal] = useState<{ visible: boolean; id: number | null; reason: string }>({
    visible: false,
    id: null,
    reason: '',
  });

  const fetchReviews = async () => {
    setLoading(true);
    try {
      const res: any = await getReviews({ page, pageSize, auditStatus: status || undefined });
      setReviews(res.data?.list || []);
      setTotal(res.data?.total || 0);
    } catch (error) {
      message.error('获取评价列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchReviews();
  }, [page, pageSize, status]);

  const handleApprove = async (id: number) => {
    try {
      await approveReview(id);
      message.success('审核通过');
      fetchReviews();
    } catch (error: any) {
      message.error(error.message || '操作失败');
    }
  };

  const handleReject = async () => {
    if (!rejectModal.reason.trim()) {
      message.warning('请输入拒绝原因');
      return;
    }
    try {
      await rejectReview(rejectModal.id!, rejectModal.reason);
      message.success('已拒绝');
      setRejectModal({ visible: false, id: null, reason: '' });
      fetchReviews();
    } catch (error: any) {
      message.error(error.message || '操作失败');
    }
  };

  const columns: ColumnsType<any> = [
    {
      title: '订单号',
      dataIndex: ['order', 'orderNo'],
      width: 180,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      width: 150,
      render: (rating: number) => <Rate disabled value={rating} />,
    },
    {
      title: '评价内容',
      dataIndex: 'content',
      ellipsis: true,
      render: (content: string) => content || '-',
    },
    {
      title: '图片',
      dataIndex: 'images',
      width: 120,
      render: (images: string[]) => {
        if (!images || images.length === 0) return '-';
        return (
          <Image.PreviewGroup>
            <Space>
              {images.slice(0, 3).map((img, idx) => (
                <Image key={idx} src={img} width={40} height={40} style={{ objectFit: 'cover' }} />
              ))}
              {images.length > 3 && <span>+{images.length - 3}</span>}
            </Space>
          </Image.PreviewGroup>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status: string) => (
        <Tag color={statusMap[status]?.color}>{statusMap[status]?.label || status}</Tag>
      ),
    },
    {
      title: '评价时间',
      dataIndex: 'createdAt',
      width: 180,
      render: (date: string) => dayjs(date).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          {record.status === 'pending' && (
            <>
              <Button type="primary" size="small" onClick={() => handleApprove(record.id)}>
                通过
              </Button>
              <Button
                danger
                size="small"
                onClick={() => setRejectModal({ visible: true, id: record.id, reason: '' })}
              >
                拒绝
              </Button>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
        <h2>评价管理</h2>
        <Select
          value={status || undefined}
          placeholder="审核状态"
          style={{ width: 150 }}
          allowClear
          onChange={(v) => {
            setStatus(v || '');
            setPage(1);
          }}
        >
          {Object.entries(statusMap).map(([k, v]) => (
            <Option key={k} value={k}>
              {v.label}
            </Option>
          ))}
        </Select>
      </div>

      <Table
        columns={columns}
        dataSource={reviews}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1200 }}
        pagination={{
          current: page,
          pageSize,
          total,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
          onChange: (page, pageSize) => {
            setPage(page);
            setPageSize(pageSize);
          },
        }}
      />

      <Modal
        title="拒绝评价"
        open={rejectModal.visible}
        onOk={handleReject}
        onCancel={() => setRejectModal({ visible: false, id: null, reason: '' })}
      >
        <TextArea
          rows={3}
          placeholder="请输入拒绝原因"
          value={rejectModal.reason}
          onChange={(e) => setRejectModal({ ...rejectModal, reason: e.target.value })}
        />
      </Modal>
    </div>
  );
};

export default ReviewManage;
