import React, { useState, useEffect } from 'react';
import { Table, Button, Input, Select, DatePicker, message, Card, Tabs } from 'antd';
import { SearchOutlined, FilterOutlined, ExportOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { financeDataSource, ReconciliationRecord } from '@/services/financeDataSource';

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

const Reconciliation: React.FC = () => {
  const navigate = useNavigate();
  const [reconciliations, setReconciliations] = useState<Reconciliation[]>([]);
  const [loading, setLoading] = useState(false);
  const [filters, setFilters] = useState({
    platform: '',
    status: '',
    search: '',
    dateRange: null as any,
  });

  useEffect(() => {
    fetchReconciliations();
  }, [filters]);

  const fetchReconciliations = async () => {
    setLoading(true);
    try {
      const data = await financeDataSource.fetchReconciliation(filters);
      setReconciliations(data);
    } catch (error) {
      message.error('Failed to load reconciliations');
    } finally {
      setLoading(false);
    }
  };

  const handleExport = () => {
    message.success('对账记录已导出');
  };

  const handleReconcile = (id: string) => {
    message.success('对账完成');
    fetchReconciliations();
  };

  const columns = [
    {
      title: '对账ID',
      dataIndex: 'reconciliationId',
      key: 'reconciliationId',
    },
    {
      title: '平台',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: '对账期间',
      dataIndex: 'period',
      key: 'period',
    },
    {
      title: '预期金额',
      dataIndex: 'expectedAmount',
      key: 'expectedAmount',
      render: (amount: number) => `$${amount.toFixed(2)}`,
    },
    {
      title: '实际金额',
      dataIndex: 'actualAmount',
      key: 'actualAmount',
      render: (amount: number) => `$${amount.toFixed(2)}`,
    },
    {
      title: '差异',
      dataIndex: 'difference',
      key: 'difference',
      render: (difference: number) => (
        <span style={{ color: difference === 0 ? '#3f8600' : '#cf1322' }}>
          ${difference.toFixed(2)}
        </span>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusMap = {
          reconciled: { text: '已对账', icon: <CheckCircleOutlined style={{ color: '#3f8600' }} />, color: '#3f8600' },
          unreconciled: { text: '未对账', icon: <CloseCircleOutlined style={{ color: '#cf1322' }} />, color: '#cf1322' },
          partial: { text: '部分对账', icon: <CloseCircleOutlined style={{ color: '#fa8c16' }} />, color: '#fa8c16' },
        };
        const statusInfo = statusMap[status as keyof typeof statusMap] || { text: status, icon: null, color: '#000' };
        return (
          <span style={{ color: statusInfo.color }}>
            {statusInfo.icon} {statusInfo.text}
          </span>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: Reconciliation) => (
        <div>
          {record.status !== 'reconciled' && (
            <Button
              type="primary"
              size="small"
              onClick={() => handleReconcile(record.id)}
            >
              对账
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="reconciliation">
      <div className="page-header">
        <h1>对账记录</h1>
        <Button
          type="primary"
          icon={<ExportOutlined />}
          onClick={handleExport}
        >
          导出
        </Button>
      </div>

      <div className="filter-section" style={{ marginBottom: 24, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
        <Search
          placeholder="搜索对账ID或平台"
          style={{ width: 300 }}
          onChange={(e) => setFilters({ ...filters, search: e.target.value })}
        />
        <Select
          placeholder="平台"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, platform: value })}
        >
          <Option value="">全部</Option>
          <Option value="Shopify">Shopify</Option>
          <Option value="Amazon">Amazon</Option>
          <Option value="eBay">eBay</Option>
        </Select>
        <Select
          placeholder="状态"
          style={{ width: 120 }}
          onChange={(value) => setFilters({ ...filters, status: value })}
        >
          <Option value="">全部</Option>
          <Option value="reconciled">已对账</Option>
          <Option value="unreconciled">未对账</Option>
          <Option value="partial">部分对账</Option>
        </Select>
        <RangePicker
          style={{ width: 300 }}
          onChange={(dates) => setFilters({ ...filters, dateRange: dates })}
        />
        <Button
          icon={<FilterOutlined />}
          onClick={fetchReconciliations}
        >
          筛选
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={reconciliations}
        loading={loading}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
      />
    </div>
  );
};

export default Reconciliation;