"use client";

import { useMemo, useState, useCallback } from "react";
import type { OrderSummary } from "@customer-portal/domain/orders";
import { getOrderServiceCategory } from "@customer-portal/domain/orders";

export type OrderStatusFilter = "all" | "pending" | "active" | "processing" | "cancelled";
export type OrderStatusCategory = Exclude<OrderStatusFilter, "all">;
export type OrderTypeFilter = "all" | "internet" | "sim" | "vpn";

export interface OrdersSummaryStats {
  total: number;
  pending: number;
  active: number;
  processing: number;
  cancelled: number;
}

export interface UseOrdersFilterOptions {
  orders: OrderSummary[] | undefined;
}

export interface UseOrdersFilterResult {
  // Filter state
  searchTerm: string;
  setSearchTerm: (value: string) => void;
  statusFilter: OrderStatusFilter;
  setStatusFilter: (value: OrderStatusFilter) => void;
  typeFilter: OrderTypeFilter;
  setTypeFilter: (value: OrderTypeFilter) => void;

  // Computed values
  filteredOrders: OrderSummary[];
  stats: OrdersSummaryStats;
  hasActiveFilters: boolean;

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

/**
 * Determines the status category for filtering purposes
 */
function getStatusCategory(
  status: string | undefined,
  activationStatus: string | undefined
): OrderStatusCategory {
  // Active: Activated orders
  if (activationStatus === "Activated") {
    return "active";
  }

  // Pending: Draft or Pending Review
  if (status === "Draft" || status === "Pending Review" || status === "Pending") {
    return "pending";
  }

  // Cancelled
  if (status === "Cancelled" || status === "Failed") {
    return "cancelled";
  }

  // Processing: Scheduled, Activating, or any other in-progress state
  // Note: status === "Activated" without activationStatus === "Activated" means
  // the order is approved but service activation isn't complete yet
  return "processing";
}

export function useOrdersFilter({ orders }: UseOrdersFilterOptions): UseOrdersFilterResult {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<OrderStatusFilter>("all");
  const [typeFilter, setTypeFilter] = useState<OrderTypeFilter>("all");

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

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

  const stats = useMemo<OrdersSummaryStats>(() => {
    if (!orders || orders.length === 0) {
      return { total: 0, pending: 0, active: 0, processing: 0, cancelled: 0 };
    }

    return orders.reduce(
      (acc, order) => {
        const category = getStatusCategory(order.status, order.activationStatus);
        acc.total++;
        acc[category]++;
        return acc;
      },
      { total: 0, pending: 0, active: 0, processing: 0, cancelled: 0 }
    );
  }, [orders]);

  const filteredOrders = useMemo<OrderSummary[]>(() => {
    if (!orders) return [];

    return orders.filter(order => {
      // Search filter - match order number
      if (searchTerm.trim()) {
        const orderNumber = order.orderNumber || String(order.id).slice(-8);
        if (!orderNumber.toLowerCase().includes(searchTerm.toLowerCase())) {
          return false;
        }
      }

      // Status filter
      if (statusFilter !== "all") {
        const orderStatusCategory = getStatusCategory(order.status, order.activationStatus);
        if (orderStatusCategory !== statusFilter) {
          return false;
        }
      }

      // Type filter
      if (typeFilter !== "all") {
        const serviceCategory = getOrderServiceCategory(order.orderType);
        if (serviceCategory !== typeFilter) {
          return false;
        }
      }

      return true;
    });
  }, [orders, searchTerm, statusFilter, typeFilter]);

  return {
    searchTerm,
    setSearchTerm,
    statusFilter,
    setStatusFilter,
    typeFilter,
    setTypeFilter,
    filteredOrders,
    stats,
    hasActiveFilters,
    clearFilters,
  };
}
