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

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

interface ContractFormData {
  startDate: string;
  endDate: string;
  totalAmount: number;
  signedDate?: string;
  signedBy?: string;
  attachments: string[];
  terms: string;
  remark?: string;
  createdAt: string;
  updatedAt: string;
}

const MOCK_CUSTOMERS = [
  { id: 'C001', name: 'TechCorp Industries' },
  { id: 'C002', name: 'Global Manufacturing Co' },
  { id: 'C003', name: 'Smart Factory Solutions' },
];

const CONTRACT_TYPES = [
  { value: 'PURCHASE', label: 'Purchase Contract' },
  { value: 'SALES', label: 'Sales Contract' },
  { value: 'SERVICE', label: 'Service Agreement' },
  { value: 'DISTRIBUTION', label: 'Distribution Agreement' },
  { value: 'OEM', label: 'OEM Contract' },
];

const STATUS_CONFIG: Record<string, { color: string; text: string; icon: React.ReactNode }> = {
  DRAFT: { color: 'default', text: 'Draft', icon: <EditOutlined /> },
  PENDING_REVIEW: { color: 'warning', text: 'Pending Review', icon: <ClockCircleOutlined /> },
  ACTIVE: { color: 'success', text: 'Active', icon: <CheckCircleOutlined /> },
  EXPIRED: { color: 'error', text: 'Expired', icon: <CloseCircleOutlined /> },
  TERMINATED: { color: 'red', text: 'Terminated', icon: <CloseCircleOutlined /> },
  RENEWED: { color: 'blue', text: 'Renewed', icon: <SyncOutlined /> },
};

