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

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

// 模拟订单数据
const mockOrders = [
  {
    id: 'ORD-20260318-001',
    customerName: '张三',
    productName: 'Apple iPhone 15 Pro',
    quantity: 1,
    price: 9999,
    orderDate: '2026-03-15',
    status: 'DELIVERED',
  },
  {
    id: 'ORD-20260318-002',
    customerName: '李四',
    productName: 'MacBook Pro 14',
    quantity: 1,
    price: 14999,
    orderDate: '2026-03-10',
    status: 'DELIVERED',
  },
  {
    id: 'ORD-20260318-003',
    customerName: '王五',
    productName: 'AirPods Pro 2',
    quantity: 2,
    price: 1899,
    orderDate: '2026-03-05',
    status: 'DELIVERED',
  },
];

// 退货原因选项
const returnReasons = [
  { value: 'QUALITY_ISSUE', label: '商品质量问题' },
  { value: 'WRONG_ITEM', label: '发错商品' },
  { value: 'DAMAGED', label: '商品损坏' },
  { value: 'NOT_AS_DESCRIBED', label: '与描述不符' },
  { value: 'CHANGE_MIND', label: '买家改变主意' },
  { value: 'OTHER', label: '其他原因' },
];

const ReturnApply: React.FC = () => {
  const [form] = Form.useForm();
  const [orders, setOrders] = useState(mockOrders);
  const [selectedOrder, setSelectedOrder] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [returnApplications, setReturnApplications] = useState<any[]>([]);

  // 处理订单选择
  const handleOrderSelect = (order: any) => {
    setSelectedOrder(order);
    form.setFieldsValue({
      orderId: order.id,
      productName: order.productName,
      quantity: order.quantity,
      purchaseAmount: order.price,
    });
    setIsModalVisible(true);
  };

  // 处理退货申请提交
  const handleSubmit = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const newApplication = {
        id: `RET-${Date.now()}`,
        orderId: values.orderId,
        productName: values.productName,
        quantity: values.quantity,
        returnReason: values.returnReason,
        description: values.description,
        refundAmount: values.refundAmount,
        status: 'PENDING',
        createdAt: new Date().toISOString(),
      };
      
      setReturnApplications([...returnApplications, newApplication]);
      message.success('退货申请提交成功');
      setIsModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('退货申请提交失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 订单状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'PENDING':
        return <Tag color="processing"><ClockCircleOutlined /> 待处理</Tag>;
      case 'APPROVED':
        return <Tag color="success"><CheckCircleOutlined /> 已通过</Tag>;
      case 'REJECTED':
        return <Tag color="error"><CloseCircleOutlined /> 已拒绝</Tag>;
      case 'DELIVERED':
        return <Tag color="success">已送达</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  // 订单表格列
  const orderColumns = [
    {
      title: '订单ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '客户姓名',
      dataIndex: 'customerName',
      key: 'customerName',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '金额',
      dataIndex: 'price',
      key: 'price',
      render: (price: number) => `¥${price}`,
    },
    {
      title: '下单日期',
      dataIndex: 'orderDate',
      key: 'orderDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button type="primary" onClick={() => handleOrderSelect(record)}>
          申请退货
        </Button>
      ),
    },
  ];

  // 退货申请表格列
  const applicationColumns = [
    {
      title: '申请ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '订单ID',
      dataIndex: 'orderId',
      key: 'orderId',
    },
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: '数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
    {
      title: '退货原因',
      dataIndex: 'returnReason',
      key: 'returnReason',
      render: (reason: string) => {
        const reasonObj = returnReasons.find(r => r.value === reason);
        return reasonObj ? reasonObj.label : reason;
      },
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmount',
      key: 'refundAmount',
      render: (amount: number) => `¥${amount}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '申请时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
  ];

  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={orderColumns}
          dataSource={orders}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          style={{ marginBottom: '24px' }}
        />

        <Divider orientation="left">退货申请记录</Divider>
        <Table
          columns={applicationColumns}
          dataSource={returnApplications}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>

      {/* 退货申请模态框 */}
      <Modal
        title="提交退货申请"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="orderId"
                label="订单ID"
                rules={[{ required: true, message: '请选择订单' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="productName"
                label="商品名称"
                rules={[{ required: true, message: '商品名称不能为空' }]}
              >
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="quantity"
                label="数量"
                rules={[{ required: true, message: '数量不能为空' }]}
              >
                <Input type="number" disabled />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="purchaseAmount"
                label="购买金额"
                rules={[{ required: true, message: '购买金额不能为空' }]}
              >
                <Input prefix="¥" disabled />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="returnReason"
            label="退货原因"
            rules={[{ required: true, message: '请选择退货原因' }]}
          >
            <Select placeholder="请选择退货原因">
              {returnReasons.map(reason => (
                <Option key={reason.value} value={reason.value}>
                  {reason.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="详细描述"
            rules={[{ required: true, message: '请详细描述退货原因' }]}
          >
            <Input.TextArea rows={4} placeholder="请详细描述退货原因，如有商品问题请提供具体情况" />
          </Form.Item>

          <Form.Item
            name="refundAmount"
            label="申请退款金额"
            rules={[{ required: true, message: '请填写退款金额' }]}
          >
            <Input prefix="¥" />
          </Form.Item>

          <Form.Item
            name="evidence"
            label="上传凭证"
          >
            <Upload
              name="evidence"
              action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
              listType="picture"
            >
              <Button icon={<FileOutlined />}>上传图片凭证</Button>
            </Upload>
            <Text type="secondary" style={{ display: 'block', marginTop: 8 }}>
              请上传商品问题的相关图片，最多可上传5张
            </Text>
          </Form.Item>

          <Form.Item
            name="contactInfo"
            label="联系方式"
            rules={[{ required: true, message: '请填写联系方式' }]}
          >
            <Input 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 ReturnApply;