import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Descriptions,
  Divider,
  message,
  Tag,
  Tooltip,
  Row,
  Col,
  Statistic,
  Alert,
  Result,
} from 'antd';
import {
  DollarOutlined,
  FileTextOutlined,
  CalculatorOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;

interface QuoteItem {
  key: string;
  productId: string;
  productName: string;
  quantity: number;
  basePrice: number;
  unitPrice: number;
  discountPercent: number;
  totalAmount: number;
  profitMargin: number;
  isApproved: boolean;
  rejectionReason?: string;
}

interface Customer {
  id: string;
  name: string;
  creditLevel: string;
  creditLimit: number;
  usedCredit: number;
}

interface QuoteFormData {
  customerId: string;
  items: QuoteItem[];
  validUntil: string;
  remark: string;
}

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

const MOCK_CUSTOMERS: Customer[] = [
  { id: 'C001', name: 'TechCorp Industries', creditLevel: 'A', creditLimit: 100000, usedCredit: 25000 },
  { id: 'C002', name: 'Global Manufacturing Co', creditLevel: 'B', creditLimit: 50000, usedCredit: 15000 },
  { id: 'C003', name: 'Smart Factory Solutions', creditLevel: 'A', creditLimit: 200000, usedCredit: 80000 },
];

const CREDIT_LEVEL_COLORS: Record<string, string> = {
  A: 'green',
  B: 'blue',
  C: 'orange',
  D: 'red',
};

export const EnterpriseQuote: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [quoteItems, setQuoteItems] = useState<QuoteItem[]>([]);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [quoteModalVisible, setQuoteModalVisible] = useState(false);
  const [resultModalVisible, setResultModalVisible] = useState(false);
  const [quoteResult, setQuoteResult] = useState<any>(null);
  const [profitWarning, setProfitWarning] = useState<string | null>(null);

  useEffect(() => {
    form.setFieldsValue({ items: [{}] });
  }, []);

  const calculatePrice = (productId: string, quantity: number): QuoteItem | null => {
    const product = MOCK_PRODUCTS.find(p => p.id === productId);
    if (!product) return null;

    let discountPercent = 0;
    if (quantity >= 500) discountPercent = 20;
    else if (quantity >= 100) discountPercent = 15;
    else if (quantity >= 50) discountPercent = 10;
    else if (quantity >= 10) discountPercent = 5;

    const unitPrice = Number((product.basePrice * (1 - discountPercent / 100)).toFixed(2));
    const totalAmount = Number((unitPrice * quantity).toFixed(2));
    const profitMargin = Number(((unitPrice - product.basePrice * 0.7) / unitPrice).toFixed(4));

    const isApproved = profitMargin >= 0.15;
    let rejectionReason: string | undefined;
    if (!isApproved) {
      rejectionReason = `Profit margin ${(profitMargin * 100).toFixed(2)}% is below the minimum threshold of 15% for B2B transactions`;
    }

    return {
      key: `${productId}-${Date.now()}`,
      productId,
      productName: product.name,
      quantity,
      basePrice: product.basePrice,
      unitPrice,
      discountPercent,
      totalAmount,
      profitMargin,
      isApproved,
      rejectionReason,
    };
  };

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

  const handleAddItem = () => {
    const values = form.getFieldsValue();
    const newItem = calculatePrice(values.newProductId, values.newQuantity);
    if (newItem) {
      setQuoteItems([...quoteItems, newItem]);
      form.setFieldsValue({ newProductId: undefined, newQuantity: undefined });
      
      if (!newItem.isApproved) {
        setProfitWarning(newItem.rejectionReason || null);
      }
    }
  };

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

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

    const hasUnapproved = quoteItems.some(item => !item.isApproved);
    if (hasUnapproved) {
      Modal.confirm({
        title: 'Profit Margin Warning',
        icon: <WarningOutlined />,
        content: 'Some items have profit margins below the 15% threshold. Do you want to proceed with PENDING_REVIEW status?',
        onOk: () => submitQuote(),
      });
    } else {
      await submitQuote();
    }
  };

  const submitQuote = async () => {
    setLoading(true);
    try {
      const totalAmount = quoteItems.reduce((sum, item) => sum + item.totalAmount, 0);
      
      const result = {
        quoteId: `QT-${Date.now()}`,
        customerId: selectedCustomer?.id,
        customerName: selectedCustomer?.name,
        items: quoteItems,
        totalAmount,
        status: quoteItems.every(item => item.isApproved) ? 'APPROVED' : 'PENDING_REVIEW',
        createdAt: new Date().toISOString(),
        validUntil: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
      };

      setQuoteResult(result);
      setResultModalVisible(true);
      message.success('Quote submitted successfully');
    } catch (error) {
      message.error('Failed to submit quote');
    } finally {
      setLoading(false);
    }
  };

  const columns: ColumnsType<QuoteItem> = [
    {
      title: 'Product ID',
      dataIndex: 'productId',
      key: 'productId',
      width: 100,
    },
    {
      title: 'Product Name',
      dataIndex: 'productName',
      key: 'productName',
      width: 200,
    },
    {
      title: 'Quantity',
      dataIndex: 'quantity',
      key: 'quantity',
      width: 80,
    },
    {
      title: 'Base Price',
      dataIndex: 'basePrice',
      key: 'basePrice',
      width: 100,
      render: (price: number) => `$${price.toFixed(2)}`,
    },
    {
      title: 'Discount',
      dataIndex: 'discountPercent',
      key: 'discountPercent',
      width: 80,
      render: (discount: number) => `${discount}%`,
    },
    {
      title: 'Unit Price',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 100,
      render: (price: number) => <strong>${price.toFixed(2)}</strong>,
    },
    {
      title: 'Total',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 100,
      render: (amount: number) => <strong style={{ color: '#1890ff' }}>${amount.toFixed(2)}</strong>,
    },
    {
      title: 'Profit Margin',
      dataIndex: 'profitMargin',
      key: 'profitMargin',
      width: 100,
      render: (margin: number, record: QuoteItem) => (
        <Tag color={record.isApproved ? 'green' : 'red'}>
          {(margin * 100).toFixed(1)}%
        </Tag>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'isApproved',
      key: 'isApproved',
      width: 100,
      render: (approved: boolean, record: QuoteItem) => (
        <Tooltip title={record.rejectionReason}>
          <Tag color={approved ? 'green' : 'red'} icon={approved ? <CheckCircleOutlined /> : <CloseCircleOutlined />}>
            {approved ? 'Approved' : 'Rejected'}
          </Tag>
        </Tooltip>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button type="link" danger onClick={() => handleRemoveItem(record.key)}>
          Remove
        </Button>
      ),
    },
  ];

  const totalAmount = quoteItems.reduce((sum, item) => sum + item.totalAmount, 0);
  const totalProfit = quoteItems.reduce((sum, item) => sum + (item.unitPrice - item.basePrice * 0.7) * item.quantity, 0);

  return (
    <div className="enterprise-quote-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Quote Amount"
              value={totalAmount}
              precision={2}
              prefix={<DollarOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Estimated Profit"
              value={totalProfit}
              precision={2}
              prefix="$"
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Items Count"
              value={quoteItems.length}
              suffix="items"
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Avg Profit Margin"
              value={quoteItems.length > 0 
                ? (quoteItems.reduce((sum, item) => sum + item.profitMargin, 0) / quoteItems.length * 100).toFixed(1)
                : 0}
              suffix="%"
              valueStyle={{ 
                color: quoteItems.length > 0 && quoteItems.reduce((sum, item) => sum + item.profitMargin, 0) / quoteItems.length >= 0.15 
                  ? '#52c41a' 
                  : '#ff4d4f' 
              }}
            />
          </Card>
        </Col>
      </Row>

      {profitWarning && (
        <Alert
          message="Profit Margin Warning"
          description={profitWarning}
          type="warning"
          showIcon
          closable
          onClose={() => setProfitWarning(null)}
          style={{ marginBottom: 16 }}
        />
      )}

      <Card title="Enterprise Quote Management" extra={
        <Space>
          <Button type="primary" onClick={handleSubmitQuote} loading={loading} icon={<FileTextOutlined />}>
            Submit Quote
          </Button>
        </Space>
      }>
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="customerId" label="Customer" rules={[{ required: true }]}>
                <Select placeholder="Select Customer" onChange={handleCustomerChange}>
                  {MOCK_CUSTOMERS.map(customer => (
                    <Option key={customer.id} value={customer.id}>
                      {customer.name} 
                      <Tag color={CREDIT_LEVEL_COLORS[customer.creditLevel]} style={{ marginLeft: 8 }}>
                        Level {customer.creditLevel}
                      </Tag>
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="validUntil" label="Valid Until">
                <Input type="date" defaultValue={new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="remark" label="Remark">
                <Input placeholder="Enter remark" />
              </Form.Item>
            </Col>
          </Row>

          {selectedCustomer && (
            <Card size="small" style={{ marginBottom: 16, background: '#fafafa' }}>
              <Descriptions size="small" column={4}>
                <Descriptions.Item label="Credit Level">
                  <Tag color={CREDIT_LEVEL_COLORS[selectedCustomer.creditLevel]}>
                    {selectedCustomer.creditLevel}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Credit Limit">
                  ${selectedCustomer.creditLimit.toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="Used Credit">
                  ${selectedCustomer.usedCredit.toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="Available Credit">
                  ${(selectedCustomer.creditLimit - selectedCustomer.usedCredit).toLocaleString()}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          )}

          <Divider>Add Quote Items</Divider>

          <Row gutter={16}>
            <Col span={10}>
              <Form.Item name="newProductId" label="Product">
                <Select placeholder="Select Product">
                  {MOCK_PRODUCTS.map(product => (
                    <Option key={product.id} value={product.id}>
                      {product.id} - {product.name} (${product.basePrice.toFixed(2)})
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item name="newQuantity" label="Quantity">
                <InputNumber min={1} placeholder="Qty" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label=" ">
                <Button type="primary" onClick={handleAddItem} icon={<CalculatorOutlined />}>
                  Calculate & Add
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>

        <Divider>Quote Items</Divider>

        <Table
          columns={columns}
          dataSource={quoteItems}
          pagination={false}
          scroll={{ x: 1000 }}
          summary={() => (
            <Table.Summary fixed>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0} colSpan={6}>
                  <strong>Total</strong>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={1}>
                  <strong style={{ color: '#1890ff', fontSize: 16 }}>
                    ${totalAmount.toFixed(2)}
                  </strong>
                </Table.Summary.Cell>
                <Table.Summary.Cell index={2} colSpan={3} />
              </Table.Summary.Row>
            </Table.Summary>
          )}
        />
      </Card>

      <Modal
        title="Quote Result"
        open={resultModalVisible}
        onCancel={() => setResultModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setResultModalVisible(false)}>
            Close
          </Button>,
          <Button key="print" type="primary" onClick={() => message.info('Print functionality coming soon')}>
            Print Quote
          </Button>,
        ]}
        width={800}
      >
        {quoteResult && (
          <Result
            status={quoteResult.status === 'APPROVED' ? 'success' : 'warning'}
            title={`Quote ${quoteResult.quoteId}`}
            subTitle={quoteResult.status === 'APPROVED' 
              ? 'Quote has been approved automatically' 
              : 'Quote requires manual review due to profit margin constraints'}
            extra={[
              <Descriptions key="details" bordered column={2} style={{ marginTop: 24 }}>
                <Descriptions.Item label="Customer">{quoteResult.customerName}</Descriptions.Item>
                <Descriptions.Item label="Status">
                  <Tag color={quoteResult.status === 'APPROVED' ? 'green' : 'orange'}>
                    {quoteResult.status}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="Total Amount">
                  <strong style={{ fontSize: 18, color: '#1890ff' }}>
                    ${quoteResult.totalAmount.toFixed(2)}
                  </strong>
                </Descriptions.Item>
                <Descriptions.Item label="Items Count">{quoteResult.items.length}</Descriptions.Item>
                <Descriptions.Item label="Created At">
                  {new Date(quoteResult.createdAt).toLocaleString()}
                </Descriptions.Item>
                <Descriptions.Item label="Valid Until">
                  {new Date(quoteResult.validUntil).toLocaleDateString()}
                </Descriptions.Item>
              </Descriptions>,
            ]}
          />
        )}
      </Modal>
    </div>
  );
};

export default EnterpriseQuote;
