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

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

const mockTransactions = [
  {
    id: '1',
    transactionNo: 'TXN-2026-001',
    type: 'income',
    category: 'Sales Revenue',
    amount: 12500,
    status: 'completed',
    description: 'Product sales revenue',
    date: '2026-03-18',
    createdAt: '2026-03-18',
  },
  {
    id: '2',
    transactionNo: 'TXN-2026-002',
    type: 'expense',
    category: 'Product Cost',
    amount: 8500,
    status: 'completed',
    description: 'Product purchase cost',
    date: '2026-03-17',
    createdAt: '2026-03-17',
  },
  {
    id: '3',
    transactionNo: 'TXN-2026-003',
    type: 'expense',
    category: 'Shipping Cost',
    amount: 1200,
    status: 'completed',
    description: 'Shipping and logistics cost',
    date: '2026-03-16',
    createdAt: '2026-03-16',
  },
  {
    id: '4',
    transactionNo: 'TXN-2026-004',
    type: 'income',
    category: 'Refund',
    amount: 350,
    status: 'pending',
    description: 'Customer refund',
    date: '2026-03-15',
    createdAt: '2026-03-15',
  },
];

const mockSettlements = [
  {
    id: '1',
    settlementNo: 'SET-2026-001',
    platform: 'Amazon',
    period: '2026-03-01 to 2026-03-15',
    totalAmount: 45000,
    fee: 2250,
    netAmount: 42750,
    status: 'completed',
    createdAt: '2026-03-16',
  },
  {
    id: '2',
    settlementNo: 'SET-2026-002',
    platform: 'eBay',
    period: '2026-03-01 to 2026-03-15',
    totalAmount: 28000,
    fee: 1400,
    netAmount: 26600,
    status: 'pending',
    createdAt: '2026-03-16',
  },
  {
    id: '3',
    settlementNo: 'SET-2026-003',
    platform: 'Shopee',
    period: '2026-02-16 to 2026-02-28',
    totalAmount: 32000,
    fee: 1600,
    netAmount: 30400,
    status: 'completed',
    createdAt: '2026-03-01',
  },
];

