import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Modal,
  Steps,
  Upload,
  message,
  Space,
  Tag,
  Descriptions,
  Divider,
  Row,
  Col,
} from 'antd';
import {
  UploadOutlined,
  ArrowLeftOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { afterSalesDataSource, OrderItem, ReturnFormData } from '@/services/afterSalesDataSource';

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

interface ReturnApplyProps {
  orderId?: string;
  onBack?: () => void;
}

const RETURN_REASONS = [
  { value: 'DEFECTIVE', label: '商品有缺陷/损坏' },
  { value: 'WRONG_ITEM', label: '发错商品' },
  { value: 'QUALITY_ISSUE', label: '质量问题' },
  { value: 'NOT_AS_DESCRIBED', label: '与描述不符' },
  { value: 'SIZE_MISMATCH', label: '尺寸不符' },
  { value: 'OTHER', label: '其他原因' },
];

const RETURN_STATUS_MAP: Record<string, { color: string; text: string }> = {
  PENDING: { color: 'processing', text: '待审核' },
  APPROVED: { color: 'success', text: '已通过' },
  REJECTED: { color: 'error', text: '已拒绝' },
  PROCESSING: { color: 'blue', text: '处理中' },
  COMPLETED: { color: 'success', text: '已完成' },
  CANCELLED: { color: 'default', text: '已取消' },
};

export const ReturnApply: React.FC<ReturnApplyProps> = ({ orderId, onBack }) => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [submitModalVisible, setSubmitModalVisible] = useState(false);
  const [fileList, setFileList] = useState<any[]>([]);

  useEffect(() => {
    if (orderId) {
      fetchOrderItems(orderId);
    }
  }, [orderId]);

  const fetchOrderItems = async (id: string) => {
    setLoading(true);
    try {
      const items = await afterSalesDataSource.fetchOrderItems(id);
      setOrderItems(items);
    } catch (error) {
      message.error('Failed to load order items');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const returnData: ReturnFormData = {
        orderId: orderId || '',
        returnReason: values.returnReason,
        returnDescription: values.returnDescription,
        returnItems: selectedItems,
        images: fileList.map((f) => f.response?.url || f.name),
        contactPhone: values.contactPhone,
      };

      await afterSalesDataSource.submitReturnApply(returnData);

      message.success('Return application submitted successfully');
      setCurrentStep(2);
      setSubmitModalVisible(false);
    } catch (error) {
      message.error('Failed to submit return application');
    } finally {
      setLoading(false);
    }
  };

  const handleItemSelect = (selectedRowKeys: React.Key[]) => {
    setSelectedItems(selectedRowKeys as string[]);
  };

  const columns: ColumnsType<OrderItem> = [
    {
      title: 'SKU',
      dataIndex: 'skuId',
      key: 'skuId',
      width: 120,
    },
    {
      title: 'Product Name',
      dataIndex: 'productName',
      key: 'productName',
    },
    {
      title: 'Quantity',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 80,
    },
    {
      title: 'Unit Price',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Total',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
  ];

  const rowSelection = {
    selectedRowKeys: selectedItems,
    onChange: handleItemSelect,
  };

  const handleUploadChange = (info: any) => {
    setFileList(info.fileList);
  };

  const steps = [
    { title: 'Select Items', description: 'Choose items to return' },
    { title: 'Fill Details', description: 'Provide return reason' },
    { title: 'Submit', description: 'Review and submit' },
  ];

  return (
    <div className="return-apply-page">
      <Card
        title={
          <Space>
            {onBack && (
              <Button icon={<ArrowLeftOutlined />} onClick={onBack}>
                Back
              </Button>
            )}
            <span>Return Application</span>
          </Space>
        }
        extra={
          <Tag color="blue">
            Order ID: {orderId || 'ORD-2026-001'}
          </Tag>
        }
      >
        <Steps current={currentStep} items={steps} style={{ marginBottom: 24 }} />

        {currentStep === 0 && (
          <>
            <Descriptions title="Order Information" bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="Order ID">{orderId || 'ORD-2026-001'}</Descriptions.Item>
              <Descriptions.Item label="Order Date">2026-03-15</Descriptions.Item>
              <Descriptions.Item label="Platform">Amazon</Descriptions.Item>
              <Descriptions.Item label="Total Amount">$84.93</Descriptions.Item>
            </Descriptions>

            <Divider>Select Items to Return</Divider>

            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={orderItems}
              rowKey="id"
              loading={loading}
              pagination={false}
            />

            <div style={{ marginTop: 24, textAlign: 'right' }}>
              <Button
                type="primary"
                disabled={selectedItems.length === 0}
                onClick={() => setCurrentStep(1)}
              >
                Next Step
              </Button>
            </div>
          </>
        )}

        {currentStep === 1 && (
          <Form form={form} layout="vertical">
            <Row gutter={24}>
              <Col span={12}>
                <Form.Item
                  name="returnReason"
                  label="Return Reason"
                  rules={[{ required: true, message: 'Please select return reason' }]}
                >
                  <Select placeholder="Select return reason" size="large">
                    {RETURN_REASONS.map((reason) => (
                      <Option key={reason.value} value={reason.value}>
                        {reason.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="contactPhone"
                  label="Contact Phone"
                  rules={[{ required: true, message: 'Please enter contact phone' }]}
                >
                  <Input placeholder="Enter contact phone number" size="large" />
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="returnDescription"
              label="Description"
              rules={[{ required: true, message: 'Please describe the issue' }]}
            >
              <TextArea
                rows={4}
                placeholder="Please describe the issue in detail..."
                showCount
                maxLength={500}
              />
            </Form.Item>

            <Form.Item label="Upload Images (Optional)">
              <Upload
                listType="picture-card"
                fileList={fileList}
                onChange={handleUploadChange}
                beforeUpload={() => false}
                maxCount={5}
              >
                {fileList.length < 5 && (
                  <div>
                    <UploadOutlined />
                    <div style={{ marginTop: 8 }}>Upload</div>
                  </div>
                )}
              </Upload>
              <div style={{ color: '#999', fontSize: 12 }}>
                Support JPG, PNG format, max 5 images
              </div>
            </Form.Item>

            <div style={{ marginTop: 24, textAlign: 'right' }}>
              <Space>
                <Button onClick={() => setCurrentStep(0)}>Previous</Button>
                <Button type="primary" onClick={() => setSubmitModalVisible(true)}>
                  Submit Application
                </Button>
              </Space>
            </div>
          </Form>
        )}

        {currentStep === 2 && (
          <div style={{ textAlign: 'center', padding: '40px 0' }}>
            <CheckCircleOutlined style={{ fontSize: 64, color: '#52c41a' }} />
            <h2 style={{ marginTop: 24 }}>Return Application Submitted</h2>
            <p style={{ color: '#666' }}>
              Your return application has been submitted successfully.
              <br />
              We will review your application within 1-2 business days.
            </p>
            <Descriptions bordered column={1} style={{ maxWidth: 400, margin: '24px auto' }}>
              <Descriptions.Item label="Return ID">RTN-2026-0001</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color="processing">Pending Review</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Items Count">{selectedItems.length}</Descriptions.Item>
            </Descriptions>
            <Button type="primary" onClick={onBack}>
              Return to Order List
            </Button>
          </div>
        )}
      </Card>

      <Modal
        title="Confirm Submission"
        open={submitModalVisible}
        onCancel={() => setSubmitModalVisible(false)}
        onOk={handleSubmit}
        confirmLoading={loading}
      >
        <p>Are you sure you want to submit this return application?</p>
        <Descriptions column={1} size="small">
          <Descriptions.Item label="Items Selected">{selectedItems.length}</Descriptions.Item>
          <Descriptions.Item label="Reason">
            {form.getFieldValue('returnReason')}
          </Descriptions.Item>
        </Descriptions>
      </Modal>
    </div>
  );
};

export default ReturnApply;
