import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Modal,
  Descriptions,
  Divider,
  message,
  Space,
  Tag,
  Row,
  Col,
  InputNumber,
  DatePicker,
  Tooltip,
  Badge,
  Statistic,
} from 'antd';
import {
  FileTextOutlined,
  PlusOutlined,
  CalculatorOutlined,
  SendOutlined,
  HistoryOutlined,
  UserOutlined,
  ShoppingOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { b2bTradeDataSource, Customer, Product } from '@/services/b2bTradeDataSource';

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

interface ProductFormData {
  suggestedPrice: number;
  moq: number;
  stock: number;
}

interface QuoteItem {
  key: string;
  productId: string;
  sku: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  discount: number;
  totalPrice: number;
  note?: string;
}

interface Quotation {
  id: string;
  quoteId: string;
  customerId: string;
  customerName: string;
  status: 'DRAFT' | 'PENDING' | 'SENT' | 'ACCEPTED' | 'REJECTED' | 'EXPIRED';
  validUntil: string;
  totalAmount: number;
  currency: string;
  createdAt: string;
  items: QuoteItem[];
}

const QUOTE_STATUS_MAP: Record<string, { color: string; text: string }> = {
  DRAFT: { color: 'default', text: 'Draft' },
  PENDING: { color: 'processing', text: 'Pending' },
  SENT: { color: 'blue', text: 'Sent' },
  ACCEPTED: { color: 'success', text: 'Accepted' },
  REJECTED: { color: 'error', text: 'Rejected' },
  EXPIRED: { color: 'warning', text: 'Expired' },
};

const CUSTOMER_TIERS = [
  { value: 'BASIC', label: 'Basic', discount: 0 },
  { value: 'PRO', label: 'Pro', discount: 5 },
  { value: 'ENTERPRISE', label: 'Enterprise', discount: 10 },
];

const MIN_PROFIT_RATE = 15;

export const EnterpriseQuote: React.FC = () => {
  const [form] = Form.useForm();
  const [itemForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [quotations, setQuotations] = useState<Quotation[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [quoteItems, setQuoteItems] = useState<QuoteItem[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState<Quotation | null>(null);
  const [addProductModalVisible, setAddProductModalVisible] = useState(false);
  const [stats, setStats] = useState({
    total: 0,
    pending: 0,
    accepted: 0,
    totalAmount: 0,
  });

  useEffect(() => {
    fetchQuotations();
    fetchCustomers();
    fetchProducts();
  }, []);

  const fetchQuotations = async () => {
    setLoading(true);
    try {
      const mockQuotations: Quotation[] = [
        {
          id: '1',
          quoteId: 'QT-2026-001',
          customerId: 'CUST_001',
          customerName: 'ABC Trading Co.',
          status: 'SENT',
          validUntil: '2026-04-18',
          totalAmount: 15000.00,
          currency: 'USD',
          createdAt: '2026-03-18 10:00:00',
          items: [],
        },
        {
          id: '2',
          quoteId: 'QT-2026-002',
          customerId: 'CUST_002',
          customerName: 'XYZ Electronics Ltd.',
          status: 'PENDING',
          validUntil: '2026-04-15',
          totalAmount: 28500.00,
          currency: 'USD',
          createdAt: '2026-03-17 14:30:00',
          items: [],
        },
        {
          id: '3',
          quoteId: 'QT-2026-003',
          customerId: 'CUST_003',
          customerName: 'Global Import Inc.',
          status: 'ACCEPTED',
          validUntil: '2026-04-10',
          totalAmount: 42000.00,
          currency: 'USD',
          createdAt: '2026-03-15 09:00:00',
          items: [],
        },
      ];
      setQuotations(mockQuotations);
      calculateStats(mockQuotations);
    } catch (error) {
      message.error('Failed to load quotations');
    } finally {
      setLoading(false);
    }
  };

  const fetchCustomers = async () => {
    const mockCustomers: Customer[] = [
      { id: 'CUST_001', name: 'ABC Trading Co.', email: 'contact@abc.com', company: 'ABC Trading', tier: 'ENTERPRISE' },
      { id: 'CUST_002', name: 'XYZ Electronics Ltd.', email: 'sales@xyz.com', company: 'XYZ Electronics', tier: 'PRO' },
      { id: 'CUST_003', name: 'Global Import Inc.', email: 'info@global.com', company: 'Global Import', tier: 'ENTERPRISE' },
    ];
    setCustomers(mockCustomers);
  };

  const fetchProducts = async () => {
    const mockProducts: Product[] = [
      { id: 'PROD_001', sku: 'SKU-001', name: 'Wireless Headphones', costPrice: 15.00, suggestedPrice: 25.00, moq: 100, stock: 5000 },
      { id: 'PROD_002', sku: 'SKU-002', name: 'USB-C Cable', costPrice: 2.50, suggestedPrice: 5.00, moq: 500, stock: 10000 },
      { id: 'PROD_003', sku: 'SKU-003', name: 'Phone Case', costPrice: 3.00, suggestedPrice: 8.00, moq: 200, stock: 8000 },
    ];
    setProducts(mockProducts);
  };

  const calculateStats = (quotes: Quotation[]) => {
    setStats({
      total: quotes.length,
      pending: quotes.filter((q) => q.status === 'PENDING' || q.status === 'SENT').length,
      accepted: quotes.filter((q) => q.status === 'ACCEPTED').length,
      totalAmount: quotes.filter((q) => q.status === 'ACCEPTED').reduce((sum, q) => sum + q.totalAmount, 0),
    });
  };

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

  const handleAddProduct = async () => {
    try {
      const values = await itemForm.validateFields();
      const product = products.find((p) => p.id === values.productId);
      if (!product) return;

      const tierDiscount = selectedCustomer
        ? CUSTOMER_TIERS.find((t) => t.value === selectedCustomer.tier)?.discount || 0
        : 0;
      const unitPrice = values.unitPrice || product.suggestedPrice;
      const discount = values.discount || tierDiscount;
      const totalPrice = unitPrice * values.quantity * (1 - discount / 100);

      const profitRate = ((unitPrice - product.costPrice) / product.costPrice) * 100;
      if (profitRate < MIN_PROFIT_RATE) {
        message.warning(`Warning: Profit rate (${profitRate.toFixed(1)}%) is below minimum (${MIN_PROFIT_RATE}%)`);
      }

      const newItem: QuoteItem = {
        key: Date.now().toString(),
        productId: product.id,
        sku: product.sku,
        productName: product.name,
        quantity: values.quantity,
        unitPrice,
        discount,
        totalPrice,
        note: values.note,
      };

      setQuoteItems([...quoteItems, newItem]);
      setAddProductModalVisible(false);
      itemForm.resetFields();
      message.success('Product added to quotation');
    } catch (error) {
      message.error('Failed to add product');
    }
  };

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

  const handleSubmitQuotation = async () => {
    try {
      const values = await form.validateFields();
      if (quoteItems.length === 0) {
        message.error('Please add at least one product');
        return;
      }

      setLoading(true);
      const totalAmount = quoteItems.reduce((sum, item) => sum + item.totalPrice, 0);

      const quotationData = {
        customerId: values.customerId,
        validUntil: values.validUntil,
        items: quoteItems,
        totalAmount,
        currency: 'USD',
        note: values.note,
      };

      console.log('Submitting quotation:', quotationData);

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

      message.success('Quotation created successfully');
      setCreateModalVisible(false);
      form.resetFields();
      setQuoteItems([]);
      setSelectedCustomer(null);
      fetchQuotations();
    } catch (error) {
      message.error('Failed to create quotation');
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetail = (quote: Quotation) => {
    setSelectedQuote(quote);
    setDetailModalVisible(true);
  };

  const handleSendQuote = async (quoteId: string) => {
    setLoading(true);
    try {
      console.log('Sending quotation:', quoteId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Quotation sent to customer');
      fetchQuotations();
    } catch (error) {
      message.error('Failed to send quotation');
    } finally {
      setLoading(false);
    }
  };

  const itemColumns: ColumnsType<QuoteItem> = [
    { title: 'SKU', dataIndex: 'sku', key: 'sku', width: 100 },
    { title: 'Product', dataIndex: 'productName', key: 'productName' },
    { title: 'Qty', dataIndex: 'quantity', key: 'quantity', width: 80 },
    {
      title: 'Unit Price',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Discount',
      dataIndex: 'discount',
      key: 'discount',
      width: 80,
      render: (discount: number) => `${discount}%`,
    },
    {
      title: 'Total',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Action',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button type="link" danger onClick={() => handleRemoveItem(record.key)}>
          Remove
        </Button>
      ),
    },
  ];

  const quoteColumns: ColumnsType<Quotation> = [
    {
      title: 'Quote ID',
      dataIndex: 'quoteId',
      key: 'quoteId',
      width: 130,
      render: (text: string, record) => (
        <a onClick={() => handleViewDetail(record)}>{text}</a>
      ),
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 180,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const config = QUOTE_STATUS_MAP[status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount: number) => (
        <span style={{ fontWeight: 'bold' }}>${amount.toFixed(2)}</span>
      ),
    },
    {
      title: 'Valid Until',
      dataIndex: 'validUntil',
      key: 'validUntil',
      width: 120,
    },
    {
      title: 'Created',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 160,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="View Details">
            <Button type="link" icon={<FileTextOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          {(record.status === 'DRAFT' || record.status === 'PENDING') && (
            <Tooltip title="Send to Customer">
              <Button type="link" icon={<SendOutlined />} onClick={() => handleSendQuote(record.quoteId)} />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

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

  return (
    <div className="enterprise-quote-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Quotations" value={stats.total} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Pending"
              value={stats.pending}
              valueStyle={{ color: '#1890ff' }}
              prefix={<HistoryOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Accepted"
              value={stats.accepted}
              valueStyle={{ color: '#52c41a' }}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Amount"
              value={stats.totalAmount}
              precision={2}
              prefix="$"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="Enterprise Quotations"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
            Create Quotation
          </Button>
        }
      >
        <Table
          columns={quoteColumns}
          dataSource={quotations}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1000 }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} quotations`,
          }}
        />
      </Card>

      <Modal
        title="Create New Quotation"
        open={createModalVisible}
        onCancel={() => {
          setCreateModalVisible(false);
          setQuoteItems([]);
          setSelectedCustomer(null);
        }}
        onOk={handleSubmitQuotation}
        confirmLoading={loading}
        width={900}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="customerId" label="Customer" rules={[{ required: true }]}>
                <Select
                  placeholder="Select customer"
                  showSearch
                  optionFilterProp="children"
                  onChange={handleCustomerChange}
                >
                  {customers.map((c) => (
                    <Option key={c.id} value={c.id}>
                      {c.name} ({c.company})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="validUntil" label="Valid Until" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          {selectedCustomer && (
            <Card size="small" style={{ marginBottom: 16, background: '#f5f5f5' }}>
              <Descriptions column={3} size="small">
                <Descriptions.Item label="Tier">
                  <Tag color={selectedCustomer.tier === 'ENTERPRISE' ? 'gold' : 'blue'}>
                    {selectedCustomer.tier}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Default Discount">
                  {CUSTOMER_TIERS.find((t) => t.value === selectedCustomer.tier)?.discount}%
                </Descriptions.Item>
                <Descriptions.Item label="Email">{selectedCustomer.email}</Descriptions.Item>
              </Descriptions>
            </Card>
          )}

          <Divider>Products</Divider>

          <div style={{ marginBottom: 16 }}>
            <Button icon={<PlusOutlined />} onClick={() => setAddProductModalVisible(true)}>
              Add Product
            </Button>
          </div>

          <Table
            columns={itemColumns}
            dataSource={quoteItems}
            rowKey="key"
            pagination={false}
            size="small"
            summary={() => (
              <Table.Summary.Row>
                <Table.Summary.Cell index={0} colSpan={5} align="right">
                  <strong>Total:</strong>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={1}>
                  <strong>${totalAmount.toFixed(2)}</strong>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={2} />
              </Table.Summary.Row>
            )}
          />

          <Form.Item name="note" label="Note" style={{ marginTop: 16 }}>
            <TextArea rows={2} placeholder="Add notes (optional)" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Add Product"
        open={addProductModalVisible}
        onCancel={() => setAddProductModalVisible(false)}
        onOk={handleAddProduct}
        width={600}
      >
        <Form form={itemForm} layout="vertical">
          <Form.Item name="productId" label="Product" rules={[{ required: true }]}>
            <Select placeholder="Select product" showSearch optionFilterProp="children">
              {products.map((p) => (
                <Option key={p.id} value={p.id}>
                  {p.sku} - {p.name} (Cost: ${p.costPrice}, Suggested: ${p.suggestedPrice}, MOQ: {p.moq})
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="quantity" label="Quantity" rules={[{ required: true }]}>
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="unitPrice" label="Unit Price ($)" rules={[{ required: true }]}>
                <InputNumber min={0} precision={2} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="discount" label="Discount (%)">
                <InputNumber min={0} max={100} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="note" label="Note">
            <Input placeholder="Item note (optional)" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Quotation Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={700}
      >
        {selectedQuote && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="Quote ID">{selectedQuote.quoteId}</Descriptions.Item>
            <Descriptions.Item label="Status">
              <Tag color={QUOTE_STATUS_MAP[selectedQuote.status].color}>
                {QUOTE_STATUS_MAP[selectedQuote.status].text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="Customer">{selectedQuote.customerName}</Descriptions.Item>
            <Descriptions.Item label="Currency">{selectedQuote.currency}</Descriptions.Item>
            <Descriptions.Item label="Total Amount" span={2}>
              <span style={{ fontSize: 18, fontWeight: 'bold', color: '#1890ff' }}>
                ${selectedQuote.totalAmount.toFixed(2)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="Valid Until">{selectedQuote.validUntil}</Descriptions.Item>
            <Descriptions.Item label="Created">{selectedQuote.createdAt}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default EnterpriseQuote;
