import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  message,
  Spin,
  Row,
  Col,
  Typography,
  Divider,
  Space,
  Tag,
  Descriptions,
  Timeline,
} from 'antd';
import {
  CheckCircleOutlined,
  ClockCircleOutlined,
  CloseCircleOutlined,
  DollarOutlined,
  BankOutlined,
  AlipayOutlined,
  WechatOutlined,
} from '@ant-design/icons';

const { Option } = Select;
const { Title, Text, Paragraph } = Typography;
const { RangePicker } = DatePicker;

// 模拟退款数据
const mockRefunds = [
  {
    id: 'REF-20260318-001',
    orderId: 'ORD-20260318-001',
    returnId: 'RET-123456',
    customerName: '张三',
    productName: 'Apple iPhone 15 Pro',
    refundAmount: 9999,
    paymentMethod: 'ALIPAY',
    status: 'PENDING',
    createdAt: '2026-03-18T10:00:00Z',
    updatedAt: '2026-03-18T10:00:00Z',
    timeline: [
      {
        time: '2026-03-18 10:00',
        status: 'PENDING',
        description: '退款申请提交成功',
      },
    ],
  },
  {
    id: 'REF-20260318-002',
    orderId: 'ORD-20260318-002',
    returnId: 'RET-123457',
    customerName: '李四',
    productName: 'MacBook Pro 14',
    refundAmount: 14999,
    paymentMethod: 'WECHAT',
    status: 'PROCESSING',
    createdAt: '2026-03-17T15:30:00Z',
    updatedAt: '2026-03-18T09:00:00Z',
    timeline: [
      {
        time: '2026-03-17 15:30',
        status: 'PENDING',
        description: '退款申请提交成功',
      },
      {
        time: '2026-03-18 09:00',
        status: 'PROCESSING',
        description: '退款处理中',
      },
    ],
  },
  {
    id: 'REF-20260318-003',
    orderId: 'ORD-20260318-003',
    returnId: 'RET-123458',
    customerName: '王五',
    productName: 'AirPods Pro 2',
    refundAmount: 1899,
    paymentMethod: 'BANK',
    status: 'COMPLETED',
    createdAt: '2026-03-16T14:00:00Z',
    updatedAt: '2026-03-17T10:00:00Z',
    timeline: [
      {
        time: '2026-03-16 14:00',
        status: 'PENDING',
        description: '退款申请提交成功',
      },
      {
        time: '2026-03-16 16:00',
        status: 'PROCESSING',
        description: '退款处理中',
      },
      {
        time: '2026-03-17 10:00',
        status: 'COMPLETED',
        description: '退款成功',
      },
    ],
  },
];

// 退款状态选项
const refundStatuses = [
  { value: 'PENDING', label: '待处理' },
  { value: 'PROCESSING', label: '处理中' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'REJECTED', label: '已拒绝' },
];

// 支付方式选项
const paymentMethods = [
  { value: 'ALIPAY', label: '支付宝', icon: <AlipayOutlined /> },
  { value: 'WECHAT', label: '微信支付', icon: <WechatOutlined /> },
  { value: 'BANK', label: '银行卡', icon: <BankOutlined /> },
];

