import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Descriptions,
  Divider,
  message,
  Tabs,
  Badge,
  Tooltip,
  Row,
  Col,
  Statistic,
} from 'antd';
import {
  DollarOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  EyeOutlined,
  AuditOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { afterSalesDataSource, RefundRecord } from '@/services/afterSalesDataSource';

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

interface RefundRecord {
  id: string;
  orderId: string;
  refundId: string;
  customerId: string;
  customerName: string;
  amount: number;
  currency: string;
  reason: string;
  status: 'PENDING' | 'APPROVED' | 'REJECTED' | 'PROCESSING' | 'COMPLETED' | 'FAILED';
  createdAt: string;
  updatedAt: string;
  platform: string;
  refundMethod: string;
  transactionId?: string;
  processedBy?: string;
  remark?: string;
}

const REFUND_STATUS_MAP: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  PENDING: { color: 'warning', text: 'Pending', icon: <ClockCircleOutlined /> },
  APPROVED: { color: 'success', text: 'Approved', icon: <CheckCircleOutlined /> },
  REJECTED: { color: 'error', text: 'Rejected', icon: <CloseCircleOutlined /> },
  PROCESSING: { color: 'processing', text: 'Processing', icon: <SyncOutlined spin /> },
  COMPLETED: { color: 'success', text: 'Completed', icon: <CheckCircleOutlined /> },
  FAILED: { color: 'error', text: 'Failed', icon: <CloseCircleOutlined /> },
};

const REFUND_METHODS = [
  { value: 'ORIGINAL', label: 'Original Payment Method' },
  { value: 'STORE_CREDIT', label: 'Store Credit' },
  { value: 'BANK_TRANSFER', label: 'Bank Transfer' },
  { value: 'OTHER', label: 'Other' },
];

