// HurtigBogforing - Quick Booking Page for simple bank transaction processing

import { useState, useEffect, useMemo } from 'react';
import {
  Card,
  Row,
  Col,
  Select,
  Typography,
  Space,
  Badge,
  Statistic,
  Divider,
  Switch,
  message,
  Spin,
} from 'antd';
import {
  BankOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  ThunderboltOutlined,
} from '@ant-design/icons';
import { formatCurrency } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';
import type { Account, BankAccount } from '@/types/accounting';
import type { GeneratedTransaction } from '@/lib/accounting';
import {
  BankTransactionList,
  QuickBookModal,
  SplitBookModal,
} from '@/components/simple-booking';
import {
  useSimpleBookingStore,
  useUnbookedTransactions,
  type PendingBankTransaction,
} from '@/stores/simpleBookingStore';

const { Title, Text } = Typography;

// Mock data for development - replace with actual API calls
const MOCK_BANK_ACCOUNTS: BankAccount[] = [
  {
    id: 'bank-1',
    name: 'Hovedkonto',
    accountNumber: '1000',
    bankName: 'Danske Bank',
    iban: 'DK12 3456 7890 1234 56',
    currency: 'DKK',
    balance: 125000,
    lastSyncedAt: new Date().toISOString(),
    isActive: true,
  },
  {
    id: 'bank-2',
    name: 'Opsparingskonto',
    accountNumber: '1010',
    bankName: 'Danske Bank',
    iban: 'DK12 3456 7890 1234 99',
    currency: 'DKK',
    balance: 50000,
    lastSyncedAt: new Date().toISOString(),
    isActive: true,
  },
];

const MOCK_ACCOUNTS: Account[] = [
  { id: 'acc-1', accountNumber: '1000', name: 'Bank', type: 'asset', balance: 125000 },
  { id: 'acc-2', accountNumber: '4000', name: 'Salg af varer', type: 'revenue', balance: 0 },
  { id: 'acc-3', accountNumber: '4100', name: 'Salg af ydelser', type: 'revenue', balance: 0 },
  { id: 'acc-4', accountNumber: '5000', name: 'Varekoeb', type: 'cogs', balance: 0 },
  { id: 'acc-5', accountNumber: '6100', name: 'Husleje', type: 'expense', balance: 0 },
  { id: 'acc-6', accountNumber: '6200', name: 'El og varme', type: 'expense', balance: 0 },
  { id: 'acc-7', accountNumber: '6300', name: 'Vedligeholdelse', type: 'expense', balance: 0 },
  { id: 'acc-8', accountNumber: '6400', name: 'Administration', type: 'expense', balance: 0 },
  { id: 'acc-9', accountNumber: '6500', name: 'IT og software', type: 'expense', balance: 0 },
  { id: 'acc-10', accountNumber: '6800', name: 'Kontorartikler', type: 'expense', balance: 0 },
  { id: 'acc-11', accountNumber: '7100', name: 'Loen', type: 'personnel', balance: 0 },
  { id: 'acc-12', accountNumber: '7200', name: 'ATP', type: 'personnel', balance: 0 },
  { id: 'acc-13', accountNumber: '8100', name: 'Renteindtaegter', type: 'financial', balance: 0 },
  { id: 'acc-14', accountNumber: '8200', name: 'Renteudgifter', type: 'financial', balance: 0 },
];

const MOCK_PENDING_TRANSACTIONS: PendingBankTransaction[] = [
  {
    id: 'tx-1',
    date: '2025-01-15',
    amount: -15000,
    description: 'HUSLEJE JANUAR EJENDOM APS',
    counterparty: 'Ejendom ApS',
    bankAccountId: 'bank-1',
    bankAccountNumber: '1000',
    isBooked: false,
  },
  {
    id: 'tx-2',
    date: '2025-01-14',
    amount: -499,
    description: 'MOBILEPAY STAPLES',
    counterparty: 'Staples',
    bankAccountId: 'bank-1',
    bankAccountNumber: '1000',
    isBooked: false,
  },
  {
    id: 'tx-3',
    date: '2025-01-13',
    amount: 25000,
    description: 'OVERFOERSEL FRA KUNDE ABC APS',
    counterparty: 'ABC ApS',
    bankAccountId: 'bank-1',
    bankAccountNumber: '1000',
    isBooked: false,
  },
  {
    id: 'tx-4',
    date: '2025-01-12',
    amount: -10000,
    description: 'SAMLET BETALING DIVERSE',
    counterparty: 'Diverse leverandoerer',
    bankAccountId: 'bank-1',
    bankAccountNumber: '1000',
    isBooked: false,
  },
  {
    id: 'tx-5',
    date: '2025-01-11',
    amount: -2500,
    description: 'ELREGNING JANUAR',
    counterparty: 'Andel Energi',
    bankAccountId: 'bank-1',
    bankAccountNumber: '1000',
    isBooked: false,
  },
  {
    id: 'tx-6',
    date: '2025-01-10',
    amount: 12500,
    description: 'FAKTURA 2025-001',
    counterparty: 'XYZ Holding A/S',
    bankAccountId: 'bank-1',
    bankAccountNumber: '1000',
    isBooked: true,
    bookedAt: '2025-01-10T14:30:00Z',
    transactionId: 'booked-tx-1',
  },
];

