import { useState } from 'react';
import {
  Typography,
  Button,
  Card,
  Row,
  Col,
  Select,
  DatePicker,
  Space,
  List,
  Checkbox,
  Tag,
  Statistic,
  Modal,
  Form,
  Input,
  message,
  Tooltip,
  Alert,
  Skeleton,
  Empty,
} from 'antd';
import {
  SwapOutlined,
  PlusOutlined,
  UndoOutlined,
  CheckOutlined,
  LinkOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { useCompany } from '@/hooks/useCompany';
import { useReconciliationStore } from '@/stores/reconciliationStore';
import { useCompanyStore } from '@/stores/companyStore';
import { useActiveBankConnections } from '@/api/queries/bankConnectionQueries';
import { usePendingBankTransactions } from '@/api/queries/bankTransactionQueries';
import { formatCurrency, formatDate } from '@/lib/formatters';
import { accountingColors } from '@/styles/theme';
import type { BankTransaction } from '@/types/accounting';
import { DemoDataDisclaimer } from '@/components/shared/DemoDataDisclaimer';
import { PageHeader } from '@/components/shared/PageHeader';

const { Text } = Typography;
const { RangePicker } = DatePicker;

// Type for ledger entries (API not implemented yet)
interface LedgerEntry {
  id: string;
  date: string;
  description: string;
  amount: number;
  accountId: string;
  accountName: string;
  transactionNumber: string;
  isReconciled: boolean;
}

// Type for match suggestions (API not implemented yet)
interface MatchSuggestion {
  bankTransactionId: string;
  ledgerEntryId: string;
  confidence: number;
  reason: string;
}

export default function Bankafstemning() {
  const { company } = useCompany();
  const { activeCompany } = useCompanyStore();

  // Fetch data from API
  const { data: bankConnections = [], isLoading: connectionsLoading } = useActiveBankConnections(activeCompany?.id);
  const { data: pendingTransactions = [], isLoading: transactionsLoading } = usePendingBankTransactions(activeCompany?.id);

  const isLoading = connectionsLoading || transactionsLoading;

  // Convert bankConnections to bankAccounts format
  const bankAccounts = bankConnections.flatMap(conn =>
    (conn.accounts || []).map(acc => ({
      id: acc.accountId,
      companyId: activeCompany?.id || '',
      name: acc.name || acc.iban,
      bankName: conn.aspspName,
      accountNumber: acc.iban,
      iban: acc.iban,
      currency: acc.currency,
      ledgerAccountId: acc.linkedAccountId || '',
      isActive: conn.isActive,
    }))
  );

  // Convert pendingTransactions to display format
  const allBankTransactions: BankTransaction[] = pendingTransactions.map(tx => ({
    id: tx.id,
    bankAccountId: tx.bankAccountId,
    date: tx.date,
    valueDate: tx.date,
    description: tx.description,
    amount: tx.amount,
    balance: 0, // Not available from API yet
    counterparty: tx.counterparty,
    isReconciled: tx.isBooked,
    importedAt: new Date().toISOString(),
  }));

  // For ledgerEntries and suggestions - show empty state as they are not implemented in API yet
  const allLedgerEntries: LedgerEntry[] = [];
  const matchSuggestions: MatchSuggestion[] = [];

  const [selectedBankAccount, setSelectedBankAccount] = useState<string>('');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().startOf('month'),
    dayjs().endOf('month'),
  ]);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [selectedBankTx, setSelectedBankTx] = useState<BankTransaction | null>(null);
  const [form] = Form.useForm();

  const {
    selectedBankTransactions,
    selectedLedgerTransactions,
    toggleBankTransaction,
    toggleLedgerTransaction,
    clearAllSelections,
    pendingMatches,
    addPendingMatch,
    removePendingMatch,
  } = useReconciliationStore();

  // Set default selected bank account when accounts are loaded
  const effectiveSelectedAccount = selectedBankAccount || (bankAccounts.length > 0 ? bankAccounts[0].id : '');

  // Filter transactions
  const bankTransactions = allBankTransactions.filter(
    (tx) => tx.bankAccountId === effectiveSelectedAccount && !tx.isReconciled
  );
  const ledgerEntries = allLedgerEntries.filter((entry) => !entry.isReconciled);

  // Calculate totals
  const bankTotal = bankTransactions.reduce((sum, tx) => sum + tx.amount, 0);
  const ledgerTotal = ledgerEntries.reduce((sum, entry) => sum + entry.amount, 0);
  const difference = bankTotal - ledgerTotal;

  // Check if selected items can be matched
  const canMatch =
    selectedBankTransactions.length === 1 && selectedLedgerTransactions.length === 1;

  // Get suggestion for a bank transaction
  const getSuggestion = (bankTxId: string) => {
    return matchSuggestions.find((s) => s.bankTransactionId === bankTxId);
  };

  const handleMatch = () => {
    if (!canMatch) return;

    const bankTx = bankTransactions.find((tx) => tx.id === selectedBankTransactions[0]);
    const ledgerEntry = ledgerEntries.find((e) => e.id === selectedLedgerTransactions[0]);

    if (bankTx && ledgerEntry) {
      addPendingMatch({
        bankTransactionId: bankTx.id,
        ledgerTransactionId: ledgerEntry.id,
        matchType: 'existing',
      });
      message.success('Match tilføjet');
    }
  };

  const handleCreateEntry = (bankTx: BankTransaction) => {
    setSelectedBankTx(bankTx);
    form.setFieldsValue({
      date: dayjs(bankTx.date),
      description: bankTx.description,
      amount: Math.abs(bankTx.amount),
    });
    setIsCreateModalOpen(true);
  };

  const handleSubmitCreate = async () => {
    try {
      const values = await form.validateFields();

      // TODO: Backend mutation for creating a journal entry from bank transaction is needed.
      // This should create a JournalEntryDraft and then post it, linking it to the bank transaction.
      if (selectedBankTx) {
        addPendingMatch({
          bankTransactionId: selectedBankTx.id,
          matchType: 'new',
          newTransaction: {
            description: values.description,
            accountId: values.accountId,
          },
        });
      }

      message.success('Postering tilfojet til afventende matches');
      setIsCreateModalOpen(false);
      setSelectedBankTx(null);
    } catch (error) {
      if (error instanceof Error) {
        message.error(`Fejl: ${error.message}`);
      }
    }
  };

  const handleSaveAll = () => {
    if (pendingMatches.length === 0) {
      message.warning('Ingen matches at gemme');
      return;
    }
    // TODO: Backend mutation for saving reconciliation matches is not yet implemented.
    // The mutation should accept a list of bank transaction IDs matched to ledger entries,
    // mark them as reconciled, and create journal entries for new transactions.
    message.info('Denne funktion er under udvikling. Afstemninger kan endnu ikke gemmes til backend.');
  };

  const handleApplySuggestion = (suggestion: MatchSuggestion) => {
    addPendingMatch({
      bankTransactionId: suggestion.bankTransactionId,
      ledgerTransactionId: suggestion.ledgerEntryId,
      matchType: 'existing',
    });
    message.success('Forslag anvendt');
  };

  // Loading state
  if (isLoading) {
    return (
      <div>
        <Skeleton active paragraph={{ rows: 2 }} />
        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={12}><Skeleton active paragraph={{ rows: 8 }} /></Col>
          <Col span={12}><Skeleton active paragraph={{ rows: 8 }} /></Col>
        </Row>
      </div>
    );
  }

  // Empty state - no bank connections
  if (bankAccounts.length === 0) {
    return (
      <Empty
        description="Ingen bankforbindelser. Opret forbindelse til din bank under Indstillinger."
      />
    );
  }

  return (
    <div>
      <PageHeader
        title="Bankafstemning"
        subtitle={company?.name}
        breadcrumbs={[{ title: 'Bank', path: '/bankafstemning' }, { title: 'Bankafstemning' }]}
        extra={
          <Space>
            <Button
              icon={<UndoOutlined />}
              onClick={clearAllSelections}
              disabled={
                selectedBankTransactions.length === 0 &&
                selectedLedgerTransactions.length === 0
              }
            >
              Nulstil valg
            </Button>
            <Button
              type="primary"
              icon={<CheckOutlined />}
              onClick={handleSaveAll}
              disabled={pendingMatches.length === 0}
            >
              Gem afstemninger ({pendingMatches.length})
            </Button>
          </Space>
        }
      />

      <DemoDataDisclaimer message="Bankafstemning er delvist implementeret. Gem-funktionen er under udvikling." />

      {/* Filters */}
      <Space style={{ marginBottom: 16 }} wrap>
        <Select
          value={effectiveSelectedAccount}
          onChange={setSelectedBankAccount}
          style={{ width: 250 }}
          options={bankAccounts.map((acc) => ({
            value: acc.id,
            label: `${acc.bankName} - ${acc.name}`,
          }))}
        />
        <RangePicker
          value={dateRange}
          onChange={(dates) => setDateRange(dates as [dayjs.Dayjs, dayjs.Dayjs])}
          format="DD/MM/YYYY"
        />
      </Space>

      {/* Summary */}
      <Row gutter={16} style={{ marginBottom: 16 }}>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="Bank (uafstemt)"
              value={bankTotal}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color: bankTotal >= 0 ? accountingColors.credit : accountingColors.debit,
              }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="Bogføring (uafstemt)"
              value={ledgerTotal}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color: ledgerTotal >= 0 ? accountingColors.credit : accountingColors.debit,
              }}
            />
          </Card>
        </Col>
        <Col span={8}>
          <Card size="small">
            <Statistic
              title="Difference"
              value={difference}
              precision={2}
              formatter={(value) => formatCurrency(value as number)}
              valueStyle={{
                color:
                  Math.abs(difference) < 0.01
                    ? accountingColors.credit
                    : accountingColors.debit,
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* Suggestions Alert */}
      {matchSuggestions.length > 0 && (
        <Alert
          message={
            <Space>
              <BulbOutlined />
              <Text strong>{matchSuggestions.length} automatiske matchforslag fundet</Text>
            </Space>
          }
          type="info"
          style={{ marginBottom: 16 }}
          action={
            <Button
              size="small"
              onClick={() => matchSuggestions.forEach(handleApplySuggestion)}
            >
              Anvend alle
            </Button>
          }
        />
      )}

      {/* Match Button */}
      <div style={{ textAlign: 'center', marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<LinkOutlined />}
          size="large"
          onClick={handleMatch}
          disabled={!canMatch}
        >
          Match valgte ({selectedBankTransactions.length} bank,{' '}
          {selectedLedgerTransactions.length} bogføring)
        </Button>
      </div>

      {/* Side-by-side panels */}
      <Row gutter={16}>
        {/* Bank Transactions */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <Text strong>Banktransaktioner</Text>
                <Tag color="blue">{bankTransactions.length} uafstemte</Tag>
              </Space>
            }
            size="small"
            bodyStyle={{ padding: 0, maxHeight: 500, overflow: 'auto' }}
          >
            {bankTransactions.length === 0 ? (
              <Empty
                description="Ingen uafstemte banktransaktioner"
                style={{ padding: 24 }}
              />
            ) : (
              <List
                dataSource={bankTransactions}
                renderItem={(tx) => {
                  const suggestion = getSuggestion(tx.id);
                  const isPending = pendingMatches.some(
                    (m) => m.bankTransactionId === tx.id
                  );
                  const isSelected = selectedBankTransactions.includes(tx.id);

                  if (isPending) return null;

                  return (
                    <List.Item
                      style={{
                        padding: '8px 16px',
                        cursor: 'pointer',
                        backgroundColor: isSelected ? '#e6f4ff' : undefined,
                      }}
                      onClick={() => toggleBankTransaction(tx.id)}
                    >
                      <div style={{ width: '100%' }}>
                        <div
                          style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'flex-start',
                          }}
                        >
                          <Space>
                            <Checkbox checked={isSelected} />
                            <div>
                              <Text style={{ display: 'block' }}>
                                {tx.description}
                              </Text>
                              <Text type="secondary" style={{ fontSize: 12 }}>
                                {formatDate(tx.date)} - {tx.counterparty || 'Ukendt'}
                              </Text>
                            </div>
                          </Space>
                          <div style={{ textAlign: 'right' }}>
                            <Text
                              strong
                              className="tabular-nums"
                              style={{
                                color:
                                  tx.amount >= 0
                                    ? accountingColors.credit
                                    : accountingColors.debit,
                              }}
                            >
                              {formatCurrency(tx.amount, { showSign: true })}
                            </Text>
                            {suggestion && (
                              <div>
                                <Tooltip title={suggestion.reason}>
                                  <Tag
                                    color="green"
                                    style={{ cursor: 'pointer', marginTop: 4 }}
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      handleApplySuggestion(suggestion);
                                    }}
                                  >
                                    <BulbOutlined />{' '}
                                    {Math.round(suggestion.confidence * 100)}% match
                                  </Tag>
                                </Tooltip>
                              </div>
                            )}
                          </div>
                        </div>
                        <div style={{ marginTop: 4 }}>
                          <Button
                            type="link"
                            size="small"
                            icon={<PlusOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleCreateEntry(tx);
                            }}
                          >
                            Opret postering
                          </Button>
                        </div>
                      </div>
                    </List.Item>
                  );
                }}
              />
            )}
          </Card>
        </Col>

        {/* Ledger Entries */}
        <Col span={12}>
          <Card
            title={
              <Space>
                <Text strong>Bogføringsposter</Text>
                <Tag color="orange">{ledgerEntries.length} uafstemte</Tag>
              </Space>
            }
            size="small"
            bodyStyle={{ padding: 0, maxHeight: 500, overflow: 'auto' }}
          >
            {ledgerEntries.length === 0 ? (
              <Empty
                description="Ingen uafstemte bogføringsposter (API ikke implementeret endnu)"
                style={{ padding: 24 }}
              />
            ) : (
              <List
                dataSource={ledgerEntries}
                renderItem={(entry) => {
                  const isPending = pendingMatches.some(
                    (m) => m.ledgerTransactionId === entry.id
                  );
                  const isSelected = selectedLedgerTransactions.includes(entry.id);

                  if (isPending) return null;

                  return (
                    <List.Item
                      style={{
                        padding: '8px 16px',
                        cursor: 'pointer',
                        backgroundColor: isSelected ? '#e6f4ff' : undefined,
                      }}
                      onClick={() => toggleLedgerTransaction(entry.id)}
                    >
                      <div style={{ width: '100%' }}>
                        <div
                          style={{
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'flex-start',
                          }}
                        >
                          <Space>
                            <Checkbox checked={isSelected} />
                            <div>
                              <Text style={{ display: 'block' }}>
                                {entry.description}
                              </Text>
                              <Text type="secondary" style={{ fontSize: 12 }}>
                                {formatDate(entry.date)} - Bilag{' '}
                                {entry.transactionNumber}
                              </Text>
                            </div>
                          </Space>
                          <Text
                            strong
                            className="tabular-nums"
                            style={{
                              color:
                                entry.amount >= 0
                                  ? accountingColors.credit
                                  : accountingColors.debit,
                            }}
                          >
                            {formatCurrency(entry.amount, { showSign: true })}
                          </Text>
                        </div>
                      </div>
                    </List.Item>
                  );
                }}
              />
            )}
          </Card>
        </Col>
      </Row>

      {/* Pending Matches */}
      {pendingMatches.length > 0 && (
        <Card
          title={
            <Space>
              <Text strong>Afventende matches</Text>
              <Tag color="blue">{pendingMatches.length}</Tag>
            </Space>
          }
          size="small"
          style={{ marginTop: 16 }}
        >
          <List
            dataSource={pendingMatches}
            renderItem={(match) => {
              const bankTx = allBankTransactions.find(
                (tx) => tx.id === match.bankTransactionId
              );
              const ledgerEntry = allLedgerEntries.find(
                (e) => e.id === match.ledgerTransactionId
              );

              return (
                <List.Item
                  actions={[
                    <Button
                      type="link"
                      danger
                      size="small"
                      onClick={() => removePendingMatch(match.bankTransactionId)}
                    >
                      Fjern
                    </Button>,
                  ]}
                >
                  <Space split={<SwapOutlined />}>
                    <Text>
                      Bank: {bankTx?.description} ({formatCurrency(bankTx?.amount || 0)})
                    </Text>
                    {match.matchType === 'existing' ? (
                      <Text>
                        Bilag: {ledgerEntry?.transactionNumber} - {ledgerEntry?.description}
                      </Text>
                    ) : (
                      <Tag color="green">Ny postering oprettes</Tag>
                    )}
                  </Space>
                </List.Item>
              );
            }}
          />
        </Card>
      )}

      {/* Create Entry Modal */}
      <Modal
        title="Opret bogforingspost"
        open={isCreateModalOpen}
        onCancel={() => {
          setIsCreateModalOpen(false);
          setSelectedBankTx(null);
        }}
        onOk={handleSubmitCreate}
        okText="Opret og match"
        cancelText="Annuller"
      >
        {selectedBankTx && (
          <Alert
            message={
              <Space direction="vertical" size={0}>
                <Text>Banktransaktion:</Text>
                <Text strong>{selectedBankTx.description}</Text>
                <Text>
                  {formatDate(selectedBankTx.date)} -{' '}
                  {formatCurrency(selectedBankTx.amount, { showSign: true })}
                </Text>
              </Space>
            }
            type="info"
            style={{ marginBottom: 16 }}
          />
        )}
        <Form form={form} layout="vertical">
          <Form.Item
            name="date"
            label="Dato"
            rules={[{ required: true }]}
          >
            <DatePicker format="DD/MM/YYYY" style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="description"
            label="Beskrivelse"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="accountId"
            label="Modkonto"
            rules={[{ required: true }]}
          >
            <Select
              placeholder="Vælg konto"
              options={[
                { value: '6100', label: '6100 - Husleje' },
                { value: '6800', label: '6800 - Kontorartikler' },
                { value: '5000', label: '5000 - Varekøb' },
                { value: '4000', label: '4000 - Salg' },
              ]}
            />
          </Form.Item>
          <Form.Item name="vatCode" label="Momskode">
            <Select
              placeholder="Vælg momskode"
              allowClear
              options={[
                { value: 'K25', label: 'K25 - Indgående moms 25%' },
                { value: 'S25', label: 'S25 - Udgående moms 25%' },
                { value: 'NONE', label: 'Ingen moms' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