export const RefundProcess: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [refundRecords, setRefundRecords] = useState<RefundRecord[]>([]);
  const [selectedRecord, setSelectedRecord] = useState<RefundRecord | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [processModalVisible, setProcessModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [stats, setStats] = useState({
    total: 0,
    pending: 0,
    processing: 0,
    completed: 0,
    totalAmount: 0,
  });

  useEffect(() => {
    fetchRefundRecords();
  }, []);

  const fetchRefundRecords = async () => {
    setLoading(true);
    try {
      const mockRecords: RefundRecord[] = [
        {
          id: '1',
          orderId: 'ORD-2026-001',
          refundId: 'REF-2026-001',
          customerId: 'CUST_001',
          customerName: 'John Smith',
          amount: 59.98,
          currency: 'USD',
          reason: 'DEFECTIVE',
          status: 'PENDING',
          createdAt: '2026-03-18 10:30:00',
          updatedAt: '2026-03-18 10:30:00',
          platform: 'Amazon',
          refundMethod: 'ORIGINAL',
        },
        {
          id: '2',
          orderId: 'ORD-2026-002',
          refundId: 'REF-2026-002',
          customerId: 'CUST_002',
          customerName: 'Emma Wilson',
          amount: 125.50,
          currency: 'USD',
          reason: 'WRONG_ITEM',
          status: 'PROCESSING',
          createdAt: '2026-03-17 14:20:00',
          updatedAt: '2026-03-18 09:00:00',
          platform: 'eBay',
          refundMethod: 'ORIGINAL',
          transactionId: 'TXN_123456',
        },
        {
          id: '3',
          orderId: 'ORD-2026-003',
          refundId: 'REF-2026-003',
          customerId: 'CUST_003',
          customerName: 'Michael Brown',
          amount: 45.00,
          currency: 'USD',
          reason: 'QUALITY_ISSUE',
          status: 'COMPLETED',
          createdAt: '2026-03-16 09:15:00',
          updatedAt: '2026-03-17 16:30:00',
          platform: 'Shopify',
          refundMethod: 'ORIGINAL',
          transactionId: 'TXN_789012',
          processedBy: 'admin',
        },
        {
          id: '4',
          orderId: 'ORD-2026-004',
          refundId: 'REF-2026-004',
          customerId: 'CUST_004',
          customerName: 'Sarah Davis',
          amount: 89.99,
          currency: 'USD',
          reason: 'NOT_AS_DESCRIBED',
          status: 'REJECTED',
          createdAt: '2026-03-15 11:45:00',
          updatedAt: '2026-03-16 10:00:00',
          platform: 'Amazon',
          refundMethod: 'ORIGINAL',
          processedBy: 'manager',
          remark: 'Customer did not provide sufficient evidence',
        },
      ];

      setRefundRecords(mockRecords);
      calculateStats(mockRecords);
    } catch (error) {
      message.error('Failed to load refund records');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (records: RefundRecord[]) => {
    setStats({
      total: records.length,
      pending: records.filter((r) => r.status === 'PENDING').length,
      processing: records.filter((r) => r.status === 'PROCESSING').length,
      completed: records.filter((r) => r.status === 'COMPLETED').length,
      totalAmount: records
        .filter((r) => r.status === 'COMPLETED')
        .reduce((sum, r) => sum + r.amount, 0),
    });
  };

  const handleViewDetail = (record: RefundRecord) => {
    setSelectedRecord(record);
    setDetailModalVisible(true);
  };

  const handleProcess = (record: RefundRecord) => {
    setSelectedRecord(record);
    form.setFieldsValue({
      refundMethod: record.refundMethod,
      amount: record.amount,
    });
    setProcessModalVisible(true);
  };

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

      console.log('Approving refund:', {
        refundId: selectedRecord?.refundId,
        ...values,
      });

      await new Promise((resolve) => setTimeout(resolve, 1000));

      message.success('Refund approved successfully');
      setProcessModalVisible(false);
      fetchRefundRecords();
    } catch (error) {
      message.error('Failed to approve refund');
    } finally {
      setLoading(false);
    }
  };

  const handleReject = async () => {
    try {
      const values = await form.validateFields(['remark']);
      setLoading(true);

      console.log('Rejecting refund:', {
        refundId: selectedRecord?.refundId,
        remark: values.remark,
      });

      await new Promise((resolve) => setTimeout(resolve, 1000));

      message.success('Refund rejected');
      setProcessModalVisible(false);
      fetchRefundRecords();
    } catch (error) {
      message.error('Failed to reject refund');
    } finally {
      setLoading(false);
    }
  };

  const getFilteredRecords = () => {
    if (activeTab === 'all') return refundRecords;
    return refundRecords.filter((r) => r.status === activeTab.toUpperCase());
  };

  const columns: ColumnsType<RefundRecord> = [
    {
      title: 'Refund ID',
      dataIndex: 'refundId',
      key: 'refundId',
      width: 140,
      render: (text: string) => (
        <a onClick={() => handleViewDetail(refundRecords.find((r) => r.refundId === text)!)}>
          {text}
        </a>
      ),
    },
    {
      title: 'Order ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 140,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 120,
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
      width: 100,
      render: (platform: string) => <Tag>{platform}</Tag>,
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      key: 'amount',
      width: 100,
      render: (amount: number, record: RefundRecord) => (
        <span style={{ fontWeight: 'bold' }}>
          {record.currency} ${amount.toFixed(2)}
        </span>
      ),
    },
    {
      title: 'Reason',
      dataIndex: 'reason',
      key: 'reason',
      width: 150,
      render: (reason: string) => reason.replace(/_/g, ' '),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => {
        const config = REFUND_STATUS_MAP[status];
        return (
          <Tag icon={config.icon} color={config.color}>
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="View Details">
            <Button
              type="link"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          {(record.status === 'PENDING' || record.status === 'PROCESSING') && (
            <Tooltip title="Process">
              <Button
                type="link"
                icon={<AuditOutlined />}
                onClick={() => handleProcess(record)}
              />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="refund-process-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic
              title="Total Refunds"
              value={stats.total}
              prefix={<DollarOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Pending"
              value={stats.pending}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Processing"
              value={stats.processing}
              valueStyle={{ color: '#1890ff' }}
              prefix={<SyncOutlined />}
            />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic
              title="Completed"
              value={stats.completed}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic
              title="Total Refunded Amount"
              value={stats.totalAmount}
              precision={2}
              prefix="$"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Refund Management">
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={
              <span>
                <Badge count={stats.pending} offset={[10, 0]} size="small">
                  All
                </Badge>
              </span>
            }
            key="all"
          />
          <TabPane
            tab={
              <span>
                <Badge count={stats.pending} offset={[10, 0]} size="small">
                  Pending
                </Badge>
              </span>
            }
            key="pending"
          />
          <TabPane tab="Processing" key="processing" />
          <TabPane tab="Completed" key="completed" />
          <TabPane tab="Rejected" key="rejected" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={getFilteredRecords()}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1200 }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} records`,
          }}
        />
      </Card>

      <Modal
        title="Refund Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={700}
      >
        {selectedRecord && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="Refund ID" span={2}>
              {selectedRecord.refundId}
            </Descriptions.Item>
            <Descriptions.Item label="Order ID">{selectedRecord.orderId}</Descriptions.Item>
            <Descriptions.Item label="Platform">{selectedRecord.platform}</Descriptions.Item>
            <Descriptions.Item label="Customer ID">{selectedRecord.customerId}</Descriptions.Item>
            <Descriptions.Item label="Customer Name">
              {selectedRecord.customerName}
            </Descriptions.Item>
            <Descriptions.Item label="Amount" span={2}>
              <span style={{ fontSize: 18, fontWeight: 'bold', color: '#1890ff' }}>
                {selectedRecord.currency} ${selectedRecord.amount.toFixed(2)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="Reason">
              {selectedRecord.reason.replace(/_/g, ' ')}
            </Descriptions.Item>
            <Descriptions.Item label="Status">
              <Tag color={REFUND_STATUS_MAP[selectedRecord.status].color}>
                {REFUND_STATUS_MAP[selectedRecord.status].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Refund Method">
              {REFUND_METHODS.find((m) => m.value === selectedRecord.refundMethod)?.label}
            </Descriptions.Item>
            <Descriptions.Item label="Transaction ID">
              {selectedRecord.transactionId || '-'}
            </Descriptions.Item>
            <Descriptions.Item label="Created At">
              {selectedRecord.createdAt}
            </Descriptions.Item>
            <Descriptions.Item label="Updated At">
              {selectedRecord.updatedAt}
            </Descriptions.Item>
            {selectedRecord.processedBy && (
              <Descriptions.Item label="Processed By">
                {selectedRecord.processedBy}
              </Descriptions.Item>
            )}
            {selectedRecord.remark && (
              <Descriptions.Item label="Remark" span={2}>
                {selectedRecord.remark}
              </Descriptions.Item>
            )}
          </Descriptions>
        )}
      </Modal>

      <Modal
        title="Process Refund"
        open={processModalVisible}
        onCancel={() => setProcessModalVisible(false)}
        footer={null}
        width={600}
      >
        {selectedRecord && (
          <>
            <Descriptions bordered column={2} size="small" style={{ marginBottom: 24 }}>
              <Descriptions.Item label="Refund ID">
                {selectedRecord.refundId}
              </Descriptions.Item>
              <Descriptions.Item label="Order ID">{selectedRecord.orderId}</Descriptions.Item>
              <Descriptions.Item label="Customer">
                {selectedRecord.customerName}
              </Descriptions.Item>
              <Descriptions.Item label="Amount">
                ${selectedRecord.amount.toFixed(2)}
              </Descriptions.Item>
            </Descriptions>

            <Divider />

            <Form form={form} layout="vertical">
              <Form.Item
                name="refundMethod"
                label="Refund Method"
                rules={[{ required: true }]}
              >
                <Select>
                  {REFUND_METHODS.map((method) => (
                    <Option key={method.value} value={method.value}>
                      {method.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>

              <Form.Item
                name="amount"
                label="Refund Amount"
                rules={[{ required: true }]}
              >
                <InputNumber
                  prefix="$"
                  precision={2}
                  min={0}
                  max={selectedRecord.amount}
                  style={{ width: '100%' }}
                />
              </Form.Item>

              <Form.Item name="remark" label="Remark">
                <TextArea rows={3} placeholder="Enter remark (optional)" />
              </Form.Item>

              <div style={{ textAlign: 'right' }}>
                <Space>
                  <Button onClick={() => setProcessModalVisible(false)}>Cancel</Button>
                  <Button danger onClick={handleReject} loading={loading}>
                    Reject
                  </Button>
                  <Button type="primary" onClick={handleApprove} loading={loading}>
                    Approve
                  </Button>
                </Space>
              </div>
            </Form>
          </>
        )}
      </Modal>
    </div>
  );
};

export default RefundProcess;
