"use client";

import { useMemo, useState, useCallback } from "react";
import type { Invoice, InvoiceStatus } from "@customer-portal/domain/billing";

export type InvoiceStatusFilter = InvoiceStatus | "all";

export interface InvoicesSummaryStats {
  total: number;
  paid: number;
  unpaid: number;
  overdue: number;
}

export interface UseInvoicesFilterOptions {
  invoices: Invoice[] | undefined;
}

export interface UseInvoicesFilterResult {
  // Filter state
  searchTerm: string;
  setSearchTerm: (value: string) => void;
  statusFilter: InvoiceStatusFilter;
  setStatusFilter: (value: InvoiceStatusFilter) => void;

  // Computed values
  filteredInvoices: Invoice[];
  stats: InvoicesSummaryStats;
  hasActiveFilters: boolean;

  // Actions
  clearFilters: () => void;
}

/**
 * useInvoicesFilter - Hook for filtering and computing stats on invoices.
 *
 * Provides search, status filtering, summary statistics, and clear functionality
 * for invoice list pages.
 */
export function useInvoicesFilter({ invoices }: UseInvoicesFilterOptions): UseInvoicesFilterResult {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<InvoiceStatusFilter>("all");

  const hasActiveFilters = searchTerm.trim() !== "" || statusFilter !== "all";

  const clearFilters = useCallback(() => {
    setSearchTerm("");
    setStatusFilter("all");
  }, []);

  const stats = useMemo<InvoicesSummaryStats>(() => {
    if (!invoices || invoices.length === 0) {
      return { total: 0, paid: 0, unpaid: 0, overdue: 0 };
    }

    return invoices.reduce(
      (acc, invoice) => {
        acc.total++;
        if (invoice.status === "Paid") {
          acc.paid++;
        } else if (invoice.status === "Unpaid") {
          acc.unpaid++;
        } else if (invoice.status === "Overdue") {
          acc.overdue++;
        }
        return acc;
      },
      { total: 0, paid: 0, unpaid: 0, overdue: 0 }
    );
  }, [invoices]);

  const filteredInvoices = useMemo<Invoice[]>(() => {
    if (!invoices) return [];

    return invoices.filter(invoice => {
      // Search filter - match invoice number or description
      if (searchTerm.trim()) {
        const term = searchTerm.toLowerCase();
        const matchesNumber = invoice.number.toLowerCase().includes(term);
        const matchesDescription = invoice.description?.toLowerCase().includes(term);
        if (!matchesNumber && !matchesDescription) {
          return false;
        }
      }

      // Status filter
      return statusFilter === "all" || invoice.status === statusFilter;
    });
  }, [invoices, searchTerm, statusFilter]);

  return {
    searchTerm,
    setSearchTerm,
    statusFilter,
    setStatusFilter,
    filteredInvoices,
    stats,
    hasActiveFilters,
    clearFilters,
  };
}