export const ContractManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [contracts, setContracts] = useState<Contract[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedContract, setSelectedContract] = useState<Contract | null>(null);
  const [activeTab, setActiveTab] = useState('all');

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

  const fetchContracts = async () => {
    setLoading(true);
    try {
      const mockContracts: Contract[] = [
        {
          id: '1',
          contractNo: 'CTR-2026-001',
          customerId: 'C001',
          customerName: 'TechCorp Industries',
          title: 'Annual Supply Agreement 2026',
          type: 'SALES',
          status: 'ACTIVE',
          startDate: '2026-01-01',
          endDate: '2026-12-31',
          totalAmount: 500000,
          signedDate: '2025-12-15',
          signedBy: 'John Smith',
          attachments: ['contract_ctr_2026_001.pdf'],
          terms: 'Net 30 payment terms. Minimum order quantity: 100 units per SKU. Price adjustment clause applies after 6 months.',
          createdAt: '2025-12-01 10:00:00',
          updatedAt: '2025-12-15 14:30:00',
        },
        {
          id: '2',
          contractNo: 'CTR-2026-002',
          customerId: 'C002',
          customerName: 'Global Manufacturing Co',
          title: 'OEM Manufacturing Agreement',
          type: 'OEM',
          status: 'PENDING_REVIEW',
          startDate: '2026-03-01',
          endDate: '2027-02-28',
          totalAmount: 800000,
          attachments: ['oem_agreement_draft.pdf', 'specification_v2.pdf'],
          terms: 'Exclusive manufacturing rights for North America region. Quality standards: ISO 9001:2015. Lead time: 45 days.',
          createdAt: '2026-03-10 09:00:00',
          updatedAt: '2026-03-15 11:20:00',
        },
        {
          id: '3',
          contractNo: 'CTR-2025-015',
          customerId: 'C003',
          customerName: 'Smart Factory Solutions',
          title: 'Distribution Partnership Agreement',
          type: 'DISTRIBUTION',
          status: 'EXPIRED',
          startDate: '2025-01-01',
          endDate: '2025-12-31',
          totalAmount: 300000,
          signedDate: '2024-12-20',
          signedBy: 'Mike Johnson',
          attachments: ['distribution_2025.pdf'],
          terms: 'Non-exclusive distribution rights for West Coast region. Minimum annual purchase: $250,000.',
          remark: 'Contract expired. Renewal pending.',
          createdAt: '2024-12-10 14:00:00',
          updatedAt: '2026-01-02 09:00:00',
        },
        {
          id: '4',
          contractNo: 'CTR-2026-003',
          customerId: 'C001',
          customerName: 'TechCorp Industries',
          title: 'Service Level Agreement',
          type: 'SERVICE',
          status: 'DRAFT',
          startDate: '2026-04-01',
          endDate: '2027-03-31',
          totalAmount: 120000,
          attachments: [],
          terms: '24/7 technical support. Response time: 4 hours for critical issues. On-site support included.',
          createdAt: '2026-03-18 10:30:00',
          updatedAt: '2026-03-18 10:30:00',
        },
      ];
      setContracts(mockContracts);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateContract = async (values: any) => {
    setLoading(true);
    try {
      const customer = MOCK_CUSTOMERS.find(c => c.id === values.customerId);
      const newContract: Contract = {
        id: `${Date.now()}`,
        contractNo: `CTR-${new Date().getFullYear()}-${String(contracts.length + 1).padStart(3, '0')}`,
        customerId: values.customerId,
        customerName: customer?.name || '',
        title: values.title,
        type: values.type,
        status: 'DRAFT',
        startDate: values.dateRange[0].format('YYYY-MM-DD'),
        endDate: values.dateRange[1].format('YYYY-MM-DD'),
        totalAmount: values.totalAmount,
        attachments: [],
        terms: values.terms,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };

      setContracts([newContract, ...contracts]);
      message.success('Contract created successfully');
      setCreateModalVisible(false);
      form.resetFields();
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmitForReview = (contractId: string) => {
    Modal.confirm({
      title: 'Submit for Review',
      content: 'Are you sure you want to submit this contract for review?',
      onOk: () => {
        setContracts(contracts.map(c => 
          c.id === contractId ? { ...c, status: 'PENDING_REVIEW' as const, updatedAt: new Date().toISOString() } : c
        ));
        message.success('Contract submitted for review');
      },
    });
  };

  const handleApprove = (contractId: string) => {
    Modal.confirm({
      title: 'Approve Contract',
      content: 'Are you sure you want to approve this contract?',
      onOk: () => {
        setContracts(contracts.map(c => 
          c.id === contractId ? { 
            ...c, 
            status: 'ACTIVE' as const, 
            signedDate: new Date().toISOString().split('T')[0],
            signedBy: 'Current User',
            updatedAt: new Date().toISOString() 
          } : c
        ));
        message.success('Contract approved');
        setDetailModalVisible(false);
      },
    });
  };

  const getFilteredContracts = () => {
    if (activeTab === 'all') return contracts;
    if (activeTab === 'expiring') {
      return contracts.filter(c => {
        const daysUntilExpiry = dayjs(c.endDate).diff(dayjs(), 'day');
        return daysUntilExpiry > 0 && daysUntilExpiry <= 30;
      });
    }
    return contracts.filter(c => c.status === activeTab.toUpperCase());
  };

  const columns: ColumnsType<Contract> = [
    {
      title: 'Contract No',
      dataIndex: 'contractNo',
      key: 'contractNo',
      width: 140,
      render: (no: string, record: Contract) => (
        <a onClick={() => handleViewDetail(record)}>{no}</a>
      ),
    },
    {
      title: 'Title',
      dataIndex: 'title',
      key: 'title',
      width: 200,
      ellipsis: true,
    },
    {
      title: 'Customer',
      dataIndex: 'customerName',
      key: 'customerName',
      width: 160,
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => {
        const config = CONTRACT_TYPES.find(t => t.value === type);
        return <Tag>{config?.label || type}</Tag>;
      },
    },
    {
      title: 'Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount: number) => <strong>${amount.toLocaleString()}</strong>,
    },
    {
      title: 'Period',
      key: 'period',
      width: 180,
      render: (_, record: Contract) => `${record.startDate} ~ ${record.endDate}`,
    },
    {
      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: 'Actions',
      key: 'actions',
      width: 150,
      render: (_, record: Contract) => (
        <Space>
          <Tooltip title="View Details">
            <Button type="link" icon={<EyeOutlined />} onClick={() => handleViewDetail(record)} />
          </Tooltip>
          {record.status === 'DRAFT' && (
            <Tooltip title="Submit for Review">
              <Button type="link" icon={<CheckCircleOutlined />} onClick={() => handleSubmitForReview(record.id)} />
            </Tooltip>
          )}
        </Space>
      ),
    },
  ];

  const stats = {
    total: contracts.length,
    active: contracts.filter(c => c.status === 'ACTIVE').length,
    pending: contracts.filter(c => c.status === 'PENDING_REVIEW').length,
    expiring: contracts.filter(c => {
      const daysUntilExpiry = dayjs(c.endDate).diff(dayjs(), 'day');
      return daysUntilExpiry > 0 && daysUntilExpiry <= 30;
    }).length,
    totalAmount: contracts.filter(c => c.status === 'ACTIVE').reduce((sum, c) => sum + c.totalAmount, 0),
  };

  return (
    <div className="contract-manage-page">
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={4}>
          <Card>
            <Statistic title="Total Contracts" value={stats.total} prefix={<FileTextOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Active" value={stats.active} valueStyle={{ color: '#52c41a' }} prefix={<CheckCircleOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Pending Review" value={stats.pending} valueStyle={{ color: '#faad14' }} prefix={<ClockCircleOutlined />} />
          </Card>
        </Col>
        <Col span={4}>
          <Card>
            <Statistic title="Expiring Soon" value={stats.expiring} valueStyle={{ color: '#ff4d4f' }} prefix={<CloseCircleOutlined />} />
          </Card>
        </Col>
        <Col span={8}>
          <Card>
            <Statistic title="Active Contract Value" value={stats.totalAmount} prefix="$" valueStyle={{ color: '#1890ff' }} />
          </Card>
        </Col>
      </Row>

      <Card title="Contract Management" extra={
        <Button type="primary" icon={<PlusOutlined />} onClick={() => setCreateModalVisible(true)}>
          New Contract
        </Button>
      }>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="All" key="all" />
          <TabPane tab="Draft" key="draft" />
          <TabPane tab="Pending Review" key="pending_review" />
          <TabPane tab="Active" key="active" />
          <TabPane tab="Expiring Soon" key="expiring" />
          <TabPane tab="Expired" key="expired" />
        </Tabs>

        <Table
          columns={columns}
          dataSource={getFilteredContracts()}
          rowKey="id"
          loading={loading}
          pagination={{ pageSize: 10 }}
        />
      </Card>

      <Modal
        title="Create New Contract"
        open={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form form={form} layout="vertical" onFinish={handleCreateContract}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="customerId" label="Customer" rules={[{ required: true }]}>
                <Select placeholder="Select Customer">
                  {MOCK_CUSTOMERS.map(c => (
                    <Option key={c.id} value={c.id}>{c.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="type" label="Contract Type" rules={[{ required: true }]}>
                <Select placeholder="Select Type">
                  {CONTRACT_TYPES.map(t => (
                    <Option key={t.value} value={t.value}>{t.label}</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="dateRange" label="Contract Period" rules={[{ required: true }]}>
                <RangePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="totalAmount" label="Total Amount" rules={[{ required: true }]}>
                <InputNumber prefix="$" min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="terms" label="Terms & Conditions">
            <Input.TextArea rows={4} placeholder="Enter contract terms and conditions" />
          </Form.Item>

          <Form.Item name="attachments" label="Attachments">
            <Upload>
              <Button icon={<UploadOutlined />}>Upload Files</Button>
            </Upload>
          </Form.Item>

          <div style={{ textAlign: 'right' }}>
            <Button onClick={() => setCreateModalVisible(false)} style={{ marginRight: 8 }}>Cancel</Button>
            <Button type="primary" htmlType="submit" loading={loading}>Create Contract</Button>
          </div>
        </Form>
      </Modal>

      <Modal
        title="Contract Details"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={
          selectedContract?.status === 'PENDING_REVIEW' ? [
            <Button key="reject" danger>Reject</Button>,
            <Button key="approve" type="primary" onClick={() => handleApprove(selectedContract.id)}>Approve</Button>,
          ] : [
            <Button key="close" onClick={() => setDetailModalVisible(false)}>Close</Button>,
          ]
        }
        width={800}
      >
        {selectedContract && (
          <>
            <Descriptions bordered column={2}>
              <Descriptions.Item label="Contract No">{selectedContract.contractNo}</Descriptions.Item>
              <Descriptions.Item label="Status">
                <Tag color={STATUS_CONFIG[selectedContract.status].color}>
                  {STATUS_CONFIG[selectedContract.status].text}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Title" span={2}>{selectedContract.title}</Descriptions.Item>
              <Descriptions.Item label="Customer">{selectedContract.customerName}</Descriptions.Item>
              <Descriptions.Item label="Type">
                {CONTRACT_TYPES.find(t => t.value === selectedContract.type)?.label}
              </Descriptions.Item>
              <Descriptions.Item label="Start Date">{selectedContract.startDate}</Descriptions.Item>
              <Descriptions.Item label="End Date">{selectedContract.endDate}</Descriptions.Item>
              <Descriptions.Item label="Total Amount">
                <strong style={{ fontSize: 16, color: '#1890ff' }}>${selectedContract.totalAmount.toLocaleString()}</strong>
              </Descriptions.Item>
              <Descriptions.Item label="Signed Date">{selectedContract.signedDate || '-'}</Descriptions.Item>
              <Descriptions.Item label="Signed By">{selectedContract.signedBy || '-'}</Descriptions.Item>
              <Descriptions.Item label="Terms & Conditions" span={2}>
                {selectedContract.terms}
              </Descriptions.Item>
              {selectedContract.remark && (
                <Descriptions.Item label="Remark" span={2}>{selectedContract.remark}</Descriptions.Item>
              )}
            </Descriptions>

            <Divider>Contract Timeline</Divider>

            <Timeline
              items={[
                { color: 'green', children: `Created: ${selectedContract.createdAt}` },
                ...(selectedContract.status !== 'DRAFT' ? [{ color: 'blue', children: `Submitted for review` }] : []),
                ...(selectedContract.signedDate ? [{ color: 'green', children: `Signed: ${selectedContract.signedDate} by ${selectedContract.signedBy}` }] : []),
                { color: selectedContract.status === 'ACTIVE' ? 'green' : 'gray', children: `Status: ${STATUS_CONFIG[selectedContract.status].text}` },
              ]}
            />

            {selectedContract.attachments.length > 0 && (
              <>
                <Divider>Attachments</Divider>
                <Space>
                  {selectedContract.attachments.map((file, index) => (
                    <Button key={index} icon={<DownloadOutlined />} size="small">
                      {file}
                    </Button>
                  ))}
                </Space>
              </>
            )}
          </>
        )}
      </Modal>
    </div>
  );
};

export default ContractManage;
