import React, { useState } from 'react';
import { Card, Table, Button, Select, DatePicker, Space, Modal, Typography, Badge, message, Tabs, Row, Col, Statistic, Input, Form } from 'antd';
import { PlusOutlined, EyeOutlined, EditOutlined, DeleteOutlined, ReloadOutlined, FileTextOutlined, DollarOutlined, TeamOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Text } = Typography;
const { TabPane } = Tabs;
const { TextArea } = Input;

const mockQuotes = [
  {
    id: '1',
    quoteNo: 'B2B-2026-001',
    customer: 'ABC Electronics Inc.',
    contact: 'John Smith',
    email: 'john@abc-electronics.com',
    totalAmount: 15000,
    status: 'pending',
    items: [
      { name: 'Wireless Headphones', quantity: 100, price: 50 },
      { name: 'Bluetooth Speaker', quantity: 50, price: 80 },
    ],
    createdAt: '2026-03-15',
    updatedAt: '2026-03-18',
  },
  {
    id: '2',
    quoteNo: 'B2B-2026-002',
    customer: 'XYZ Fashion Ltd.',
    contact: 'Jane Doe',
    email: 'jane@xyz-fashion.com',
    totalAmount: 25000,
    status: 'approved',
    items: [
      { name: 'Smart Watch', quantity: 80, price: 120 },
      { name: 'Fitness Tracker', quantity: 120, price: 80 },
    ],
    createdAt: '2026-03-10',
    updatedAt: '2026-03-16',
  },
  {
    id: '3',
    quoteNo: 'B2B-2026-003',
    customer: 'Global Home Decor',
    contact: 'Bob Johnson',
    email: 'bob@global-home.com',
    totalAmount: 8000,
    status: 'rejected',
    items: [
      { name: 'Home Decor Set', quantity: 40, price: 200 },
    ],
    createdAt: '2026-03-05',
    updatedAt: '2026-03-12',
  },
  {
    id: '4',
    quoteNo: 'B2B-2026-004',
    customer: 'Sports Equipment Co.',
    contact: 'Alice Williams',
    email: 'alice@sports-equip.com',
    totalAmount: 18000,
    status: 'completed',
    items: [
      { name: 'Sports Equipment Set', quantity: 60, price: 300 },
    ],
    createdAt: '2026-03-01',
    updatedAt: '2026-03-10',
  },
];

const mockContracts = [
  {
    id: '1',
    contractNo: 'CON-2026-001',
    customer: 'ABC Electronics Inc.',
    startDate: '2026-03-01',
    endDate: '2026-12-31',
    totalAmount: 150000,
    status: 'active',
    terms: 'Net 30 days',
    createdAt: '2026-02-28',
  },
  {
    id: '2',
    contractNo: 'CON-2026-002',
    customer: 'XYZ Fashion Ltd.',
    startDate: '2026-03-15',
    endDate: '2027-03-14',
    totalAmount: 300000,
    status: 'active',
    terms: 'Net 45 days',
    createdAt: '2026-03-10',
  },
  {
    id: '3',
    contractNo: 'CON-2026-003',
    customer: 'Global Home Decor',
    startDate: '2026-01-01',
    endDate: '2026-12-31',
    totalAmount: 100000,
    status: 'expired',
    terms: 'Net 30 days',
    createdAt: '2025-12-28',
  },
];

