import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  message,
  Tooltip,
  Row,
  Col,
  Statistic,
  Badge,
  Tabs,
  Descriptions,
  Divider,
  Alert,
  Popconfirm,
} from 'antd';
import {
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  EyeOutlined,
  ReloadOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { orderDataSource, OrderDetailData } from '@/services/orderDataSource';

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

interface ExceptionOrder {
  id: string;
  orderId: string;
  platform: string;
  customerName: string;
  totalAmount: number;
  exceptionType: 'PAYMENT_FAILED' | 'OUT_OF_STOCK' | 'ADDRESS_INVALID' | 'FRAUD_SUSPECTED' | 'SHIPPING_FAILED' | 'OTHER';
  severity: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  status: 'OPEN' | 'IN_PROGRESS' | 'RESOLVED' | 'ESCALATED';
  description: string;
  createdAt: string;
  assignedTo?: string;
  resolution?: string;
}

const EXCEPTION_TYPE_MAP: Record<string, { color: string; text: string }> = {
  PAYMENT_FAILED: { color: 'red', text: 'Payment Failed' },
  OUT_OF_STOCK: { color: 'orange', text: 'Out of Stock' },
  ADDRESS_INVALID: { color: 'blue', text: 'Invalid Address' },
  FRAUD_SUSPECTED: { color: 'purple', text: 'Fraud Suspected' },
  SHIPPING_FAILED: { color: 'cyan', text: 'Shipping Failed' },
  OTHER: { color: 'default', text: 'Other' },
};

const SEVERITY_MAP: Record<string, { color: string; text: string }> = {
  LOW: { color: 'default', text: 'Low' },
  MEDIUM: { color: 'blue', text: 'Medium' },
  HIGH: { color: 'orange', text: 'High' },
  CRITICAL: { color: 'red', text: 'Critical' },
};

const EXCEPTION_STATUS_MAP: Record<string, { color: string; text: string }> = {
  OPEN: { color: 'error', text: 'Open' },
  IN_PROGRESS: { color: 'processing', text: 'In Progress' },
  RESOLVED: { color: 'success', text: 'Resolved' },
  ESCALATED: { color: 'warning', text: 'Escalated' },
};

export const ExceptionOrder: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [exceptions, setExceptions] = useState<ExceptionOrder[]>([]);
  const [selectedException, setSelectedException] = useState<ExceptionOrder | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [resolveModalVisible, setResolveModalVisible] = useState(false);
  const [activeTab, setActiveTab] = useState('all');
  const [stats, setStats] = useState({
    total: 0,
    open: 0,
    critical: 0,
    resolved: 0,
  });

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

  const fetchExceptions = async () => {
    setLoading(true);
    try {
      const mockExceptions: ExceptionOrder[] = [
        {
          id: '1',
          orderId: 'ORD-2026-001',
          platform: 'AMAZON',
          customerName: 'John Smith',
          totalAmount: 159.99,
          exceptionType: 'PAYMENT_FAILED',
          severity: 'HIGH',
          status: 'OPEN',
          description: 'Payment authorization failed. Customer card was declined.',
          createdAt: '2026-03-18 10:30:00',
        },
        {
          id: '2',
          orderId: 'ORD-2026-002',
          platform: 'EBAY',
          customerName: 'Emma Wilson',
          totalAmount: 89.50,
          exceptionType: 'OUT_OF_STOCK',
          severity: 'MEDIUM',
          status: 'IN_PROGRESS',
          description: 'Item SKU-001 is out of stock. Need to source from supplier.',
          createdAt: '2026-03-18 09:15:00',
          assignedTo: 'Agent_001',
        },
        {
          id: '3',
          orderId: 'ORD-2026-003',
          platform: 'SHOPIFY',
          customerName: 'Michael Brown',
          totalAmount: 245.00,
          exceptionType: 'ADDRESS_INVALID',
          severity: 'LOW',
          status: 'RESOLVED',
          description: 'Shipping address incomplete. Missing zip code.',
          createdAt: '2026-03-17 16:45:00',
          resolution: 'Contacted customer and obtained correct address.',
        },
        {
          id: '4',
          orderId: 'ORD-2026-004',
          platform: 'SHOPEE',
          customerName: 'Sarah Davis',
          totalAmount: 780.00,
          exceptionType: 'FRAUD_SUSPECTED',
          severity: 'CRITICAL',
          status: 'ESCALATED',
          description: 'Multiple high-value orders from same IP address. Possible fraud.',
          createdAt: '2026-03-18 08:00:00',
          assignedTo: 'Fraud_Team',
        },
        {
          id: '5',
          orderId: 'ORD-2026-005',
          platform: 'AMAZON',
          customerName: 'David Lee',
          totalAmount: 120.00,
          exceptionType: 'SHIPPING_FAILED',
          severity: 'HIGH',
          status: 'OPEN',
          description: 'Carrier returned package. Address undeliverable.',
          createdAt: '2026-03-17 14:20:00',
        },
      ];

      setExceptions(mockExceptions);
      calculateStats(mockExceptions);
    } catch (error) {
      message.error('Failed to load exception orders');
    } finally {
      setLoading(false);
    }
  };

  const calculateStats = (exceptionList: ExceptionOrder[]) => {
    setStats({
      total: exceptionList.length,
      open: exceptionList.filter((e) => e.status === 'OPEN').length,
      critical: exceptionList.filter((e) => e.severity === 'CRITICAL').length,
      resolved: exceptionList.filter((e) => e.status === 'RESOLVED').length,
    });
  };

  const handleViewDetail = (exception: ExceptionOrder) => {
    setSelectedException(exception);
    setDetailModalVisible(true);
  };

  const handleResolve = (exception: ExceptionOrder) => {
    setSelectedException(exception);
    form.resetFields();
    setResolveModalVisible(true);
  };

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

      console.log('Resolving exception:', {
        exceptionId: selectedException?.id,
        resolution: values.resolution,
        action: values.action,
      });

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

      message.success('Exception resolved successfully');
      setResolveModalVisible(false);
      fetchExceptions();
    } catch (error) {
      message.error('Failed to resolve exception');
    } finally {
      setLoading(false);
    }
  };

  const handleEscalate = async (exceptionId: string) => {
    setLoading(true);
    try {
      console.log('Escalating exception:', exceptionId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Exception escalated to supervisor');
      fetchExceptions();
    } catch (error) {
      message.error('Failed to escalate exception');
    } finally {
      setLoading(false);
    }
  };

  const handleAutoResolve = async (exceptionId: string) => {
    setLoading(true);
    try {
      console.log('Auto-resolving exception:', exceptionId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Auto-resolution applied');
      fetchExceptions();
    } catch (error) {
      message.error('Failed to auto-resolve');
    } finally {
      setLoading(false);
    }
  };

  const getFilteredExceptions = () => {
    if (activeTab === 'all') return exceptions;
    if (activeTab === 'open') return exceptions.filter((e) => e.status === 'OPEN');
    if (activeTab === 'in_progress') return exceptions.filter((e) => e.status === 'IN_PROGRESS');
    if (activeTab === 'escalated') return exceptions.filter((e) => e.severity === 'CRITICAL' || e.status === 'ESCALATED');
    if (activeTab === 'resolved') return exceptions.filter((e) => e.status === 'RESOLVED');
    return exceptions;
  };

  const columns: ColumnsType<ExceptionOrder> = [
    {
      title: 'Order ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 130,
      render: (text: string, record) => (
        <a onClick={() => handleViewDetail(record)}>{text}</a>
      ),
    },
    {
      title: 'Type',
      dataIndex: 'exceptionType',
      key: 'exceptionType',
      width: 140,
      render: (type: string) => {
        const config = EXCEPTION_TYPE_MAP[type];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Severity',
      dataIndex: 'severity',
      key: 'severity',
      width: 90,
      render: (severity: string) => {
        const config = SEVERITY_MAP[severity];
        return (
          <Tag
            color={config.color}
            icon={severity === 'CRITICAL' ? <WarningOutlined /> : undefined}
          >
            {config.text}
          </Tag>
        );
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 110,
      render: (status: string) => {
        const config = EXCEPTION_STATUS_MAP[status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 120,
    },
    {
      title: 'Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 90,
      render: (amount: number) => <strong>${amount.toFixed(2)}</strong>,
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 200,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
    },
    {
      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 !== 'RESOLVED' && (
            <>
              <Tooltip title="Resolve">
                <Button type="link" icon={<CheckCircleOutlined />} onClick={() => handleResolve(record)} />
              </Tooltip>
              <Popconfirm
                title="Escalate this exception?"
                onConfirm={() => handleEscalate(record.id)}
              >
                <Tooltip title="Escalate">
                  <Button type="link" icon={<ExclamationCircleOutlined />} />
                </Tooltip>
              </Popconfirm>
            </>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="exception-order-page">
      {stats.critical > 0 && (
        <Alert
          message={`${stats.critical} Critical Exception${stats.critical > 1 ? 's' : ''} Require Immediate Attention`}
          type="error"
          showIcon
          icon={<WarningOutlined />}
          style={{ marginBottom: 16 }}
        />
      )}

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Exceptions"
              value={stats.total}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Open"
              value={stats.open}
              valueStyle={{ color: '#f5222d' }}
              prefix={<ExclamationCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Critical"
              value={stats.critical}
              valueStyle={{ color: '#faad14' }}
              prefix={<WarningOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Resolved"
              value={stats.resolved}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="Exception Order Management"
        extra={
          <Space>
            <Button icon={<ReloadOutlined />} onClick={fetchExceptions}>
              Refresh
            </Button>
          </Space>
        }
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane
            tab={<Badge count={stats.open} offset={[10, 0]} size="small">All</Badge>}
            key="all"
          />
          <TabPane tab="Open" key="open" />
          <TabPane tab="In Progress" key="in_progress" />
          <TabPane tab="Escalated" key="escalated" />
          <TabPane tab="Resolved" key="resolved" />
        </Tabs>

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

      <Modal
        title="Exception Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
          selectedException?.status !== 'RESOLVED' && (
            <Button
              key="resolve"
              type="primary"
              onClick={() => {
                setDetailModalVisible(false);
                handleResolve(selectedException!);
              }}
            >
              Resolve
            </Button>
          ),
        ]}
        width={700}
      >
        {selectedException && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Order ID">{selectedException.orderId}</Descriptions.Item>
              <Descriptions.Item label="Platform">{selectedException.platform}</Descriptions.Item>
              <Descriptions.Item label="Exception Type">
                <Tag color={EXCEPTION_TYPE_MAP[selectedException.exceptionType].color}>
                  {EXCEPTION_TYPE_MAP[selectedException.exceptionType].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Severity">
                <Tag color={SEVERITY_MAP[selectedException.severity].color}>
                  {SEVERITY_MAP[selectedException.severity].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={EXCEPTION_STATUS_MAP[selectedException.status].color}>
                  {EXCEPTION_STATUS_MAP[selectedException.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Amount">${selectedException.totalAmount.toFixed(2)}</Descriptions.Item>
              <Descriptions.Item label="Customer">{selectedException.customerName}</Descriptions.Item>
              <Descriptions.Item label="Assigned To">{selectedException.assignedTo || 'Unassigned'}</Descriptions.Item>
              <Descriptions.Item label="Created">{selectedException.createdAt}</Descriptions.Item>
            </Descriptions>

            <Divider>Description</Divider>
            <p>{selectedException.description}</p>

            {selectedException.resolution && (
              <>
                <Divider>Resolution</Divider>
                <p style={{ color: '#52c41a' }}>{selectedException.resolution}</p>
              </>
            )}
          </>
        )}
      </Modal>

      <Modal
        title="Resolve Exception"
        open={resolveModalVisible}
        onCancel={() => setResolveModalVisible(false)}
        onOk={handleSubmitResolution}
        confirmLoading={loading}
        width={600}
      >
        {selectedException && (
          <>
            <Alert
              message={`${EXCEPTION_TYPE_MAP[selectedException.exceptionType].text} - ${selectedException.orderId}`}
              description={selectedException.description}
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />

            <Form form={form} layout="vertical">
              <Form.Item name="action" label="Action Taken" rules={[{ required: true }]}>
                <Select placeholder="Select action">
                  <Option value="CONTACT_CUSTOMER">Contact Customer</Option>
                  <Option value="REFUND_ISSUED">Refund Issued</Option>
                  <Option value="REPLACEMENT_SENT">Replacement Sent</Option>
                  <Option value="ADDRESS_UPDATED">Address Updated</Option>
                  <Option value="STOCK_ALLOCATED">Stock Allocated</Option>
                  <Option value="ORDER_CANCELLED">Order Cancelled</Option>
                  <Option value="OTHER">Other</Option>
                </Select>
              </Form.Item>
              <Form.Item name="resolution" label="Resolution Notes" rules={[{ required: true }]}>
                <TextArea rows={4} placeholder="Describe how the exception was resolved..." />
              </Form.Item>
            </Form>
          </>
        )}
      </Modal>
    </div>
  );
};

export default ExceptionOrder;