export function HurtigBogforing() {
  const [selectedBankAccountId, setSelectedBankAccountId] = useState<string | undefined>(
    MOCK_BANK_ACCOUNTS[0]?.id
  );
  const [showBooked, setShowBooked] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  const {
    setPendingTransactions,
    openSimpleBooking,
    openSplitBooking,
    markAsBooked,
    setSaving,
  } = useSimpleBookingStore();

  const unbookedTransactions = useUnbookedTransactions();

  // Initialize with mock data
  useEffect(() => {
    setPendingTransactions(MOCK_PENDING_TRANSACTIONS);
  }, [setPendingTransactions]);

  // Filter transactions by selected bank account
  const filteredTransactions = useMemo(() => {
    if (!selectedBankAccountId) return [];
    return MOCK_PENDING_TRANSACTIONS.filter(
      (tx) => tx.bankAccountId === selectedBankAccountId
    );
  }, [selectedBankAccountId]);

  const selectedBankAccount = MOCK_BANK_ACCOUNTS.find(
    (ba) => ba.id === selectedBankAccountId
  );

  // Stats
  const unbookedCount = filteredTransactions.filter((tx) => !tx.isBooked).length;
  const bookedCount = filteredTransactions.filter((tx) => tx.isBooked).length;
  const totalUnbookedAmount = filteredTransactions
    .filter((tx) => !tx.isBooked)
    .reduce((sum, tx) => sum + tx.amount, 0);

  // Handle booking submission
  const handleBookingSubmit = async (transaction: GeneratedTransaction) => {
    setSaving(true);
    try {
      // Simulate API call
      await new Promise((resolve) => setTimeout(resolve, 500));

      // Mark as booked
      markAsBooked(transaction.bankTransactionId, `tx-${Date.now()}`);
      message.success('Transaktion bogfoert');
    } catch (error) {
      message.error('Fejl ved bogfoering');
    } finally {
      setSaving(false);
    }
  };

  // Bank account selector options
  const bankAccountOptions = MOCK_BANK_ACCOUNTS.map((ba) => ({
    value: ba.id,
    label: (
      <Space>
        <BankOutlined />
        <span>{ba.name}</span>
        <Text type="secondary">({ba.accountNumber})</Text>
      </Space>
    ),
  }));

  return (
    <div className="hurtig-bogforing-page">
      {/* Header */}
      <div style={{ marginBottom: 24 }}>
        <Title level={3} style={{ marginBottom: 8 }}>
          <ThunderboltOutlined style={{ marginRight: 8 }} />
          Hurtig Bogfoering
        </Title>
        <Text type="secondary">
          Bogfoer banktransaktioner hurtigt med et enkelt klik
        </Text>
      </div>

      {/* Stats and controls */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="Bankkonto"
              valueRender={() => (
                <Select
                  style={{ width: '100%' }}
                  value={selectedBankAccountId}
                  onChange={setSelectedBankAccountId}
                  options={bankAccountOptions}
                />
              )}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="Ubogfoerte transaktioner"
              value={unbookedCount}
              prefix={<ClockCircleOutlined />}
              valueStyle={{ color: unbookedCount > 0 ? accountingColors.warning : accountingColors.credit }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="Bogfoerte transaktioner"
              value={bookedCount}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: accountingColors.credit }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small">
            <Statistic
              title="Ubogfoert beloeb"
              value={formatCurrency(totalUnbookedAmount)}
              valueStyle={{ color: totalUnbookedAmount < 0 ? accountingColors.debit : accountingColors.credit }}
            />
          </Card>
        </Col>
      </Row>

      {/* Bank account info */}
      {selectedBankAccount && (
        <Card size="small" style={{ marginBottom: 16 }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space>
                <BankOutlined style={{ fontSize: 20 }} />
                <div>
                  <Text strong>{selectedBankAccount.name}</Text>
                  <Text type="secondary" style={{ marginLeft: 8 }}>
                    {selectedBankAccount.bankName} • {selectedBankAccount.iban}
                  </Text>
                </div>
              </Space>
            </Col>
            <Col>
              <Space>
                <Text>Vis boerte:</Text>
                <Switch checked={showBooked} onChange={setShowBooked} />
              </Space>
            </Col>
          </Row>
        </Card>
      )}

      {/* Transaction list */}
      <Spin spinning={isLoading}>
        <BankTransactionList
          transactions={filteredTransactions}
          onBook={openSimpleBooking}
          onSplit={openSplitBooking}
          showBooked={showBooked}
        />
      </Spin>

      {/* Modals */}
      <QuickBookModal accounts={MOCK_ACCOUNTS} onSubmit={handleBookingSubmit} />
      <SplitBookModal accounts={MOCK_ACCOUNTS} onSubmit={handleBookingSubmit} />
    </div>
  );
}

export default HurtigBogforing;
