import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Descriptions,
  Divider,
  message,
  Tag,
  Steps,
  Result,
  Row,
  Col,
  Statistic,
  Alert,
} from 'antd';
import {
  ShoppingCartOutlined,
  PlusOutlined,
  DeleteOutlined,
  SaveOutlined,
  SendOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  SyncOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { b2bTradeDataSource, BatchOrderItem, BatchOrder as B2BBatchOrder } from '@/services/b2bTradeDataSource';

const { Option } = Select;

interface OrderItem {
  key: string;
  productId: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
}

interface BatchOrderFormData {
  totalAmount: number;
  status: 'DRAFT' | 'SUBMITTED' | 'PROCESSING' | 'CONFIRMED' | 'SHIPPED' | 'COMPLETED' | 'CANCELLED';
  createdAt: string;
  estimatedDelivery?: string;
  shippingAddress?: string;
  remark?: string;
}

const MOCK_PRODUCTS = [
  { id: 'P001', name: 'Industrial Sensor A', price: 150.00, stock: 1000 },
  { id: 'P002', name: 'Control Module B', price: 280.00, stock: 500 },
  { id: 'P003', name: 'Power Supply Unit C', price: 95.00, stock: 2000 },
  { id: 'P004', name: 'Communication Gateway D', price: 420.00, stock: 300 },
  { id: 'P005', name: 'Display Panel E', price: 185.00, stock: 800 },
];

const MOCK_CUSTOMERS = [
  { id: 'C001', name: 'TechCorp Industries', contact: 'John Smith', phone: '+1-555-0101', address: '123 Industrial Ave, Los Angeles, CA' },
  { id: 'C002', name: 'Global Manufacturing Co', contact: 'Jane Doe', phone: '+1-555-0102', address: '456 Factory Rd, Chicago, IL' },
  { id: 'C003', name: 'Smart Factory Solutions', contact: 'Mike Johnson', phone: '+1-555-0103', address: '789 Tech Park, Seattle, WA' },
];

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  DRAFT: { color: 'default', text: 'Draft', icon: <ClockCircleOutlined /> },
  SUBMITTED: { color: 'processing', text: 'Submitted', icon: <SendOutlined /> },
  PROCESSING: { color: 'processing', text: 'Processing', icon: <SyncOutlined /> },
  CONFIRMED: { color: 'blue', text: 'Confirmed', icon: <CheckCircleOutlined /> },
  SHIPPED: { color: 'cyan', text: 'Shipped', icon: <SendOutlined /> },
  COMPLETED: { color: 'green', text: 'Completed', icon: <CheckCircleOutlined /> },
  CANCELLED: { color: 'red', text: 'Cancelled', icon: <DeleteOutlined /> },
};