const FinancePage: React.FC = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [isDetailModalVisible, setIsDetailModalVisible] = useState(false);
  const [selectedTransaction, setSelectedTransaction] = useState<any>(null);
  const [activeTab, setActiveTab] = useState('transactions');
  const [searchKeyword, setSearchKeyword] = useState('');

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

  const handleCreateTransaction = () => {
    message.success('Create transaction form opened');
  };

  const handleEditTransaction = (record: any) => {
    message.success(`Edit transaction ${record.transactionNo}`);
  };

  const handleDeleteTransaction = (record: any) => {
    message.success(`Delete transaction ${record.transactionNo}`);
  };

  const handleReconcile = (record: any) => {
    message.success(`Reconcile transaction ${record.transactionNo}`);
  };

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

  const handleBatchReconcile = () => {
    message.success('Batch reconcile initiated');
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'success';
      case 'pending': return 'processing';
      case 'failed': return 'error';
      case 'cancelled': return 'default';
      default: return 'default';
    }
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'income': return 'success';
      case 'expense': return 'error';
      default: return 'default';
    }
  };

  const transactionColumns = [
    {
      title: 'Transaction No',
      dataIndex: 'transactionNo',
      key: 'transactionNo',
    },
    {
      title: 'Type',
      dataIndex: 'type',
      key: 'type',
      render: (type: string) => (
        <Badge color={getTypeColor(type)} text={type} />
      ),
    },
    {
      title: 'Category',
      dataIndex: 'category',
      key: 'category',
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      key: 'amount',
      render: (value: number) => `$${value.toLocaleString()}`,
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => (
        <Badge status={getStatusColor(status)} text={status} />
      ),
    },
    {
      title: 'Description',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: 'Date',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: 'Actions',
      key: 'actions',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button icon={<EyeOutlined />} onClick={() => handleViewDetail(record)}>View</Button>
          <Button icon={<EditOutlined />} onClick={() => handleEditTransaction(record)}>Edit</Button>
          <Button icon={<SyncOutlined />} onClick={() => handleReconcile(record)}>Reconcile</Button>
          <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteTransaction(record)}>Delete</Button>
        </Space>
      ),
    },
  ];

  const settlementColumns = [
    {
      title: 'Settlement No',
      dataIndex: 'settlementNo',
      key: 'settlementNo',
    },
    {
      title: 'Platform',
      dataIndex: 'platform',
      key: 'platform',
    },
    {
      title: 'Period',
      dataIndex: 'period',
      key: 'period',
    },
    {
      title: 'Total Amount',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (value: number) => `$${value.toLocaleString()}`,
    },
    {
      title: 'Fee',
      dataIndex: 'fee',
      key: 'fee',
      render: (value: number) => `$${value.toLocaleString()}`,
    },
    {
      title: 'Net Amount',
      dataIndex: 'netAmount',
      key: 'netAmount',
      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',
    },
  ];

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

  const filteredTransactions = mockTransactions.filter(transaction =>
    transaction.description.toLowerCase().includes(searchKeyword.toLowerCase()) ||
    transaction.transactionNo.toLowerCase().includes(searchKeyword.toLowerCase())
  );

  return (
    <div className="finance-page">
      <div className="page-header" style={{ marginBottom: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={4}>Finance Management</Title>
        <Space>
          <Button icon={<PlusOutlined />} type="primary" onClick={handleCreateTransaction}>Create Transaction</Button>
          <Button icon={<ReloadOutlined />}>Refresh</Button>
          <Button onClick={handleBatchReconcile} disabled={selectedRowKeys.length === 0}>Batch Reconcile</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 Income"
              value={12850}
              precision={0}
              prefix="$"
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Total Expense"
              value={9700}
              precision={0}
              prefix="$"
              valueStyle={{ color: '#f5222d' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Net Profit"
              value={3150}
              precision={0}
              prefix="$"
              valueStyle={{ color: '#3f8600' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="Pending Settlements"
              value={1}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
        </Row>
      </Card>

      <Card style={{ marginBottom: 24 }}>
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="Transactions" key="transactions">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Select placeholder="Select Type" style={{ width: 150 }}>
                <Option value="all">All Types</Option>
                <Option value="income">Income</Option>
                <Option value="expense">Expense</Option>
              </Select>
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="completed">Completed</Option>
                <Option value="pending">Pending</Option>
                <Option value="failed">Failed</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              rowSelection={rowSelection}
              columns={transactionColumns}
              dataSource={filteredTransactions}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
          <TabPane tab="Settlements" key="settlements">
            <div style={{ display: 'flex', gap: 16, marginBottom: 16, flexWrap: 'wrap' }}>
              <Select placeholder="Select Platform" style={{ width: 150 }}>
                <Option value="all">All Platforms</Option>
                <Option value="amazon">Amazon</Option>
                <Option value="ebay">eBay</Option>
                <Option value="shopee">Shopee</Option>
              </Select>
              <Select placeholder="Select Status" style={{ width: 150 }}>
                <Option value="all">All Status</Option>
                <Option value="completed">Completed</Option>
                <Option value="pending">Pending</Option>
              </Select>
              <RangePicker style={{ width: 300 }} />
            </div>

            <Table
              columns={settlementColumns}
              dataSource={mockSettlements}
              rowKey="id"
              pagination={{
                pageSize: 10,
              }}
            />
          </TabPane>
          <TabPane tab="Reports" key="reports">
            <div style={{ padding: 24, textAlign: 'center' }}>
              <Text type="secondary">Financial reports will be displayed here</Text>
            </div>
          </TabPane>
        </Tabs>
      </Card>

      <Modal
        title={`Transaction Detail - ${selectedTransaction?.transactionNo}`}
        open={isDetailModalVisible}
        onCancel={() => setIsDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsDetailModalVisible(false)}>
            Close
          </Button>,
        ]}
        width={800}
      >
        {selectedTransaction && (
          <div>
            <div style={{ marginBottom: 24 }}>
              <h3>Basic Information</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginTop: 16 }}>
                <div>
                  <Text strong>Transaction No:</Text> {selectedTransaction.transactionNo}
                </div>
                <div>
                  <Text strong>Type:</Text> <Badge color={getTypeColor(selectedTransaction.type)} text={selectedTransaction.type} />
                </div>
                <div>
                  <Text strong>Category:</Text> {selectedTransaction.category}
                </div>
                <div>
                  <Text strong>Amount:</Text> ${selectedTransaction.amount.toLocaleString()}
                </div>
                <div>
                  <Text strong>Status:</Text> <Badge status={getStatusColor(selectedTransaction.status)} text={selectedTransaction.status} />
                </div>
                <div>
                  <Text strong>Date:</Text> {selectedTransaction.date}
                </div>
                <div>
                  <Text strong>Created At:</Text> {selectedTransaction.createdAt}
                </div>
              </div>
            </div>
            <div>
              <h3>Description</h3>
              <div style={{ marginTop: 16 }}>
                <Text>{selectedTransaction.description}</Text>
              </div>
            </div>
            <div style={{ marginTop: 24 }}>
              <h3>Quick Actions</h3>
              <Space size="middle" style={{ marginTop: 16 }}>
                <Button icon={<SyncOutlined />} onClick={() => handleReconcile(selectedTransaction)}>Reconcile</Button>
                <Button icon={<EditOutlined />} onClick={() => handleEditTransaction(selectedTransaction)}>Edit</Button>
              </Space>
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default FinancePage;