import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Modal,
  Form,
  InputNumber,
  Select,
  Tag,
  message,
  Popconfirm,
  Tooltip,
  Row,
  Col,
  Statistic,
  DatePicker,
  Alert,
  Divider,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SyncOutlined,
  DollarOutlined,
  HistoryOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment';
import { settingsDataSource, ExchangeRate } from '@/services/settingsDataSource';

const { Option } = Select;

interface RateHistory {
  id: string;
  fromCurrency: string;
  toCurrency: string;
  rate: number;
  recordedAt: string;
  source: string;
}

const CURRENCY_LIST = [
  { code: 'USD', name: 'US Dollar', symbol: '$' },
  { code: 'CNY', name: 'Chinese Yuan', symbol: '¥' },
  { code: 'EUR', name: 'Euro', symbol: '€' },
  { code: 'GBP', name: 'British Pound', symbol: '£' },
  { code: 'JPY', name: 'Japanese Yen', symbol: '¥' },
  { code: 'AUD', name: 'Australian Dollar', symbol: 'A$' },
  { code: 'CAD', name: 'Canadian Dollar', symbol: 'C$' },
  { code: 'SGD', name: 'Singapore Dollar', symbol: 'S$' },
  { code: 'HKD', name: 'Hong Kong Dollar', symbol: 'HK$' },
  { code: 'KRW', name: 'Korean Won', symbol: '₩' },
];

const SOURCE_CONFIG: Record<string, { color: string; text: string }> = {
  MANUAL: { color: 'blue', text: 'Manual' },
  AUTO: { color: 'green', text: 'Auto' },
  API: { color: 'purple', text: 'API' },
};