const B2BPage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedQuote, setSelectedQuote] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('quotes');
  const [searchKeyword, setSearchKeyword] = useState('');

  const handleViewDetail = (record: any) => {
    setSelectedQuote(record);
    setIsDetailModalVisible(true);
  };

  const handleCreateQuote = () => {
    message.success('Create quote form opened');
  };

  const handleEditQuote = (record: any) => {
    message.success(`Edit quote ${record.quoteNo}`);
  };

  const handleDeleteQuote = (record: any) => {
    message.success(`Delete quote ${record.quoteNo}`);
  };

  const handleApproveQuote = (record: any) => {
    message.success(`Approve quote ${record.quoteNo}`);
  };

  const handleRejectQuote = (record: any) => {
    message.success(`Reject quote ${record.quoteNo}`);
  };

  const handleConvertToOrder = (record: any) => {
    message.success(`Convert quote ${record.quoteNo} to order`);
  };

  const handleBatchDelete = () => {
    message.success('Batch delete initiated');
  };

  const handleBatchApprove = () => {
    message.success('Batch approve initiated');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending': return 'processing';
      case 'approved': return 'success';
      case 'rejected': return 'error';
      case 'completed': return 'success';
      case 'active': return 'success';
      case 'expired': return 'default';
      default: return 'default';
    }
  };

  const quoteColumns = [
    {
      title: 'Quote No',
      dataIndex: 'quoteNo',
      key: 'quoteNo',
    },
    {
      title: 'Customer',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: 'Contact',
      dataIndex: 'contact',
      key: 'contact',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
    },
    {
      title: 'Total Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (value: number) => `$${value.toLocaleString()}`,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button icon={<EditOutlined />} onClick={() => handleEditQuote(record)}>Edit</Button>
          {record.status === 'pending' && (
            <>
              <Button icon={<CheckCircleOutlined />} type="primary" onClick={() => handleApproveQuote(record)}>Approve</Button>
              <Button icon={<CloseCircleOutlined />} danger onClick={() => handleRejectQuote(record)}>Reject</Button>
            </>
          )}
          {record.status === 'approved' && (
            <Button icon={<FileTextOutlined />} onClick={() => handleConvertToOrder(record)}>Convert to Order</Button>
          )}
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteQuote(record)}>Delete</Button>
        </Space>
      ),
    },
  ];

  const contractColumns = [
    {
      title: 'Contract No',
      dataIndex: 'contractNo',
      key: 'contractNo',
    },
    {
      title: 'Customer',
      dataIndex: 'customer',
      key: 'customer',
    },
    {
      title: 'Start Date',
      dataIndex: 'startDate',
      key: 'startDate',
    },
    {
      title: 'End Date',
      dataIndex: 'endDate',
      key: 'endDate',
    },
    {
      title: 'Total Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (value: number) => `$${value.toLocaleString()}`,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Terms',
      dataIndex: 'terms',
      key: 'terms',
    },
    {
      title: 'Created At',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
  ];

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: React.Key[]) => {
      setSelectedRowKeys(keys);
    },
  };

  const filteredQuotes = mockQuotes.filter(quote =>
    quote.customer.toLowerCase().includes(searchKeyword.toLowerCase()) ||
    quote.quoteNo.toLowerCase().includes(searchKeyword.toLowerCase())
  );

  return (
    <div className="b2b-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>B2B Trade Management</Title>
        <Space>
          <Button icon={<PlusOutlined />} type="primary" onClick={handleCreateQuote}>Create Quote</Button>
          <Button icon={<ReloadOutlined />}>Refresh</Button>
          <Button onClick={handleBatchApprove} disabled={selectedRowKeys.length === 0}>Batch Approve</Button>
          <Button onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0} danger>Batch Delete</Button>
        </Space>
      </div>

      <Card style={{ marginBottom: 24 }}>
        <Row gutter={[16, 16]}>
          <Col span={6}>
            <Statistic
              title="Total Quotes"
              value={4}
              valueStyle={{ color: '#3f8600' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Pending Quotes"
              value={1}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Approved Quotes"
              value={1}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Total Contract Value"
              value={550000}
              precision={0}
              prefix="$"
              valueStyle={{ color: '#722ed1' }}
            />
          </Col>
        </Row>
      </Card>

      <Card style={{ marginBottom: 24 }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="Quotes" key="quotes">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Input
                placeholder="Search by customer or quote number"
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                style={{ width: 300 }}
                allowClear
              />
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="pending">Pending</Option>
                <Option value="approved">Approved</Option>
                <Option value="rejected">Rejected</Option>
                <Option value="completed">Completed</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              rowSelection={rowSelection}
              columns={quoteColumns}
              dataSource={filteredQuotes}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
          <TabPane tab="Contracts" key="contracts">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="active">Active</Option>
                <Option value="expired">Expired</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              columns={contractColumns}
              dataSource={mockContracts}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={`Quote Detail - ${selectedQuote?.quoteNo}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={1000}
      >
        {selectedQuote && (
          <Tabs defaultActiveKey="details">
            <TabPane tab="Quote Details" key="details">
              <div style={{ marginBottom: 24 }}>
                <h3>Basic Information</h3>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
                  <div>
                    <Text strong>Quote No:</Text> {selectedQuote.quoteNo}
                  </div>
                  <div>
                    <Text strong>Customer:</Text> {selectedQuote.customer}
                  </div>
                  <div>
                    <Text strong>Contact:</Text> {selectedQuote.contact}
                  </div>
                  <div>
                    <Text strong>Email:</Text> {selectedQuote.email}
                  </div>
                  <div>
                    <Text strong>Total Amount:</Text> ${selectedQuote.totalAmount.toLocaleString()}
                  </div>
                  <div>
                    <Text strong>Status:</Text> <Badge status={getStatusColor(selectedQuote.status)} text={selectedQuote.status} />
                  </div>
                  <div>
                    <Text strong>Created At:</Text> {selectedQuote.createdAt}
                  </div>
                  <div>
                    <Text strong>Updated At:</Text> {selectedQuote.updatedAt}
                  </div>
                </div>
              </div>
              <div>
                <h3>Quote Items</h3>
                <Table
                  columns={[
                    { title: 'Product', dataIndex: 'name', key: 'name' },
                    { title: 'Quantity', dataIndex: 'quantity', key: 'quantity' },
                    { title: 'Unit Price', dataIndex: 'price', key: 'price', render: (value: number) => `$${value.toFixed(2)}` },
                    { title: 'Total', key: 'total', render: (_: any, record: any) => `$${(record.quantity * record.price).toFixed(2)}` },
                  ]}
                  dataSource={selectedQuote.items}
                  rowKey="name"
                  pagination={false}
                />
              </div>
              <div style={{ marginTop: 24 }}>
                <h3>Quick Actions</h3>
                <Space size="middle" style={{ marginTop: 16 }}>
                  {selectedQuote.status === 'pending' && (
                    <>
                      <Button icon={<CheckCircleOutlined />} type="primary" onClick={() => handleApproveQuote(selectedQuote)}>Approve</Button>
                      <Button icon={<CloseCircleOutlined />} danger onClick={() => handleRejectQuote(selectedQuote)}>Reject</Button>
                    </>
                  )}
                  {selectedQuote.status === 'approved' && (
                    <Button icon={<FileTextOutlined />} onClick={() => handleConvertToOrder(selectedQuote)}>Convert to Order</Button>
                  )}
                </Space>
              </div>
            </TabPane>
            <TabPane tab="Customer Info" key="customer">
              <div style={{ padding: 24, textAlign: 'center' }}>
                <Text type="secondary">Customer information will be displayed here</Text>
              </div>
            </TabPane>
            <TabPane tab="History" key="history">
              <div style={{ padding: 24, textAlign: 'center' }}>
                <Text type="secondary">Quote history will be displayed here</Text>
              </div>
            </TabPane>
          </Tabs>
        )}
      </Modal>
    </div>
  );
};

export default B2BPage;