const RefundProcess: React.FC = () => {
  const [refunds, setRefunds] = useState(mockRefunds);
  const [selectedRefund, setSelectedRefund] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [form] = Form.useForm();

  // 处理退款详情查看
  const handleRefundView = (refund: any) => {
    setSelectedRefund(refund);
    setIsModalVisible(true);
  };

  // 处理退款状态更新
  const handleStatusUpdate = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const updatedRefunds = refunds.map(refund => {
        if (refund.id === selectedRefund.id) {
          const updatedRefund = {
            ...refund,
            status: values.status,
            updatedAt: new Date().toISOString(),
            timeline: [
              ...refund.timeline,
              {
                time: new Date().toLocaleString(),
                status: values.status,
                description: getStatusDescription(values.status),
              },
            ],
          };
          return updatedRefund;
        }
        return refund;
      });
      
      setRefunds(updatedRefunds);
      setSelectedRefund(updatedRefunds.find(r => r.id === selectedRefund.id));
      message.success('退款状态更新成功');
    } catch (error) {
      message.error('退款状态更新失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 获取状态描述
  const getStatusDescription = (status: string) => {
    switch (status) {
      case 'PENDING':
        return '退款申请提交成功';
      case 'PROCESSING':
        return '退款处理中';
      case 'COMPLETED':
        return '退款成功';
      case 'REJECTED':
        return '退款被拒绝';
      default:
        return status;
    }
  };

  // 退款状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="processing"><ClockCircleOutlined /> 待处理</Tag>;
      case 'PROCESSING':
        return <Tag color="processing"><ClockCircleOutlined /> 处理中</Tag>;
      case 'COMPLETED':
        return <Tag color="success"><CheckCircleOutlined /> 已完成</Tag>;
      case 'REJECTED':
        return <Tag color="error"><CloseCircleOutlined /> 已拒绝</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  // 支付方式标签
  const getPaymentTag = (paymentMethod: string) => {
    const method = paymentMethods.find(m => m.value === paymentMethod);
    return method ? (
      <Tag icon={method.icon}>{method.label}</Tag>
    ) : (
      <Tag>{paymentMethod}</Tag>
    );
  };

  // 退款表格列
  const refundColumns = [
    {
      title: '退款ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmount',
      key: 'refundAmount',
      render: (amount: number) => `¥${amount}`,
    },
    {
      title: '支付方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      render: (method: string) => getPaymentTag(method),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button type="primary" onClick={() => handleRefundView(record)}>
          查看详情
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4} style={{ margin: 0 }}>退款流程管理</Title>
            <Text type="secondary">售后逆向流程第二步</Text>
          </div>
        }
        extra={
          <Button type="primary" ghost>
            导出退款记录
          </Button>
        }
      >
        <Divider orientation="left">退款记录</Divider>
        <Table
          columns={refundColumns}
          dataSource={refunds}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 退款详情模态框 */}
      {selectedRefund && (
        <Modal
          title="退款详情"
          open={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={null}
          width={900}
        >
          <Descriptions bordered column={2}>
            <Descriptions.Item label="退款ID">{selectedRefund.id}</Descriptions.Item>
            <Descriptions.Item label="订单ID">{selectedRefund.orderId}</Descriptions.Item>
            <Descriptions.Item label="退货申请ID">{selectedRefund.returnId}</Descriptions.Item>
            <Descriptions.Item label="客户姓名">{selectedRefund.customerName}</Descriptions.Item>
            <Descriptions.Item label="商品名称">{selectedRefund.productName}</Descriptions.Item>
            <Descriptions.Item label="退款金额">¥{selectedRefund.refundAmount}</Descriptions.Item>
            <Descriptions.Item label="支付方式">{getPaymentTag(selectedRefund.paymentMethod)}</Descriptions.Item>
            <Descriptions.Item label="当前状态">{getStatusTag(selectedRefund.status)}</Descriptions.Item>
            <Descriptions.Item label="申请时间" span={2}>
              {new Date(selectedRefund.createdAt).toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="更新时间" span={2}>
              {new Date(selectedRefund.updatedAt).toLocaleString()}
            </Descriptions.Item>
          </Descriptions>

          <Divider orientation="left">处理流程</Divider>
          <Timeline>
            {selectedRefund.timeline.map((item: any, index: number) => (
              <Timeline.Item
                key={index}
                color={
                  item.status === 'COMPLETED' ? 'green' :
                  item.status === 'REJECTED' ? 'red' :
                  'blue'
                }
              >
                <div>
                  <Text strong>{item.time}</Text>
                  <p>{item.description}</p>
                </div>
              </Timeline.Item>
            ))}
          </Timeline>

          <Divider orientation="left">状态更新</Divider>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleStatusUpdate}
            initialValues={{ status: selectedRefund.status }}
          >
            <Form.Item
              name="status"
              label="退款状态"
              rules={[{ required: true, message: '请选择退款状态' }]}
            >
              <Select placeholder="请选择退款状态">
                {refundStatuses.map(status => (
                  <Option key={status.value} value={status.value}>
                    {status.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              name="remark"
              label="处理备注"
            >
              <Input.TextArea rows={3} placeholder="请输入处理备注" />
            </Form.Item>

            <Form.Item>
              <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
                <Button onClick={() => setIsModalVisible(false)}>
                  关闭
                </Button>
                <Button type="primary" htmlType="submit" loading={isLoading}>
                  更新状态
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      )}
    </div>
  );
};

export default RefundProcess;