const ExchangeRateConfig: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [rates, setRates] = useState<ExchangeRate[]>([]);
  const [history, setHistory] = useState<RateHistory[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [historyModalVisible, setHistoryModalVisible] = useState(false);
  const [editingRate, setEditingRate] = useState<ExchangeRate | null>(null);
  const [selectedPair, setSelectedPair] = useState<{ from: string; to: string } | null>(null);
  const [form] = Form.useForm();

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

  const fetchRates = async () => {
    setLoading(true);
    try {
      const mockRates: ExchangeRate[] = [
        { id: '1', fromCurrency: 'USD', toCurrency: 'CNY', rate: 7.24, source: 'AUTO', updatedAt: '2026-03-18 10:00:00', updatedBy: 'system', effectiveDate: '2026-03-18', isActive: true },
        { id: '2', fromCurrency: 'EUR', toCurrency: 'CNY', rate: 7.86, source: 'AUTO', updatedAt: '2026-03-18 10:00:00', updatedBy: 'system', effectiveDate: '2026-03-18', isActive: true },
        { id: '3', fromCurrency: 'GBP', toCurrency: 'CNY', rate: 9.21, source: 'AUTO', updatedAt: '2026-03-18 10:00:00', updatedBy: 'system', effectiveDate: '2026-03-18', isActive: true },
        { id: '4', fromCurrency: 'JPY', toCurrency: 'CNY', rate: 0.048, source: 'AUTO', updatedAt: '2026-03-18 10:00:00', updatedBy: 'system', effectiveDate: '2026-03-18', isActive: true },
        { id: '5', fromCurrency: 'USD', toCurrency: 'EUR', rate: 0.92, source: 'MANUAL', updatedAt: '2026-03-17 15:00:00', updatedBy: 'admin', effectiveDate: '2026-03-17', isActive: true },
        { id: '6', fromCurrency: 'AUD', toCurrency: 'CNY', rate: 4.72, source: 'API', updatedAt: '2026-03-18 09:30:00', updatedBy: 'system', effectiveDate: '2026-03-18', isActive: true },
      ];
      setRates(mockRates);
    } catch (error) {
      message.error('Failed to load exchange rates');
    } finally {
      setLoading(false);
    }
  };

  const fetchHistory = (from: string, to: string) => {
    const mockHistory: RateHistory[] = [
      { id: '1', fromCurrency: from, toCurrency: to, rate: 7.24, recordedAt: '2026-03-18 10:00:00', source: 'AUTO' },
      { id: '2', fromCurrency: from, toCurrency: to, rate: 7.22, recordedAt: '2026-03-17 10:00:00', source: 'AUTO' },
      { id: '3', fromCurrency: from, toCurrency: to, rate: 7.20, recordedAt: '2026-03-16 10:00:00', source: 'AUTO' },
      { id: '4', fromCurrency: from, toCurrency: to, rate: 7.18, recordedAt: '2026-03-15 10:00:00', source: 'AUTO' },
      { id: '5', fromCurrency: from, toCurrency: to, rate: 7.15, recordedAt: '2026-03-14 10:00:00', source: 'AUTO' },
    ];
    setHistory(mockHistory);
    setSelectedPair({ from, to });
    setHistoryModalVisible(true);
  };

  const handleAdd = () => {
    setEditingRate(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: ExchangeRate) => {
    setEditingRate(record);
    form.setFieldsValue({
      ...record,
      effectiveDate: moment(record.effectiveDate),
      expiryDate: record.expiryDate ? moment(record.expiryDate) : undefined,
    });
    setModalVisible(true);
  };

  const handleDelete = (id: string) => {
    setRates(rates.filter(r => r.id !== id));
    message.success('Exchange rate deleted successfully');
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const rateData = {
        ...values,
        effectiveDate: values.effectiveDate.format('YYYY-MM-DD'),
        expiryDate: values.expiryDate?.format('YYYY-MM-DD'),
        updatedAt: moment().format('YYYY-MM-DD HH:mm:ss'),
        updatedBy: 'admin',
        source: 'MANUAL' as const,
        isActive: true,
      };

      if (editingRate) {
        setRates(rates.map(r => r.id === editingRate.id ? { ...r, ...rateData } : r));
        message.success('Exchange rate updated successfully');
      } else {
        setRates([...rates, { ...rateData, id: `${Date.now()}` }]);
        message.success('Exchange rate added successfully');
      }
      setModalVisible(false);
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const handleSyncFromAPI = async () => {
    message.loading('Syncing exchange rates from API...', 2);
    await new Promise(resolve => setTimeout(resolve, 2000));
    message.success('Exchange rates synced successfully');
    fetchRates();
  };

  const handleToggleActive = (id: string, checked: boolean) => {
    setRates(rates.map(r => r.id === id ? { ...r, isActive: checked } : r));
    message.success(`Exchange rate ${checked ? 'activated' : 'deactivated'}`);
  };

  const stats = {
    total: rates.length,
    active: rates.filter(r => r.isActive).length,
    manual: rates.filter(r => r.source === 'MANUAL').length,
    auto: rates.filter(r => r.source === 'AUTO' || r.source === 'API').length,
  };

  const columns: ColumnsType<ExchangeRate> = [
    {
      title: 'From',
      dataIndex: 'fromCurrency',
      key: 'fromCurrency',
      width: 100,
      render: (code) => {
        const currency = CURRENCY_LIST.find(c => c.code === code);
        return <Tag>{code} ({currency?.symbol})</Tag>;
      },
    },
    {
      title: 'To',
      dataIndex: 'toCurrency',
      key: 'toCurrency',
      width: 100,
      render: (code) => {
        const currency = CURRENCY_LIST.find(c => c.code === code);
        return <Tag color="blue">{code} ({currency?.symbol})</Tag>;
      },
    },
    {
      title: 'Rate',
      dataIndex: 'rate',
      key: 'rate',
      width: 120,
      render: (rate) => <span style={{ fontWeight: 'bold', fontSize: 16 }}>{rate.toFixed(4)}</span>,
    },
    {
      title: 'Source',
      dataIndex: 'source',
      key: 'source',
      width: 100,
      render: (source) => {
        const config = SOURCE_CONFIG[source];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: 'Effective Date',
      dataIndex: 'effectiveDate',
      key: 'effectiveDate',
      width: 120,
    },
    {
      title: 'Updated',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      width: 160,
    },
    {
      title: 'Active',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 80,
      render: (active, record) => (
        <Tag color={active ? 'success' : 'default'} onClick={() => handleToggleActive(record.id, !active)} style={{ cursor: 'pointer' }}>
          {active ? 'Yes' : 'No'}
        </Tag>
      ),
    },
    {
      title: 'Actions',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Tooltip title="Edit">
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          </Tooltip>
          <Tooltip title="History">
            <Button type="link" size="small" icon={<HistoryOutlined />} onClick={() => fetchHistory(record.fromCurrency, record.toCurrency)} />
          </Tooltip>
          <Popconfirm title="Delete this rate?" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" size="small" danger icon={<DeleteOutlined />} />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const historyColumns: ColumnsType<RateHistory> = [
    { title: 'Date', dataIndex: 'recordedAt', key: 'recordedAt', width: 180 },
    { title: 'Rate', dataIndex: 'rate', key: 'rate', render: (r) => r.toFixed(4) },
    { title: 'Source', dataIndex: 'source', key: 'source' },
  ];

  return (
    <div className="exchange-rate-config">
      <Alert
        message="Exchange rates are automatically synced daily at 10:00 AM. You can also manually add or edit rates."
        type="info"
        showIcon
        style={{ marginBottom: 16 }}
      />

      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic title="Total Pairs" value={stats.total} prefix={<DollarOutlined />} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Active" value={stats.active} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Manual" value={stats.manual} valueStyle={{ color: '#1890ff' }} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="Auto/API" value={stats.auto} valueStyle={{ color: '#722ed1' }} />
          </Card>
        </Col>
      </Row>

      <Card
        title="Exchange Rate Configuration"
        extra={
          <Space>
            <Button icon={<SyncOutlined />} onClick={handleSyncFromAPI}>
              Sync from API
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              Add Rate
            </Button>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={rates}
          rowKey="id"
          loading={loading}
          scroll={{ x: 1000 }}
          pagination={{ showSizeChanger: true, showTotal: (total) => `Total ${total} rates` }}
        />
      </Card>

      <Modal
        title={editingRate ? 'Edit Exchange Rate' : 'Add Exchange Rate'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={500}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="fromCurrency" label="From Currency" rules={[{ required: true }]}>
                <Select placeholder="Select currency" showSearch optionFilterProp="children">
                  {CURRENCY_LIST.map(c => (
                    <Option key={c.code} value={c.code}>{c.code} - {c.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="toCurrency" label="To Currency" rules={[{ required: true }]}>
                <Select placeholder="Select currency" showSearch optionFilterProp="children">
                  {CURRENCY_LIST.map(c => (
                    <Option key={c.code} value={c.code}>{c.code} - {c.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Form.Item name="rate" label="Exchange Rate" rules={[{ required: true }]}>
            <InputNumber style={{ width: '100%' }} min={0} step={0.0001} precision={4} placeholder="Enter rate" />
          </Form.Item>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="effectiveDate" label="Effective Date" rules={[{ required: true }]}>
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="expiryDate" label="Expiry Date">
                <DatePicker style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <Modal
        title={`Rate History: ${selectedPair?.from}/${selectedPair?.to}`}
        open={historyModalVisible}
        onCancel={() => setHistoryModalVisible(false)}
        footer={null}
        width={600}
      >
        <Table
          columns={historyColumns}
          dataSource={history}
          rowKey="id"
          pagination={false}
          size="small"
        />
      </Modal>
    </div>
  );
};

export default ExchangeRateConfig;
