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

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

type LogisticsChannel = 'EXPRESS' | 'STANDARD' | 'ECONOMY' | 'SPECIAL';

interface FreightCalculation {
  totalWithDuty: number;
}

interface ProductInfo {
  productId: string;
  name: string;
  weight: number;
  length: number;
  width: number;
  height: number;
  quantity: number;
  declaredValue: number;
  hsCode: string;
}

interface DestinationInfo {
  country: string;
  city: string;
  postalCode: string;
  isRemoteArea: boolean;
  customsRate: number;
}

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

const COUNTRIES = [
  { code: 'US', name: 'United States', customsRate: 0.06, remoteAreas: ['AK', 'HI', 'PR', 'VI'] },
  { code: 'GB', name: 'United Kingdom', customsRate: 0.12, remoteAreas: [] },
  { code: 'DE', name: 'Germany', customsRate: 0.19, remoteAreas: [] },
  { code: 'FR', name: 'France', customsRate: 0.20, remoteAreas: [] },
  { code: 'JP', name: 'Japan', customsRate: 0.08, remoteAreas: ['OKinawa', 'Hokkaido'] },
  { code: 'AU', name: 'Australia', customsRate: 0.10, remoteAreas: ['NT', 'TAS'] },
  { code: 'CA', name: 'Canada', customsRate: 0.05, remoteAreas: ['YT', 'NT', 'NU'] },
];

const CARRIERS = [
  {
    channel: 'EXPRESS',
    name: 'DHL Express',
    basePrice: 25.0,
    pricePerKg: 8.5,
    pricePerVol: 150,
    fuelRate: 0.15,
  },
  {
    channel: 'EXPRESS',
    name: 'FedEx',
    basePrice: 22.0,
    pricePerKg: 7.8,
    pricePerVol: 140,
    fuelRate: 0.12,
  },
  {
    channel: 'STANDARD',
    name: 'UPS',
    basePrice: 15.0,
    pricePerKg: 5.5,
    pricePerVol: 100,
    fuelRate: 0.10,
  },
  {
    channel: 'STANDARD',
    name: 'TNT',
    basePrice: 14.0,
    pricePerKg: 5.0,
    pricePerVol: 95,
    fuelRate: 0.10,
  },
  {
    channel: 'ECONOMY',
    name: 'China Post',
    basePrice: 5.0,
    pricePerKg: 2.0,
    pricePerVol: 40,
    fuelRate: 0.05,
  },
  {
    channel: 'ECONOMY',
    name: 'Sea Freight',
    basePrice: 50.0,
    pricePerKg: 0.8,
    pricePerVol: 15,
    fuelRate: 0.08,
  },
  {
    channel: 'SPECIAL',
    name: '4PX Special Line',
    basePrice: 12.0,
    pricePerKg: 4.0,
    pricePerVol: 80,
    fuelRate: 0.08,
  },
];

