import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Modal,
  Descriptions,
  Divider,
  message,
  Space,
  Tag,
  Row,
  Col,
  DatePicker,
  Upload,
  Tooltip,
  Badge,
  Statistic,
  Timeline,
  Tabs,
  Popconfirm,
} from 'antd';
import {
  FileTextOutlined,
  PlusOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  SyncOutlined,
  UploadOutlined,
  DownloadOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  HistoryOutlined,
  ClockCircleOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { b2bTradeDataSource, Contract } from '@/services/b2bTradeDataSource';

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

interface ContractFormData {
  customerId: string;
  customerName: string;
  title: string;
  type: 'SALES' | 'PURCHASE' | 'SERVICE' | 'NDA' | 'OTHER';
  status: 'DRAFT' | 'PENDING_SIGN' | 'ACTIVE' | 'EXPIRED' | 'TERMINATED';
  startDate: string;
  endDate: string;
  totalValue: number;
  currency: string;
  signedDate?: string;
  signedBy?: string;
  attachments: string[];
  createdAt: string;
  updatedAt: string;
}

interface ContractHistory {
  id: string;
  contractId: string;
  action: string;
  operator: string;
  timestamp: string;
  remark?: string;
}

interface Customer {
  id: string;
  name: string;
  company: string;
}

const CONTRACT_STATUS_MAP: Record<string, { color: string; text: string }> = {
  DRAFT: { color: 'default', text: 'Draft' },
  PENDING_SIGN: { color: 'processing', text: 'Pending Signature' },
  ACTIVE: { color: 'success', text: 'Active' },
  EXPIRED: { color: 'warning', text: 'Expired' },
  TERMINATED: { color: 'error', text: 'Terminated' },
};

const CONTRACT_TYPE_MAP: Record<string, { color: string; text: string }> = {
  SALES: { color: 'blue', text: 'Sales Contract' },
  PURCHASE: { color: 'green', text: 'Purchase Contract' },
  SERVICE: { color: 'orange', text: 'Service Agreement' },
  NDA: { color: 'purple', text: 'NDA' },
  OTHER: { color: 'default', text: 'Other' },
};

export const ContractManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [selectedContract, setSelectedContract] = useState<Contract | null>(null);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [historyModalVisible, setHistoryModalVisible] = useState(false);
  const [contractHistory, setContractHistory] = useState<ContractHistory[]>([]);
  const [fileList, setFileList] = useState<any[]>([]);
  const [stats, setStats] = useState({
    total: 0,
    active: 0,
    expiringSoon: 0,
    totalValue: 0,
  });

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

  const fetchContracts = async () => {
    setLoading(true);
    try {
      const mockContracts: Contract[] = [
        {
          id: '1',
          contractId: 'CTR-2026-001',
          contractNumber: 'SALES-2026-001',
          customerId: 'CUST_001',
          customerName: 'ABC Trading Co.',
          title: 'Annual Sales Agreement',
          type: 'SALES',
          status: 'ACTIVE',
          startDate: '2026-01-01',
          endDate: '2026-12-31',
          totalValue: 500000.00,
          currency: 'USD',
          signedDate: '2025-12-15',
          signedBy: 'John Smith',
          attachments: ['contract.pdf'],
          createdAt: '2025-12-01 10:00:00',
          updatedAt: '2025-12-15 14:00:00',
        },
        {
          id: '2',
          contractId: 'CTR-2026-002',
          contractNumber: 'NDA-2026-001',
          customerId: 'CUST_002',
          customerName: 'XYZ Electronics Ltd.',
          title: 'Non-Disclosure Agreement',
          type: 'NDA',
          status: 'ACTIVE',
          startDate: '2026-02-01',
          endDate: '2028-01-31',
          totalValue: 0,
          currency: 'USD',
          signedDate: '2026-01-20',
          signedBy: 'Emma Wilson',
          attachments: ['nda.pdf'],
          createdAt: '2026-01-10 09:00:00',
          updatedAt: '2026-01-20 16:00:00',
        },
        {
          id: '3',
          contractId: 'CTR-2026-003',
          contractNumber: 'PURCHASE-2026-001',
          customerId: 'CUST_003',
          customerName: 'Global Import Inc.',
          title: 'Purchase Agreement Q2',
          type: 'PURCHASE',
          status: 'PENDING_SIGN',
          startDate: '2026-04-01',
          endDate: '2026-06-30',
          totalValue: 150000.00,
          currency: 'USD',
          attachments: ['purchase_agreement.pdf'],
          createdAt: '2026-03-15 11:00:00',
          updatedAt: '2026-03-18 10:00:00',
        },
        {
          id: '4',
          contractId: 'CTR-2025-015',
          contractNumber: 'SALES-2025-015',
          customerId: 'CUST_001',
          customerName: 'ABC Trading Co.',
          title: 'Expired Sales Contract',
          type: 'SALES',
          status: 'EXPIRED',
          startDate: '2025-01-01',
          endDate: '2025-12-31',
          totalValue: 350000.00,
          currency: 'USD',
          signedDate: '2025-01-05',
          signedBy: 'John Smith',
          attachments: ['old_contract.pdf'],
          createdAt: '2025-01-01 10:00:00',
          updatedAt: '2026-01-01 00:00:00',
        },
      ];
      setContracts(mockContracts);
      calculateStats(mockContracts);
    } catch (error) {
      message.error('Failed to load contracts');
    } finally {
      setLoading(false);
    }
  };

  const fetchCustomers = async () => {
    const mockCustomers: Customer[] = [
      { id: 'CUST_001', name: 'ABC Trading Co.', company: 'ABC Trading' },
      { id: 'CUST_002', name: 'XYZ Electronics Ltd.', company: 'XYZ Electronics' },
      { id: 'CUST_003', name: 'Global Import Inc.', company: 'Global Import' },
    ];
    setCustomers(mockCustomers);
  };

  const calculateStats = (contractList: Contract[]) => {
    const today = new Date();
    const thirtyDaysLater = new Date(today.getTime() + 30 * 24 * 60 * 60 * 1000);

    setStats({
      total: contractList.length,
      active: contractList.filter((c) => c.status === 'ACTIVE').length,
      expiringSoon: contractList.filter((c) => {
        if (c.status !== 'ACTIVE') return false;
        const endDate = new Date(c.endDate);
        return endDate <= thirtyDaysLater && endDate >= today;
      }).length,
      totalValue: contractList.filter((c) => c.status === 'ACTIVE').reduce((sum, c) => sum + c.totalValue, 0),
    });
  };

  const handleViewDetail = (contract: Contract) => {
    setSelectedContract(contract);
    setDetailModalVisible(true);
  };

  const handleEdit = (contract: Contract) => {
    setSelectedContract(contract);
    form.setFieldsValue({
      customerId: contract.customerId,
      title: contract.title,
      type: contract.type,
      startDate: contract.startDate,
      endDate: contract.endDate,
      totalValue: contract.totalValue,
    });
    setEditModalVisible(true);
  };

  const handleViewHistory = (contract: Contract) => {
    setSelectedContract(contract);
    const mockHistory: ContractHistory[] = [
      { id: '1', contractId: contract.contractId, action: 'Created', operator: 'System', timestamp: contract.createdAt },
      { id: '2', contractId: contract.contractId, action: 'Status changed to Pending Signature', operator: 'Admin', timestamp: '2026-03-16 10:00:00' },
      { id: '3', contractId: contract.contractId, action: 'Document uploaded', operator: 'Admin', timestamp: '2026-03-17 14:00:00' },
    ];
    setContractHistory(mockHistory);
    setHistoryModalVisible(true);
  };

  const handleCreateContract = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const contractData = {
        ...values,
        attachments: fileList.map((f) => f.name),
      };

      console.log('Creating contract:', contractData);

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

      message.success('Contract created successfully');
      setCreateModalVisible(false);
      form.resetFields();
      setFileList([]);
      fetchContracts();
    } catch (error) {
      message.error('Failed to create contract');
    } finally {
      setLoading(false);
    }
  };

  const handleUpdateContract = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      console.log('Updating contract:', { contractId: selectedContract?.contractId, ...values });

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

      message.success('Contract updated successfully');
      setEditModalVisible(false);
      fetchContracts();
    } catch (error) {
      message.error('Failed to update contract');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteContract = async (contractId: string) => {
    setLoading(true);
    try {
      console.log('Deleting contract:', contractId);
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Contract deleted successfully');
      fetchContracts();
    } catch (error) {
      message.error('Failed to delete contract');
    } finally {
      setLoading(false);
    }
  };

  const handleStatusChange = async (contractId: string, newStatus: string) => {
    setLoading(true);
    try {
      console.log('Changing status:', { contractId, newStatus });
      await new Promise((resolve) => setTimeout(resolve, 500));
      message.success('Status updated successfully');
      fetchContracts();
    } catch (error) {
      message.error('Failed to update status');
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = (filename: string) => {
    message.info(`Downloading ${filename}...`);
  };

  const columns: ColumnsType<Contract> = [
    {
      title: 'Contract ID',
      dataIndex: 'contractId',
      key: 'contractId',
      width: 130,
      render: (text: string, record) => (
        <a onClick={() => handleViewDetail(record)}>{text}</a>
      ),
    },
    {
      title: 'Contract Number',
      dataIndex: 'contractNumber',
      key: 'contractNumber',
      width: 150,
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 150,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 130,
      render: (type: string) => {
        const config = CONTRACT_TYPE_MAP[type];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      width: 130,
      render: (status: string) => {
        const config = CONTRACT_STATUS_MAP[status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Value',
      dataIndex: 'totalValue',
      key: 'totalValue',
      width: 120,
      render: (value: number) => value > 0 ? `$${value.toLocaleString()}` : '-',
    },
    {
      title: 'End Date',
      dataIndex: 'endDate',
      key: 'endDate',
      width: 110,
    },
    {
      title: 'Actions',
      key: 'action',
      width: 180,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          <Tooltip title="Edit">
            <Button type="link" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Tooltip title="History">
            <Button type="link" icon={<HistoryOutlined />} onClick={() => handleViewHistory(record)} />
          </Tooltip>
          {record.status === 'DRAFT' && (
            <Popconfirm
              title="Delete this contract?"
              onConfirm={() => handleDeleteContract(record.contractId)}
            >
              <Button type="link" danger icon={<DeleteOutlined />} />
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="contract-manage-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Contracts" value={stats.total} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Active"
              value={stats.active}
              valueStyle={{ color: '#52c41a' }}
              prefix={<CheckCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Expiring Soon"
              value={stats.expiringSoon}
              valueStyle={{ color: '#faad14' }}
              prefix={<ClockCircleOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="Total Value"
              value={stats.totalValue}
              precision={0}
              prefix="$"
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
      </Row>

      <Card
        title="Contract Management"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
            New Contract
          </Button>
        }
      >
        <Tabs defaultActiveKey="all">
          <TabPane tab="All Contracts" key="all" />
          <TabPane tab="Active" key="active" />
          <TabPane tab="Pending Signature" key="pending" />
          <TabPane tab="Expired" key="expired" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={contracts}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1400 }}
          pagination={{
            showSizeChanger: true,
            showTotal: (total) => `Total ${total} contracts`,
          }}
        />
      </Card>

      <Modal
        title="Create New Contract"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        onOk={handleCreateContract}
        confirmLoading={loading}
        width={700}
      >
        <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">
                  {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="type" label="Contract Type" rules={[{ required: true }]}>
                <Select placeholder="Select type">
                  {Object.entries(CONTRACT_TYPE_MAP).map(([key, value]) => (
                    <Option key={key} value={key}>{value.text}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="title" label="Contract Title" rules={[{ required: true }]}>
            <Input placeholder="Enter contract title" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="startDate" label="Start Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="endDate" label="End Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="totalValue" label="Contract Value">
            <InputNumber
              prefix="$"
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="Enter contract value"
            />
          </Form.Item>
          <Form.Item label="Attachments">
            <Upload
              fileList={fileList}
              onChange={({ fileList }) => setFileList(fileList)}
              beforeUpload={() => false}
            >
              <Button icon={<UploadOutlined />}>Upload Files</Button>
            </Upload>
          </Form.Item>
          <Form.Item name="note" label="Notes">
            <TextArea rows={3} placeholder="Add notes (optional)" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Edit Contract"
        open={editModalVisible}
        onCancel={() => setEditModalVisible(false)}
        onOk={handleUpdateContract}
        confirmLoading={loading}
        width={700}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="customerId" label="Customer" rules={[{ required: true }]}>
                <Select placeholder="Select customer" disabled>
                  {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="type" label="Contract Type" rules={[{ required: true }]}>
                <Select placeholder="Select type">
                  {Object.entries(CONTRACT_TYPE_MAP).map(([key, value]) => (
                    <Option key={key} value={key}>{value.text}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="title" label="Contract Title" rules={[{ required: true }]}>
            <Input placeholder="Enter contract title" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="startDate" label="Start Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="endDate" label="End Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="totalValue" label="Contract Value">
            <InputNumber
              prefix="$"
              min={0}
              precision={2}
              style={{ width: '100%' }}
              placeholder="Enter contract value"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="Contract Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            Close
          </Button>,
          selectedContract?.status === 'PENDING_SIGN' && (
            <Button key="activate" type="primary" onClick={() => {
              handleStatusChange(selectedContract.contractId, 'ACTIVE');
              setDetailModalVisible(false);
            }}>
              Mark as Active
            </Button>
          ),
        ]}
        width={800}
      >
        {selectedContract && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Contract ID">{selectedContract.contractId}</Descriptions.Item>
              <Descriptions.Item label="Contract Number">{selectedContract.contractNumber}</Descriptions.Item>
              <Descriptions.Item label="Title" span={2}>{selectedContract.title}</Descriptions.Item>
              <Descriptions.Item label="Customer">{selectedContract.customerName}</Descriptions.Item>
              <Descriptions.Item label="Type">
                <Tag color={CONTRACT_TYPE_MAP[selectedContract.type].color}>
                  {CONTRACT_TYPE_MAP[selectedContract.type].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={CONTRACT_STATUS_MAP[selectedContract.status].color}>
                  {CONTRACT_STATUS_MAP[selectedContract.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Value">
                {selectedContract.totalValue > 0 ? `$${selectedContract.totalValue.toLocaleString()}` : '-'}
              </Descriptions.Item>
              <Descriptions.Item label="Start Date">{selectedContract.startDate}</Descriptions.Item>
              <Descriptions.Item label="End Date">{selectedContract.endDate}</Descriptions.Item>
              {selectedContract.signedDate && (
                <Descriptions.Item label="Signed Date">{selectedContract.signedDate}</Descriptions.Item>
              )}
              {selectedContract.signedBy && (
                <Descriptions.Item label="Signed By">{selectedContract.signedBy}</Descriptions.Item>
              )}
              <Descriptions.Item label="Created">{selectedContract.createdAt}</Descriptions.Item>
              <Descriptions.Item label="Updated">{selectedContract.updatedAt}</Descriptions.Item>
            </Descriptions>

            {selectedContract.attachments.length > 0 && (
              <>
                <Divider>Attachments</Divider>
                <Space>
                  {selectedContract.attachments.map((file, index) => (
                    <Button
                      key={index}
                      icon={<DownloadOutlined />}
                      onClick={() => handleDownload(file)}
                    >
                      {file}
                    </Button>
                  ))}
                </Space>
              </>
            )}
          </>
        )}
      </Modal>

      <Modal
        title="Contract History"
        open={historyModalVisible}
        onCancel={() => setHistoryModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setHistoryModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={600}
      >
        <Timeline
          items={contractHistory.map((h) => ({
            color: 'blue',
            children: (
              <div>
                <p><strong>{h.action}</strong></p>
                <p style={{ color: '#666', margin: 0 }}>
                  {h.operator} - {h.timestamp}
                </p>
                {h.remark && <p style={{ color: '#999' }}>{h.remark}</p>}
              </div>
            ),
          }))}
        />
      </Modal>
    </div>
  );
};

export default ContractManage;
