import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  Select,
  Radio,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  message,
  Descriptions,
  Divider,
  Alert,
  Badge,
  Steps,
} from 'antd';
import {
  TruckOutlined,
  ClockCircleOutlined,
  DollarOutlined,
  EnvironmentOutlined,
  CheckCircleOutlined,
  InfoCircleOutlined,
  ThunderboltOutlined,
  SafetyOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { logisticsDataSource, Shipment } from '@/services/logisticsDataSource';

const { Option } = Select;

type LogisticsChannel = 'EXPRESS' | 'STANDARD' | 'ECONOMY' | 'SPECIAL';
type LogisticsStatus = 'AVAILABLE' | 'UNAVAILABLE' | 'LIMITED';

interface LogisticsOption {
  id: string;
  channel: LogisticsChannel;
  name: string;
  carrier: string;
  estimatedDays: number;
  basePrice: number;
  pricePerKg: number;
  minWeight: number;
  maxWeight: number;
  status: LogisticsStatus;
  features: string[];
  trackingAvailable: boolean;
  insuranceAvailable: boolean;
}

interface OrderInfo {
  orderId: string;
  destination: string;
  country: string;
  weight: number;
  volume: number;
  productType: string;
  declaredValue: number;
}

interface SelectedLogistics {
  orderId: string;
  logisticsId: string;
  logisticsName: string;
  carrier: string;
  estimatedDays: number;
  totalPrice: number;
  selectedAt: string;
}

const CHANNEL_COLORS: Record<LogisticsChannel, string> = {
  EXPRESS: 'red',
  STANDARD: 'blue',
  ECONOMY: 'green',
  SPECIAL: 'purple',
};

const CHANNEL_NAMES: Record<LogisticsChannel, string> = {
  EXPRESS: 'Express',
  STANDARD: 'Standard',
  ECONOMY: 'Economy',
  SPECIAL: 'Special Line',
};

const STATUS_COLORS: Record<LogisticsStatus, string> = {
  AVAILABLE: 'green',
  UNAVAILABLE: 'red',
  LIMITED: 'orange',
};

const MOCK_LOGISTICS_OPTIONS: LogisticsOption[] = [
  {
    id: 'LOG-001',
    channel: 'EXPRESS',
    name: 'DHL Express',
    carrier: 'DHL',
    estimatedDays: 3,
    basePrice: 25.0,
    pricePerKg: 8.5,
    minWeight: 0.5,
    maxWeight: 70,
    status: 'AVAILABLE',
    features: ['Door-to-door', 'Signature required', 'Real-time tracking'],
    trackingAvailable: true,
    insuranceAvailable: true,
  },
  {
    id: 'LOG-002',
    channel: 'EXPRESS',
    name: 'FedEx International Priority',
    carrier: 'FedEx',
    estimatedDays: 4,
    basePrice: 22.0,
    pricePerKg: 7.8,
    minWeight: 0.5,
    maxWeight: 68,
    status: 'AVAILABLE',
    features: ['Door-to-door', 'Customs clearance included'],
    trackingAvailable: true,
    insuranceAvailable: true,
  },
  {
    id: 'LOG-003',
    channel: 'STANDARD',
    name: 'UPS Standard',
    carrier: 'UPS',
    estimatedDays: 7,
    basePrice: 15.0,
    pricePerKg: 5.5,
    minWeight: 1,
    maxWeight: 70,
    status: 'AVAILABLE',
    features: ['Tracking available', 'Insurance optional'],
    trackingAvailable: true,
    insuranceAvailable: true,
  },
  {
    id: 'LOG-004',
    channel: 'ECONOMY',
    name: 'China Post Air Mail',
    carrier: 'China Post',
    estimatedDays: 20,
    basePrice: 5.0,
    pricePerKg: 2.0,
    minWeight: 0.1,
    maxWeight: 30,
    status: 'AVAILABLE',
    features: ['Budget friendly', 'Tracking limited'],
    trackingAvailable: false,
    insuranceAvailable: false,
  },
  {
    id: 'LOG-005',
    channel: 'SPECIAL',
    name: 'Special Line - US',
    carrier: '4PX',
    estimatedDays: 10,
    basePrice: 12.0,
    pricePerKg: 4.0,
    minWeight: 0.5,
    maxWeight: 30,
    status: 'LIMITED',
    features: ['US dedicated line', 'Fast customs clearance', 'Tax included'],
    trackingAvailable: true,
    insuranceAvailable: true,
  },
];

const MOCK_ORDERS: OrderInfo[] = [
  {
    orderId: 'ORD-2026-001',
    destination: 'Los Angeles, CA 90001',
    country: 'US',
    weight: 2.5,
    volume: 0.02,
    productType: 'Electronics',
    declaredValue: 150.0,
  },
  {
    orderId: 'ORD-2026-002',
    destination: 'London, UK',
    country: 'GB',
    weight: 1.2,
    volume: 0.01,
    productType: 'Clothing',
    declaredValue: 80.0,
  },
];

export const LogisticsSelect: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [logisticsOptions, setLogisticsOptions] = useState<LogisticsOption[]>(MOCK_LOGISTICS_OPTIONS);
  const [selectedOrder, setSelectedOrder] = useState<OrderInfo | null>(null);
  const [filteredOptions, setFilteredOptions] = useState<LogisticsOption[]>([]);
  const [selectedLogistics, setSelectedLogistics] = useState<LogisticsOption | null>(null);
  const [confirmModalVisible, setConfirmModalVisible] = useState(false);
  const [channelFilter, setChannelFilter] = useState<LogisticsChannel | 'all'>('all');
  const [resultModalVisible, setResultModalVisible] = useState(false);
  const [selectedResult, setSelectedResult] = useState<SelectedLogistics | null>(null);

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

  const loadLogisticsOptions = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setLogisticsOptions(MOCK_LOGISTICS_OPTIONS);
    } catch (error) {
      message.error('Failed to load logistics options');
    } finally {
      setLoading(false);
    }
  };

  const calculatePrice = (option: LogisticsOption, weight: number): number => {
    if (!selectedOrder) return 0;
    const basePrice = option.basePrice;
    const weightPrice = Math.max(0, weight - option.minWeight) * option.pricePerKg;
    return Number((basePrice + weightPrice).toFixed(2));
  };

  const handleOrderSelect = (order: OrderInfo) => {
    setSelectedOrder(order);
    const options = logisticsOptions.filter(opt => 
      opt.status !== 'UNAVAILABLE' &&
      order.weight >= opt.minWeight &&
      order.weight <= opt.maxWeight
    );
    setFilteredOptions(options);
    setSelectedLogistics(null);
  };

  const handleLogisticsSelect = (option: LogisticsOption) => {
    setSelectedLogistics(option);
  };

  const handleConfirmSelection = () => {
    if (!selectedOrder || !selectedLogistics) {
      message.warning('Please select order and logistics');
      return;
    }
    setConfirmModalVisible(true);
  };

  const handleConfirm = async () => {
    if (!selectedOrder || !selectedLogistics) return;

    setLoading(true);
    try {
      const result: SelectedLogistics = {
        orderId: selectedOrder.orderId,
        logisticsId: selectedLogistics.id,
        logisticsName: selectedLogistics.name,
        carrier: selectedLogistics.carrier,
        estimatedDays: selectedLogistics.estimatedDays,
        totalPrice: calculatePrice(selectedLogistics, selectedOrder.weight),
        selectedAt: new Date().toISOString(),
      };

      setSelectedResult(result);
      setConfirmModalVisible(false);
      setResultModalVisible(true);
      message.success('Logistics selected successfully');
    } catch (error) {
      message.error('Failed to select logistics');
    } finally {
      setLoading(false);
    }
  };

  const getFilteredByChannel = () => {
    if (channelFilter === 'all') return filteredOptions;
    return filteredOptions.filter(opt => opt.channel === channelFilter);
  };

  const columns: ColumnsType<LogisticsOption> = [
    {
      title: 'Channel',
      dataIndex: 'channel',
      key: 'channel',
      width: 100,
      render: (channel: LogisticsChannel) => (
        <Tag color={CHANNEL_COLORS[channel]}>{CHANNEL_NAMES[channel]}</Tag>
      ),
    },
    {
      title: 'Carrier',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name: string, record) => (
        <Space direction="vertical" size={0}>
          <strong>{name}</strong>
          <span style={{ fontSize: 12, color: '#888' }}>{record.carrier}</span>
        </Space>
      ),
    },
    {
      title: 'Est. Days',
      dataIndex: 'estimatedDays',
      key: 'estimatedDays',
      width: 100,
      render: (days: number) => (
        <Space>
          <ClockCircleOutlined />
          <span>{days} days</span>
        </Space>
      ),
    },
    {
      title: 'Price',
      key: 'price',
      width: 120,
      render: (_, record) => {
        const price = selectedOrder ? calculatePrice(record, selectedOrder.weight) : 0;
        return (
          <strong style={{ color: '#1890ff' }}>
            ${price.toFixed(2)}
          </strong>
        );
      },
    },
    {
      title: 'Features',
      dataIndex: 'features',
      key: 'features',
      width: 250,
      render: (features: string[]) => (
        <Space wrap size={4}>
          {features.slice(0, 3).map((feature, index) => (
            <Tag key={index} style={{ fontSize: 11 }}>{feature}</Tag>
          ))}
        </Space>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: LogisticsStatus) => (
        <Badge 
          status={status === 'AVAILABLE' ? 'success' : status === 'LIMITED' ? 'warning' : 'error'} 
          text={status}
        />
      ),
    },
    {
      title: 'Action',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Radio
          checked={selectedLogistics?.id === record.id}
          onChange={() => handleLogisticsSelect(record)}
          disabled={record.status === 'UNAVAILABLE'}
        />
      ),
    },
  ];

  return (
    <div className="logistics-select-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Available Channels"
              value={logisticsOptions.filter(o => o.status === 'AVAILABLE').length}
              prefix={<TruckOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Express Options"
              value={logisticsOptions.filter(o => o.channel === 'EXPRESS').length}
              prefix={<ThunderboltOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="With Tracking"
              value={logisticsOptions.filter(o => o.trackingAvailable).length}
              prefix={<EnvironmentOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="With Insurance"
              value={logisticsOptions.filter(o => o.insuranceAvailable).length}
              prefix={<SafetyOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Step 1: Select Order" style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          {MOCK_ORDERS.map(order => (
            <Col span={12} key={order.orderId}>
              <Card
                hoverable
                onClick={() => handleOrderSelect(order)}
                style={{
                  border: selectedOrder?.orderId === order.orderId ? '2px solid #1890ff' : undefined,
                }}
              >
                <Descriptions column={2} size="small">
                  <Descriptions.Item label="Order ID">
                    <strong>{order.orderId}</strong>
                  </Descriptions.Item>
                  <Descriptions.Item label="Country">
                    <Tag>{order.country}</Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label="Destination" span={2}>
                    <EnvironmentOutlined /> {order.destination}
                  </Descriptions.Item>
                  <Descriptions.Item label="Weight">{order.weight} kg</Descriptions.Item>
                  <Descriptions.Item label="Value">${order.declaredValue}</Descriptions.Item>
                </Descriptions>
              </Card>
            </Col>
          ))}
        </Row>
      </Card>

      {selectedOrder && (
        <Card 
          title="Step 2: Select Logistics"
          extra={
            <Space>
              <Select
                value={channelFilter}
                onChange={setChannelFilter}
                style={{ width: 150 }}
              >
                <Option value="all">All Channels</Option>
                <Option value="EXPRESS">Express</Option>
                <Option value="STANDARD">Standard</Option>
                <Option value="ECONOMY">Economy</Option>
                <Option value="SPECIAL">Special Line</Option>
              </Select>
              <Button 
                type="primary" 
                onClick={handleConfirmSelection}
                disabled={!selectedLogistics}
              >
                Confirm Selection
              </Button>
            </Space>
          }
        >
          <Alert
            message={`Order: ${selectedOrder.orderId} | Weight: ${selectedOrder.weight}kg | Destination: ${selectedOrder.destination}`}
            type="info"
            showIcon
            style={{ marginBottom: 16 }}
          />

          <Table
            columns={columns}
            dataSource={getFilteredByChannel()}
            rowKey="id"
            loading={loading}
            pagination={false}
            scroll={{ x: 1000 }}
            onRow={(record) => ({
              onClick: () => record.status !== 'UNAVAILABLE' && handleLogisticsSelect(record),
              style: { cursor: record.status === 'UNAVAILABLE' ? 'not-allowed' : 'pointer' },
            })}
          />
        </Card>
      )}

      <Modal
        title="Confirm Logistics Selection"
        open={confirmModalVisible}
        onCancel={() => setConfirmModalVisible(false)}
        onOk={handleConfirm}
        confirmLoading={loading}
        okText="Confirm"
      >
        {selectedOrder && selectedLogistics && (
          <div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Order ID">{selectedOrder.orderId}</Descriptions.Item>
              <Descriptions.Item label="Destination">{selectedOrder.country}</Descriptions.Item>
              <Descriptions.Item label="Weight">{selectedOrder.weight} kg</Descriptions.Item>
              <Descriptions.Item label="Product">{selectedOrder.productType}</Descriptions.Item>
            </Descriptions>
            <Divider />
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Logistics">{selectedLogistics.name}</Descriptions.Item>
              <Descriptions.Item label="Carrier">{selectedLogistics.carrier}</Descriptions.Item>
              <Descriptions.Item label="Est. Delivery">{selectedLogistics.estimatedDays} days</Descriptions.Item>
              <Descriptions.Item label="Channel">
                <Tag color={CHANNEL_COLORS[selectedLogistics.channel]}>
                  {CHANNEL_NAMES[selectedLogistics.channel]}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Total Price" span={2}>
                <strong style={{ fontSize: 18, color: '#1890ff' }}>
                  ${calculatePrice(selectedLogistics, selectedOrder.weight).toFixed(2)}
                </strong>
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>

      <Modal
        title="Selection Confirmed"
        open={resultModalVisible}
        onCancel={() => setResultModalVisible(false)}
        footer={[
          <Button key="close" type="primary" onClick={() => setResultModalVisible(false)}>
            Done
          </Button>,
        ]}
      >
        {selectedResult && (
          <div>
            <div style={{ textAlign: 'center', marginBottom: 24 }}>
              <CheckCircleOutlined style={{ fontSize: 48, color: '#52c41a' }} />
              <h3 style={{ marginTop: 16 }}>Logistics Successfully Selected</h3>
            </div>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Order ID">{selectedResult.orderId}</Descriptions.Item>
              <Descriptions.Item label="Logistics">{selectedResult.logisticsName}</Descriptions.Item>
              <Descriptions.Item label="Carrier">{selectedResult.carrier}</Descriptions.Item>
              <Descriptions.Item label="Est. Delivery">{selectedResult.estimatedDays} days</Descriptions.Item>
              <Descriptions.Item label="Total Price">
                <strong style={{ color: '#1890ff' }}>${selectedResult.totalPrice.toFixed(2)}</strong>
              </Descriptions.Item>
              <Descriptions.Item label="Selected At">
                {dayjs(selectedResult.selectedAt).format('YYYY-MM-DD HH:mm:ss')}
              </Descriptions.Item>
            </Descriptions>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default LogisticsSelect;
