import { create } from 'zustand';
import type { BankTransaction, Transaction } from '@/types/accounting';
import type { MatchSuggestion } from '@/types/ui';

interface ReconciliationState {
  // Selection state
  selectedBankTransactions: string[];
  selectedLedgerTransactions: string[];

  // Match suggestions from backend
  matchSuggestions: MatchSuggestion[];

  // Current bank account being reconciled
  activeBankAccountId: string | null;

  // Period being reconciled
  reconciliationPeriod: { start: string; end: string } | null;

  // View state
  viewMode: 'list' | 'side-by-side';

  // Pending matches (before save)
  pendingMatches: PendingMatch[];

  // Actions
  selectBankTransaction: (id: string) => void;
  deselectBankTransaction: (id: string) => void;
  toggleBankTransaction: (id: string) => void;
  clearBankSelection: () => void;

  selectLedgerTransaction: (id: string) => void;
  deselectLedgerTransaction: (id: string) => void;
  toggleLedgerTransaction: (id: string) => void;
  clearLedgerSelection: () => void;

  clearAllSelections: () => void;

  setMatchSuggestions: (suggestions: MatchSuggestion[]) => void;
  setActiveBankAccount: (id: string | null) => void;
  setReconciliationPeriod: (period: { start: string; end: string } | null) => void;
  setViewMode: (mode: 'list' | 'side-by-side') => void;

  addPendingMatch: (match: PendingMatch) => void;
  removePendingMatch: (bankTransactionId: string) => void;
  clearPendingMatches: () => void;

  // Reset entire state
  resetReconciliation: () => void;
}

interface PendingMatch {
  bankTransactionId: string;
  bankTransaction?: BankTransaction;
  ledgerTransactionId?: string;
  ledgerTransaction?: Transaction;
  matchType: 'existing' | 'new';
  newTransaction?: {
    description: string;
    accountId: string;
  };
}

const initialState = {
  selectedBankTransactions: [],
  selectedLedgerTransactions: [],
  matchSuggestions: [],
  activeBankAccountId: null,
  reconciliationPeriod: null,
  viewMode: 'side-by-side' as const,
  pendingMatches: [],
};

export const useReconciliationStore = create<ReconciliationState>()((set) => ({
  ...initialState,

  // Bank transaction selection
  selectBankTransaction: (id) =>
    set((state) => ({
      selectedBankTransactions: [...state.selectedBankTransactions, id],
    })),

  deselectBankTransaction: (id) =>
    set((state) => ({
      selectedBankTransactions: state.selectedBankTransactions.filter((i) => i !== id),
    })),

  toggleBankTransaction: (id) =>
    set((state) => ({
      selectedBankTransactions: state.selectedBankTransactions.includes(id)
        ? state.selectedBankTransactions.filter((i) => i !== id)
        : [...state.selectedBankTransactions, id],
    })),

  clearBankSelection: () =>
    set({ selectedBankTransactions: [] }),

  // Ledger transaction selection
  selectLedgerTransaction: (id) =>
    set((state) => ({
      selectedLedgerTransactions: [...state.selectedLedgerTransactions, id],
    })),

  deselectLedgerTransaction: (id) =>
    set((state) => ({
      selectedLedgerTransactions: state.selectedLedgerTransactions.filter((i) => i !== id),
    })),

  toggleLedgerTransaction: (id) =>
    set((state) => ({
      selectedLedgerTransactions: state.selectedLedgerTransactions.includes(id)
        ? state.selectedLedgerTransactions.filter((i) => i !== id)
        : [...state.selectedLedgerTransactions, id],
    })),

  clearLedgerSelection: () =>
    set({ selectedLedgerTransactions: [] }),

  clearAllSelections: () =>
    set({ selectedBankTransactions: [], selectedLedgerTransactions: [] }),

  // Other state management
  setMatchSuggestions: (matchSuggestions) =>
    set({ matchSuggestions }),

  setActiveBankAccount: (activeBankAccountId) =>
    set({ activeBankAccountId }),

  setReconciliationPeriod: (reconciliationPeriod) =>
    set({ reconciliationPeriod }),

  setViewMode: (viewMode) =>
    set({ viewMode }),

  addPendingMatch: (match) =>
    set((state) => ({
      pendingMatches: [...state.pendingMatches, match],
      selectedBankTransactions: state.selectedBankTransactions.filter(
        (id) => id !== match.bankTransactionId
      ),
      selectedLedgerTransactions: match.ledgerTransactionId
        ? state.selectedLedgerTransactions.filter(
            (id) => id !== match.ledgerTransactionId
          )
        : state.selectedLedgerTransactions,
    })),

  removePendingMatch: (bankTransactionId) =>
    set((state) => ({
      pendingMatches: state.pendingMatches.filter(
        (m) => m.bankTransactionId !== bankTransactionId
      ),
    })),

  clearPendingMatches: () =>
    set({ pendingMatches: [] }),

  resetReconciliation: () =>
    set(initialState),
}));

// Selector hooks
export const useSelectedBankTransactions = () =>
  useReconciliationStore((state) => state.selectedBankTransactions);

export const useSelectedLedgerTransactions = () =>
  useReconciliationStore((state) => state.selectedLedgerTransactions);

export const useMatchSuggestions = () =>
  useReconciliationStore((state) => state.matchSuggestions);

export const usePendingMatches = () =>
  useReconciliationStore((state) => state.pendingMatches);