export const BatchOrder: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const [orders, setOrders] = useState<B2BBatchOrder[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<any>(null);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedOrder, setSelectedOrder] = useState<B2BBatchOrder | null>(null);
  const [currentStep, setCurrentStep] = useState(0);

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

  const fetchOrders = async () => {
    setLoading(true);
    try {
      const mockOrders: B2BBatchOrder[] = [
        {
          id: 'BO-2026-001',
          customerId: 'C001',
          customerName: 'TechCorp Industries',
          items: [
            { key: '1', productId: 'P001', productName: 'Industrial Sensor A', quantity: 50, unitPrice: 142.50, totalPrice: 7125 },
            { key: '2', productId: 'P002', productName: 'Control Module B', quantity: 20, unitPrice: 266.00, totalPrice: 5320 },
          ],
          totalAmount: 12445,
          status: 'PROCESSING',
          createdAt: '2026-03-17 14:30:00',
          estimatedDelivery: '2026-03-25',
        },
        {
          id: 'BO-2026-002',
          customerId: 'C002',
          customerName: 'Global Manufacturing Co',
          items: [
            { key: '1', productId: 'P003', productName: 'Power Supply Unit C', quantity: 100, unitPrice: 85.50, totalPrice: 8550 },
          ],
          totalAmount: 8550,
          status: 'CONFIRMED',
          createdAt: '2026-03-16 10:00:00',
          estimatedDelivery: '2026-03-23',
        },
        {
          id: 'BO-2026-003',
          customerId: 'C003',
          customerName: 'Smart Factory Solutions',
          items: [
            { key: '1', productId: 'P004', productName: 'Communication Gateway D', quantity: 30, unitPrice: 399.00, totalPrice: 11970 },
            { key: '2', productId: 'P005', productName: 'Display Panel E', quantity: 50, unitPrice: 175.75, totalPrice: 8787.50 },
          ],
          totalAmount: 20757.50,
          status: 'COMPLETED',
          createdAt: '2026-03-10 09:15:00',
          estimatedDelivery: '2026-03-18',
        },
      ];
      setOrders(mockOrders);
    } finally {
      setLoading(false);
    }
  };

  const handleCustomerChange = (customerId: string) => {
    const customer = MOCK_CUSTOMERS.find(c => c.id === customerId);
    setSelectedCustomer(customer || null);
  };

  const handleAddItem = () => {
    const values = form.getFieldsValue(['newProductId', 'newQuantity']);
    if (!values.newProductId || !values.newQuantity) {
      message.error('Please select product and enter quantity');
      return;
    }

    const product = MOCK_PRODUCTS.find(p => p.id === values.newProductId);
    if (!product) return;

    if (values.newQuantity > product.stock) {
      message.error(`Insufficient stock. Available: ${product.stock}`);
      return;
    }

    const newItem: OrderItem = {
      key: `${values.newProductId}-${Date.now()}`,
      productId: product.id,
      productName: product.name,
      quantity: values.newQuantity,
      unitPrice: product.price,
      totalPrice: product.price * values.newQuantity,
    };

    setOrderItems([...orderItems, newItem]);
    form.setFieldsValue({ newProductId: undefined, newQuantity: undefined });
  };

  const handleRemoveItem = (key: string) => {
    setOrderItems(orderItems.filter(item => item.key !== key));
  };

  const handleCreateOrder = async () => {
    if (!selectedCustomer) {
      message.error('Please select a customer');
      return;
    }
    if (orderItems.length === 0) {
      message.error('Please add at least one item');
      return;
    }

    setLoading(true);
    try {
      const newOrder: B2BBatchOrder = {
        id: `BO-${Date.now()}`,
        customerId: selectedCustomer.id,
        customerName: selectedCustomer.name,
        items: orderItems,
        totalAmount: orderItems.reduce((sum, item) => sum + item.totalPrice, 0),
        status: 'DRAFT',
        createdAt: new Date().toISOString(),
      };

      setOrders([newOrder, ...orders]);
      message.success('Order created successfully');
      setCreateModalVisible(false);
      setOrderItems([]);
      setSelectedCustomer(null);
      form.resetFields();
    } finally {
      setLoading(false);
    }
  };

  const handleSubmitOrder = async (orderId: string) => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      setOrders(orders.map(o => o.id === orderId ? { ...o, status: 'SUBMITTED' as const } : o));
      message.success('Order submitted successfully');
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (order: B2BBatchOrder) => {
    setSelectedOrder(order);
    setDetailModalVisible(true);
  };

  const columns: ColumnsType<B2BBatchOrder> = [
    {
      title: 'Order ID',
      dataIndex: 'id',
      key: 'id',
      width: 140,
      render: (id: string) => <a onClick={() => handleViewDetail(orders.find(o => o.id === id)!)}>{id}</a>,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 180,
    },
    {
      title: 'Items',
      dataIndex: 'items',
      key: 'items',
      width: 80,
      render: (items: OrderItem[]) => `${items.length} items`,
    },
    {
      title: 'Total Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount: number) => <strong>${amount.toLocaleString()}</strong>,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 120,
      render: (status: string) => {
        const config = STATUS_CONFIG[status];
        return <Tag color={config.color} icon={config.icon}>{config.text}</Tag>;
      },
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: 'Est. Delivery',
      dataIndex: 'estimatedDelivery',
      key: 'estimatedDelivery',
      width: 120,
    },
    {
      title: 'Actions',
      key: 'actions',
      width: 150,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleViewDetail(record)}>View</Button>
          {record.status === 'DRAFT' && (
            <Button type="link" onClick={() => handleSubmitOrder(record.id)}>Submit</Button>
          )}
        </Space>
      ),
    },
  ];

  const orderColumns: ColumnsType<OrderItem> = [
    { title: 'Product ID', dataIndex: 'productId', key: 'productId' },
    { title: 'Product Name', dataIndex: 'productName', key: 'productName' },
    { title: 'Quantity', dataIndex: 'quantity', key: 'quantity' },
    { title: 'Unit Price', dataIndex: 'unitPrice', key: 'unitPrice', render: (p: number) => `$${p.toFixed(2)}` },
    { title: 'Total', dataIndex: 'totalPrice', key: 'totalPrice', render: (t: number) => <strong>${t.toFixed(2)}</strong> },
    {
      title: 'Action',
      key: 'action',
      render: (_, record) => (
        <Button type="link" danger icon={<DeleteOutlined />} onClick={() => handleRemoveItem(record.key)} />
      ),
    },
  ];

  const totalAmount = orderItems.reduce((sum, item) => sum + item.totalPrice, 0);

  return (
    <div className="batch-order-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Orders" value={orders.length} prefix={<ShoppingCartOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Processing" 
              value={orders.filter(o => o.status === 'PROCESSING' || o.status === 'SUBMITTED').length} 
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Completed" 
              value={orders.filter(o => o.status === 'COMPLETED').length} 
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="Total Amount" 
              value={orders.reduce((sum, o) => sum + o.totalAmount, 0)} 
              precision={2} 
              prefix="$" 
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      <Card title="Batch Order Management" extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
          Create Order
        </Button>
      }>
        <Table
          columns={columns}
          dataSource={orders}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="Create Batch Order"
        open={createModalVisible}
        onCancel={() => { setCreateModalVisible(false); setOrderItems([]); }}
        footer={null}
        width={800}
      >
        <Steps current={currentStep} style={{ marginBottom: 24 }}>
          <Steps.Step title="Customer Info" />
          <Steps.Step title="Order Items" />
          <Steps.Step title="Confirm" />
        </Steps>

        {currentStep === 0 && (
          <Form form={form} layout="vertical">
            <Form.Item name="customerId" label="Customer" rules={[{ required: true }]}>
              <Select placeholder="Select Customer" onChange={handleCustomerChange}>
                {MOCK_CUSTOMERS.map(c => (
                  <Option key={c.id} value={c.id}>{c.name}</Option>
                ))}
              </Select>
            </Form.Item>
            {selectedCustomer && (
              <Alert
                type="info"
                message={`Contact: ${selectedCustomer.contact} | Phone: ${selectedCustomer.phone}`}
                description={`Address: ${selectedCustomer.address}`}
                style={{ marginBottom: 16 }}
              />
            )}
            <div style={{ textAlign: 'right' }}>
              <Button type="primary" onClick={() => setCurrentStep(1)} disabled={!selectedCustomer}>
                Next
              </Button>
            </div>
          </Form>
        )}

        {currentStep === 1 && (
          <>
            <Form form={form} layout="horizontal">
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item name="newProductId" label="Product">
                    <Select placeholder="Select Product">
                      {MOCK_PRODUCTS.map(p => (
                        <Option key={p.id} value={p.id}>{p.id} - {p.name} ($ {p.price.toFixed(2)})</Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item name="newQuantity" label="Quantity">
                    <InputNumber min={1} style={{ width: '100%' }} />
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label=" ">
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleAddItem}>Add</Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>

            <Table columns={orderColumns} dataSource={orderItems} pagination={false} size="small" />

            <Divider>Total: ${totalAmount.toFixed(2)}</Divider>

            <div style={{ textAlign: 'right', marginTop: 16 }}>
              <Button onClick={() => setCurrentStep(0)}>Back</Button>
              <Button type="primary" onClick={() => setCurrentStep(2)} disabled={orderItems.length === 0} style={{ marginLeft: 8 }}>
                Next
              </Button>
            </div>
          </>
        )}

        {currentStep === 2 && (
          <>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="Customer">{selectedCustomer?.name}</Descriptions.Item>
              <Descriptions.Item label="Contact">{selectedCustomer?.contact}</Descriptions.Item>
              <Descriptions.Item label="Phone">{selectedCustomer?.phone}</Descriptions.Item>
              <Descriptions.Item label="Address">{selectedCustomer?.address}</Descriptions.Item>
              <Descriptions.Item label="Items">{orderItems.length} items</Descriptions.Item>
              <Descriptions.Item label="Total Amount">
                <strong style={{ fontSize: 18, color: '#1890ff' }}>${totalAmount.toFixed(2)}</strong>
              </Descriptions.Item>
            </Descriptions>

            <div style={{ textAlign: 'right', marginTop: 24 }}>
              <Button onClick={() => setCurrentStep(1)}>Back</Button>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleCreateOrder} loading={loading} style={{ marginLeft: 8 }}>
                Create Order
              </Button>
            </div>
          </>
        )}
      </Modal>

      <Modal
        title="Order Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>Close</Button>,
        ]}
        width={700}
      >
        {selectedOrder && (
          <>
            <Descriptions bordered column={2} style={{ marginBottom: 24 }}>
              <Descriptions.Item label="Order ID">{selectedOrder.id}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={STATUS_CONFIG[selectedOrder.status].color}>
                  {STATUS_CONFIG[selectedOrder.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Customer">{selectedOrder.customerName}</Descriptions.Item>
              <Descriptions.Item label="Created">{selectedOrder.createdAt}</Descriptions.Item>
              <Descriptions.Item label="Est. Delivery">{selectedOrder.estimatedDelivery || '-'}</Descriptions.Item>
              <Descriptions.Item label="Total Amount">
                <strong style={{ fontSize: 16, color: '#1890ff' }}>${selectedOrder.totalAmount.toLocaleString()}</strong>
              </Descriptions.Item>
            </Descriptions>

            <Table
              columns={orderColumns.slice(0, -1)}
              dataSource={selectedOrder.items}
              pagination={false}
              size="small"
            />
          </>
        )}
      </Modal>
    </div>
  );
};

export default BatchOrder;