export const FreightCalc: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [quotes, setQuotes] = useState<FreightQuote[]>([]);
  const [selectedCountry, setSelectedCountry] = useState<string>('');
  const [isRemoteArea, setIsRemoteArea] = useState(false);
  const [totalWeight, setTotalWeight] = useState(0);
  const [totalVolume, setTotalVolume] = useState(0);
  const [totalDeclaredValue, setTotalDeclaredValue] = useState(0);

  useEffect(() => {
    const values = form.getFieldsValue();
    calculateTotals(values);
  }, []);

  const calculateTotals = (values: any) => {
    const products = values.products || [];
    const weight = products.reduce((sum: number, p: ProductInfo) => sum + (p.weight || 0) * (p.quantity || 1), 0);
    const volume = products.reduce((sum: number, p: ProductInfo) => 
      sum + ((p.length || 0) * (p.width || 0) * (p.height || 0) / 1000000) * (p.quantity || 1), 0
    );
    const value = products.reduce((sum: number, p: ProductInfo) => sum + (p.declaredValue || 0) * (p.quantity || 1), 0);
    
    setTotalWeight(weight);
    setTotalVolume(volume);
    setTotalDeclaredValue(value);
  };

  const handleCalculate = async () => {
    const values = await form.validateFields();
    const { country, products, isInsured } = values;

    const countryInfo = COUNTRIES.find(c => c.code === country);
    if (!countryInfo) {
      message.error('Please select a destination country');
      return;
    }

    if (!products || products.length === 0) {
      message.error('Please add at least one product');
      return;
    }

    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));

      const calculatedQuotes: FreightQuote[] = CARRIERS.map(carrier => {
        const weightCharge = Math.max(totalWeight, totalVolume * 167) * carrier.pricePerVol / carrier.pricePerVol * carrier.pricePerKg;
        const baseFreight = carrier.basePrice + weightCharge;
        const fuelSurcharge = baseFreight * carrier.fuelRate;
        const remoteSurcharge = isRemoteArea ? baseFreight * 0.25 : 0;
        const customsDuty = totalDeclaredValue * (countryInfo.customsRate / 100);
        const insurance = isInsured ? Math.max(totalDeclaredValue * 0.005, 10) : 0;
        const subtotal = baseFreight + fuelSurcharge + remoteSurcharge;
        const totalWithDuty = subtotal + customsDuty + insurance;

        return {
          id: `QUOTE-${carrier.channel}-${Date.now()}`,
          channel: carrier.channel,
          carrier: carrier.name,
          name: carrier.name,
          basePrice: carrier.basePrice,
          pricePerKg: carrier.pricePerKg,
          pricePerVol: carrier.pricePerVol,
          estimatedDays: carrier.channel === 'EXPRESS' ? 3 + Math.floor(Math.random() * 3) :
                        carrier.channel === 'STANDARD' ? 7 + Math.floor(Math.random() * 5) :
                        carrier.channel === 'ECONOMY' ? 15 + Math.floor(Math.random() * 10) : 10,
          totalPrice: Number(subtotal.toFixed(2)),
          fuelSurcharge: Number(fuelSurcharge.toFixed(2)),
          remoteAreaSurcharge: Number(remoteSurcharge.toFixed(2)),
          customsDuty: Number(customsDuty.toFixed(2)),
          insurance: Number(insurance.toFixed(2)),
          totalWithDuty: Number(totalWithDuty.toFixed(2)),
        };
      });

      calculatedQuotes.sort((a, b) => a.totalWithDuty - b.totalWithDuty);
      setQuotes(calculatedQuotes);
    } catch (error) {
      message.error('Failed to calculate freight');
    } finally {
      setLoading(false);
    }
  };

  const handleCountryChange = (countryCode: string) => {
    setSelectedCountry(countryCode);
    const countryInfo = COUNTRIES.find(c => c.code === countryCode);
    if (countryInfo && countryInfo.remoteAreas.length > 0) {
      setIsRemoteArea(false);
    }
  };

  const columns: ColumnsType<FreightQuote> = [
    {
      title: 'Carrier',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (name: string, record) => (
        <Space direction="vertical" size={0}>
          <strong>{name}</strong>
          <Tag color={CHANNEL_COLORS[record.channel]}>{record.channel}</Tag>
        </Space>
      ),
    },
    {
      title: 'Est. Days',
      dataIndex: 'estimatedDays',
      key: 'estimatedDays',
      width: 100,
      render: (days: number) => `${days} days`,
    },
    {
      title: 'Base Freight',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 120,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Fuel Surcharge',
      dataIndex: 'fuelSurcharge',
      key: 'fuelSurcharge',
      width: 120,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Remote Area',
      dataIndex: 'remoteAreaSurcharge',
      key: 'remoteAreaSurcharge',
      width: 100,
      render: (price: number) => price > 0 ? `$${price.toFixed(2)}` : '-',
    },
    {
      title: 'Customs Duty',
      dataIndex: 'customsDuty',
      key: 'customsDuty',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Insurance',
      dataIndex: 'insurance',
      key: 'insurance',
      width: 80,
      render: (price: number) => price > 0 ? `$${price.toFixed(2)}` : '-',
    },
    {
      title: 'Total',
      dataIndex: 'totalWithDuty',
      key: 'totalWithDuty',
      width: 120,
      render: (price: number, record, index) => (
        <strong style={{ 
          color: index === 0 ? '#52c41a' : '#1890ff',
          fontSize: index === 0 ? 16 : 14 
        }}>
          ${price.toFixed(2)}
          {index === 0 && <Tag color="green" style={{ marginLeft: 8 }}>Best</Tag>}
        </strong>
      ),
    },
  ];

  const countryInfo = COUNTRIES.find(c => c.code === selectedCountry);

  return (
    <div className="freight-calc-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Weight"
              value={totalWeight}
              suffix="kg"
              prefix={<WeightOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Volume"
              value={totalVolume}
              suffix="m³"
              prefix={<TruckOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Declared Value"
              value={totalDeclaredValue}
              precision={2}
              prefix="$"
              prefixIcon={<DollarOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Quotes Received"
              value={quotes.length}
              prefix={<CalculateOutlined />}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Freight Calculator" style={{ marginBottom: 16 }}>
        <Form form={form} layout="vertical" onValuesChange={calculateTotals}>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="country"
                label="Destination Country"
                rules={[{ required: true, message: 'Please select country' }]}
              >
                <Select placeholder="Select country" onChange={handleCountryChange}>
                  {COUNTRIES.map(country => (
                    <Option key={country.code} value={country.code}>
                      {country.name} (Duty: {country.customsRate}%)
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="city" label="City">
                <Input placeholder="Enter city" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="postalCode" label="Postal Code">
                <Input placeholder="Enter postal code" />
              </Form.Item>
            </Col>
          </Row>

          {countryInfo && countryInfo.remoteAreas.length > 0 && (
            <Alert
              message={
                <Space>
                  <InfoCircleOutlined />
                  <span>
                    Remote areas for {countryInfo.name}: {countryInfo.remoteAreas.join(', ')}
                  </span>
                </Space>
              }
              type="info"
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          <Form.Item
            name="isRemoteArea"
            label="Remote Area Surcharge"
            valuePropName="checked"
          >
            <Radio.Group>
              <Radio value={false}>Regular Area</Radio>
              <Radio value={true}>Remote Area (+25%)</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="isInsured"
            label="Insurance"
            valuePropName="checked"
          >
            <Radio.Group>
              <Radio value={false}>No Insurance</Radio>
              <Radio value={true}>With Insurance (0.5%, min $10)</Radio>
            </Radio.Group>
          </Form.Item>

          <Divider>Product Information</Divider>

          <Form.List name="products" initialValue={[{}]}>
            {(fields, { add, remove }) => (
              <>
                {fields.map(({ key, name, ...restField }) => (
                  <Row key={key} gutter={16} align="middle">
                    <Col span={4}>
                      <Form.Item
                        {...restField}
                        name={[name, 'productId']}
                        label="Product ID"
                      >
                        <Input placeholder="ID" />
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Form.Item
                        {...restField}
                        name={[name, 'quantity']}
                        label="Qty"
                      >
                        <InputNumber min={1} placeholder="1" style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Form.Item
                        {...restField}
                        name={[name, 'weight']}
                        label="Weight(kg)"
                      >
                        <InputNumber min={0.1} step={0.1} placeholder="0.5" style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Form.Item
                        {...restField}
                        name={[name, 'length']}
                        label="L(cm)"
                      >
                        <InputNumber min={1} placeholder="10" style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Form.Item
                        {...restField}
                        name={[name, 'width']}
                        label="W(cm)"
                      >
                        <InputNumber min={1} placeholder="10" style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Form.Item
                        {...restField}
                        name={[name, 'height']}
                        label="H(cm)"
                      >
                        <InputNumber min={1} placeholder="10" style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={3}>
                      <Form.Item
                        {...restField}
                        name={[name, 'declaredValue']}
                        label="Value($)"
                      >
                        <InputNumber min={0} placeholder="0" style={{ width: '100%' }} />
                      </Form.Item>
                    </Col>
                    <Col span={2}>
                      <Button type="link" danger onClick={() => remove(name)}>
                        Remove
                      </Button>
                    </Col>
                  </Row>
                ))}
                <Form.Item>
                  <Button type="dashed" onClick={() => add()} style={{ width: '100%' }}>
                    + Add Product
                  </Button>
                </Form.Item>
              </>
            )}
          </Form.List>

          <Form.Item>
            <Button 
              type="primary" 
              icon={<CalculateOutlined />} 
              onClick={handleCalculate}
              loading={loading}
              size="large"
            >
              Calculate Freight
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {quotes.length > 0 && (
        <Card title="Freight Quotes">
          <Table
            columns={columns}
            dataSource={quotes}
            rowKey="id"
            pagination={false}
            scroll={{ x: 1100 }}
          />
        </Card>
      )}
    </div>
  );
};

export default FreightCalc;
