import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Tag,
  Row,
  Col,
  Statistic,
  message,
  Timeline,
  Descriptions,
  Divider,
  Empty,
  Spin,
  Badge,
  Progress,
  Alert,
} from 'antd';
import {
  EnvironmentOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  TruckOutlined,
  SearchOutlined,
  SyncOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { logisticsDataSource, TrackingEvent, Shipment } from '@/services/logisticsDataSource';

type TrackingStatus = 'PENDING' | 'IN_TRANSIT' | 'CUSTOMS' | 'OUT_FOR_DELIVERY' | 'DELIVERED' | 'EXCEPTION';

interface TrackingInfo {
  trackingNumber: string;
  orderId: string;
  carrier: string;
  logisticsName: string;
  origin: string;
  destination: string;
  status: TrackingStatus;
  estimatedDelivery: string;
  actualDelivery?: string;
  weight: number;
  events: TrackingEvent[];
  lastUpdate: string;
}

interface TrackingRecord {
  id: string;
  orderId: string;
  trackingNumber: string;
  carrier: string;
  status: TrackingStatus;
  lastUpdate: string;
}

const STATUS_COLORS: Record<TrackingStatus, string> = {
  PENDING: 'default',
  IN_TRANSIT: 'blue',
  CUSTOMS: 'orange',
  OUT_FOR_DELIVERY: 'cyan',
  DELIVERED: 'green',
  EXCEPTION: 'red',
};

const STATUS_ICONS: Record<TrackingStatus, React.ReactNode> = {
  PENDING: <ClockCircleOutlined />,
  IN_TRANSIT: <TruckOutlined />,
  CUSTOMS: <SyncOutlined />,
  OUT_FOR_DELIVERY: <TruckOutlined />,
  DELIVERED: <CheckCircleOutlined />,
  EXCEPTION: <CloseCircleOutlined />,
};

const STATUS_PROGRESS: Record<TrackingStatus, number> = {
  PENDING: 10,
  IN_TRANSIT: 40,
  CUSTOMS: 55,
  OUT_FOR_DELIVERY: 80,
  DELIVERED: 100,
  EXCEPTION: 0,
};

const MOCK_TRACKING_RECORDS: TrackingRecord[] = [
  {
    id: 'TRK-001',
    orderId: 'ORD-2026-001',
    trackingNumber: 'DHL123456789',
    carrier: 'DHL',
    status: 'IN_TRANSIT',
    lastUpdate: '2026-03-18T14:30:00Z',
  },
  {
    id: 'TRK-002',
    orderId: 'ORD-2026-002',
    trackingNumber: 'FedEx987654321',
    carrier: 'FedEx',
    status: 'OUT_FOR_DELIVERY',
    lastUpdate: '2026-03-18T16:45:00Z',
  },
  {
    id: 'TRK-003',
    orderId: 'ORD-2026-003',
    trackingNumber: 'UPS456789123',
    carrier: 'UPS',
    status: 'DELIVERED',
    lastUpdate: '2026-03-17T10:20:00Z',
  },
];

const MOCK_TRACKING_DETAILS: Record<string, TrackingInfo> = {
  'DHL123456789': {
    trackingNumber: 'DHL123456789',
    orderId: 'ORD-2026-001',
    carrier: 'DHL',
    logisticsName: 'DHL Express',
    origin: 'Shenzhen, China',
    destination: 'Los Angeles, CA, USA',
    status: 'IN_TRANSIT',
    estimatedDelivery: '2026-03-21',
    weight: 2.5,
    lastUpdate: '2026-03-18T14:30:00Z',
    events: [
      {
        id: 'EVT-001',
        timestamp: '2026-03-18T14:30:00Z',
        location: 'Anchorage, AK, USA',
        status: 'IN_TRANSIT',
        description: 'Shipment in transit to destination',
      },
      {
        id: 'EVT-002',
        timestamp: '2026-03-17T22:15:00Z',
        location: 'Shanghai, China',
        status: 'IN_TRANSIT',
        description: 'Departed from facility',
      },
      {
        id: 'EVT-003',
        timestamp: '2026-03-17T08:00:00Z',
        location: 'Shenzhen, China',
        status: 'IN_TRANSIT',
        description: 'Shipment picked up',
      },
      {
        id: 'EVT-004',
        timestamp: '2026-03-16T15:30:00Z',
        location: 'Shenzhen, China',
        status: 'PENDING',
        description: 'Shipment information received',
      },
    ],
  },
  'FedEx987654321': {
    trackingNumber: 'FedEx987654321',
    orderId: 'ORD-2026-002',
    carrier: 'FedEx',
    logisticsName: 'FedEx International Priority',
    origin: 'Guangzhou, China',
    destination: 'London, UK',
    status: 'OUT_FOR_DELIVERY',
    estimatedDelivery: '2026-03-18',
    weight: 1.2,
    lastUpdate: '2026-03-18T16:45:00Z',
    events: [
      {
        id: 'EVT-005',
        timestamp: '2026-03-18T16:45:00Z',
        location: 'London, UK',
        status: 'OUT_FOR_DELIVERY',
        description: 'Out for delivery',
      },
      {
        id: 'EVT-006',
        timestamp: '2026-03-18T08:00:00Z',
        location: 'London, UK',
        status: 'IN_TRANSIT',
        description: 'Arrived at local facility',
      },
      {
        id: 'EVT-007',
        timestamp: '2026-03-17T12:00:00Z',
        location: 'Paris, France',
        status: 'IN_TRANSIT',
        description: 'In transit',
      },
      {
        id: 'EVT-008',
        timestamp: '2026-03-16T10:00:00Z',
        location: 'Guangzhou, China',
        status: 'PENDING',
        description: 'Picked up',
      },
    ],
  },
  'UPS456789123': {
    trackingNumber: 'UPS456789123',
    orderId: 'ORD-2026-003',
    carrier: 'UPS',
    logisticsName: 'UPS Standard',
    origin: 'Shanghai, China',
    destination: 'New York, NY, USA',
    status: 'DELIVERED',
    estimatedDelivery: '2026-03-17',
    actualDelivery: '2026-03-17T10:20:00Z',
    weight: 3.0,
    lastUpdate: '2026-03-17T10:20:00Z',
    events: [
      {
        id: 'EVT-009',
        timestamp: '2026-03-17T10:20:00Z',
        location: 'New York, NY, USA',
        status: 'DELIVERED',
        description: 'Delivered - Signed by: J. SMITH',
      },
      {
        id: 'EVT-010',
        timestamp: '2026-03-17T08:00:00Z',
        location: 'New York, NY, USA',
        status: 'OUT_FOR_DELIVERY',
        description: 'Out for delivery',
      },
      {
        id: 'EVT-011',
        timestamp: '2026-03-16T14:00:00Z',
        location: 'New York, NY, USA',
        status: 'IN_TRANSIT',
        description: 'Arrived at facility',
      },
    ],
  },
};

export const LogisticsTrack: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [trackingRecords, setTrackingRecords] = useState<TrackingRecord[]>(MOCK_TRACKING_RECORDS);
  const [searchValue, setSearchValue] = useState('');
  const [selectedTracking, setSelectedTracking] = useState<TrackingInfo | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

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

  const loadTrackingRecords = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setTrackingRecords(MOCK_TRACKING_RECORDS);
    } catch (error) {
      message.error('Failed to load tracking records');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async () => {
    if (!searchValue.trim()) {
      message.warning('Please enter tracking number or order ID');
      return;
    }

    setDetailLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 800));
      
      const trackingInfo = MOCK_TRACKING_DETAILS[searchValue.toUpperCase()];
      if (trackingInfo) {
        setSelectedTracking(trackingInfo);
      } else {
        message.warning('Tracking information not found');
      }
    } catch (error) {
      message.error('Failed to search tracking');
    } finally {
      setDetailLoading(false);
    }
  };

  const handleRowClick = async (record: TrackingRecord) => {
    setSearchValue(record.trackingNumber);
    setDetailLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      const trackingInfo = MOCK_TRACKING_DETAILS[record.trackingNumber];
      if (trackingInfo) {
        setSelectedTracking(trackingInfo);
      }
    } catch (error) {
      message.error('Failed to load tracking details');
    } finally {
      setDetailLoading(false);
    }
  };

  const columns: ColumnsType<TrackingRecord> = [
    {
      title: 'Order ID',
      dataIndex: 'orderId',
      key: 'orderId',
      width: 150,
      render: (id: string) => <strong>{id}</strong>,
    },
    {
      title: 'Tracking Number',
      dataIndex: 'trackingNumber',
      key: 'trackingNumber',
      width: 180,
      render: (number: string) => <code>{number}</code>,
    },
    {
      title: 'Carrier',
      dataIndex: 'carrier',
      key: 'carrier',
      width: 100,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: TrackingStatus) => (
        <Tag color={STATUS_COLORS[status]} icon={STATUS_ICONS[status]}>
          {status.replace(/_/g, ' ')}
        </Tag>
      ),
    },
    {
      title: 'Last Update',
      dataIndex: 'lastUpdate',
      key: 'lastUpdate',
      width: 180,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
  ];

  const getTimelineColor = (status: string) => {
    if (status === 'DELIVERED') return 'green';
    if (status === 'EXCEPTION') return 'red';
    return 'blue';
  };

  const inTransitCount = trackingRecords.filter(r => 
    ['IN_TRANSIT', 'CUSTOMS', 'OUT_FOR_DELIVERY'].includes(r.status)
  ).length;
  const deliveredCount = trackingRecords.filter(r => r.status === 'DELIVERED').length;
  const exceptionCount = trackingRecords.filter(r => r.status === 'EXCEPTION').length;

  return (
    <div className="logistics-track-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Shipments"
              value={trackingRecords.length}
              prefix={<TruckOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="In Transit"
              value={inTransitCount}
              valueStyle={{ color: '#1890ff' }}
              prefix={<SyncOutlined spin />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Delivered"
              value={deliveredCount}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Exceptions"
              value={exceptionCount}
              valueStyle={{ color: exceptionCount > 0 ? '#ff4d4f' : '#52c41a' }}
              prefix={<CloseCircleOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card 
        title="Track Shipment"
        style={{ marginBottom: 16 }}
        extra={
          <Button icon={<SyncOutlined />} onClick={loadTrackingRecords} loading={loading}>
            Refresh
          </Button>
        }
      >
        <Space.Compact style={{ width: '100%' }}>
          <Input
            placeholder="Enter tracking number or order ID"
            value={searchValue}
            onChange={(e) => setSearchValue(e.target.value)}
            onPressEnter={handleSearch}
            prefix={<SearchOutlined />}
            size="large"
          />
          <Button type="primary" size="large" onClick={handleSearch} loading={detailLoading}>
            Track
          </Button>
        </Space.Compact>
      </Card>

      <Row gutter={16}>
        <Col span={10}>
          <Card title="Recent Shipments">
            <Table
              columns={columns}
              dataSource={trackingRecords}
              rowKey="id"
              loading={loading}
              pagination={false}
              onRow={(record) => ({
                onClick: () => handleRowClick(record),
                style: { cursor: 'pointer' },
              })}
            />
          </Card>
        </Col>
        <Col span={14}>
          <Card title="Tracking Details">
            <Spin spinning={detailLoading} indicator={<LoadingOutlined />}>
              {selectedTracking ? (
                <div>
                  <Alert
                    message={
                      <Space>
                        <span>Tracking: <strong>{selectedTracking.trackingNumber}</strong></span>
                        <Tag color={STATUS_COLORS[selectedTracking.status]} icon={STATUS_ICONS[selectedTracking.status]}>
                          {selectedTracking.status.replace(/_/g, ' ')}
                        </Tag>
                      </Space>
                    }
                    type={selectedTracking.status === 'DELIVERED' ? 'success' : 
                          selectedTracking.status === 'EXCEPTION' ? 'error' : 'info'}
                    showIcon
                    style={{ marginBottom: 16 }}
                  />

                  <div style={{ marginBottom: 24 }}>
                    <Progress
                      percent={STATUS_PROGRESS[selectedTracking.status]}
                      status={selectedTracking.status === 'EXCEPTION' ? 'exception' : 
                              selectedTracking.status === 'DELIVERED' ? 'success' : 'active'}
                      format={() => selectedTracking.status.replace(/_/g, ' ')}
                    />
                  </div>

                  <Descriptions bordered column={2} size="small">
                    <Descriptions.Item label="Order ID">{selectedTracking.orderId}</Descriptions.Item>
                    <Descriptions.Item label="Carrier">{selectedTracking.carrier}</Descriptions.Item>
                    <Descriptions.Item label="Origin">
                      <EnvironmentOutlined /> {selectedTracking.origin}
                    </Descriptions.Item>
                    <Descriptions.Item label="Destination">
                      <EnvironmentOutlined /> {selectedTracking.destination}
                    </Descriptions.Item>
                    <Descriptions.Item label="Weight">{selectedTracking.weight} kg</Descriptions.Item>
                    <Descriptions.Item label="Est. Delivery">
                      {selectedTracking.estimatedDelivery}
                    </Descriptions.Item>
                    {selectedTracking.actualDelivery && (
                      <Descriptions.Item label="Actual Delivery" span={2}>
                        <strong style={{ color: '#52c41a' }}>
                          {dayjs(selectedTracking.actualDelivery).format('YYYY-MM-DD HH:mm')}
                        </strong>
                      </Descriptions.Item>
                    )}
                  </Descriptions>

                  <Divider>Tracking History</Divider>

                  <Timeline
                    items={selectedTracking.events.map(event => ({
                      color: getTimelineColor(event.status),
                      children: (
                        <div>
                          <div style={{ fontWeight: 500 }}>{event.description}</div>
                          <div style={{ fontSize: 12, color: '#888' }}>
                            <Space split={<span>|</span>}>
                              <span>{dayjs(event.timestamp).format('YYYY-MM-DD HH:mm')}</span>
                              <span><EnvironmentOutlined /> {event.location}</span>
                            </Space>
                          </div>
                        </div>
                      ),
                    }))}
                  />
                </div>
              ) : (
                <Empty description="Select a shipment or enter tracking number to view details" />
              )}
            </Spin>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default LogisticsTrack;
