"use client";

import {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";

export interface CartItem {
  id: string;
  name: string;
  description: string | null;
  price: number;
  image: string | null;
  category: string;
  isAvailable: boolean;
  isFeatured: boolean;
}

export interface CartLine {
  item: CartItem;
  qty: number;
}

interface CartContextValue {
  lines: CartLine[];
  add: (item: CartItem) => void;
  remove: (id: string) => void;
  setQty: (id: string, qty: number) => void;
  clear: () => void;
  count: number;
  total: number;
}

const CartContext =
  createContext<CartContextValue | undefined>(
    undefined
  );

const CART_STORAGE_KEY = "happy-hours-cart";

/**
 * Vérifie qu'un article est valide.
 */
function isValidCartItem(
  item: unknown
): item is CartItem {
  if (
    !item ||
    typeof item !== "object"
  ) {
    return false;
  }

  const value =
    item as Record<string, unknown>;

  return (
    typeof value.id === "string" &&
    typeof value.name === "string" &&
    typeof value.price === "number" &&
    Number.isFinite(value.price) &&
    (typeof value.description === "string" ||
      value.description === null) &&
    (typeof value.image === "string" ||
      value.image === null) &&
    typeof value.category === "string" &&
    typeof value.isAvailable === "boolean" &&
    typeof value.isFeatured === "boolean"
  );
}

/**
 * Vérifie qu'une ligne du panier est valide.
 */
function isValidCartLine(
  line: unknown
): line is CartLine {
  if (
    !line ||
    typeof line !== "object"
  ) {
    return false;
  }

  const value =
    line as Record<string, unknown>;

  return (
    isValidCartItem(value.item) &&
    typeof value.qty === "number" &&
    Number.isInteger(value.qty) &&
    value.qty >= 1 &&
    value.qty <= 99
  );
}

export function CartProvider({
  children,
}: {
  children: ReactNode;
}) {
  const [lines, setLines] =
    useState<CartLine[]>([]);

  const [isHydrated, setIsHydrated] =
    useState(false);

  /**
   * Chargement du panier depuis localStorage.
   */
  useEffect(() => {
    try {
      const stored =
        localStorage.getItem(
          CART_STORAGE_KEY
        );

      if (stored) {
        const parsed: unknown =
          JSON.parse(stored);

        if (Array.isArray(parsed)) {
          const validLines =
            parsed.filter(
              isValidCartLine
            );

          setLines(validLines);
        }
      }
    } catch (error) {
      console.error(
        "Erreur lors du chargement du panier :",
        error
      );

      localStorage.removeItem(
        CART_STORAGE_KEY
      );
    } finally {
      setIsHydrated(true);
    }
  }, []);

  /**
   * Sauvegarde du panier dans localStorage.
   */
  useEffect(() => {
    if (!isHydrated) {
      return;
    }

    try {
      localStorage.setItem(
        CART_STORAGE_KEY,
        JSON.stringify(lines)
      );
    } catch (error) {
      console.error(
        "Erreur lors de la sauvegarde du panier :",
        error
      );
    }
  }, [lines, isHydrated]);

  /**
   * Ajoute un article au panier.
   */
  const add = (
    item: CartItem
  ) => {
    if (!item.isAvailable) {
      return;
    }

    setLines(
      (previousLines) => {
        const existingLine =
          previousLines.find(
            (line) =>
              line.item.id === item.id
          );

        if (existingLine) {
          return previousLines.map(
            (line) =>
              line.item.id === item.id
                ? {
                    ...line,
                    qty: Math.min(
                      line.qty + 1,
                      99
                    ),
                  }
                : line
          );
        }

        return [
          ...previousLines,
          {
            item,
            qty: 1,
          },
        ];
      }
    );
  };

  /**
   * Supprime complètement un article.
   */
  const remove = (
    id: string
  ) => {
    setLines(
      (previousLines) =>
        previousLines.filter(
          (line) =>
            line.item.id !== id
        )
    );
  };

  /**
   * Modifie la quantité d'un article.
   */
  const setQty = (
    id: string,
    qty: number
  ) => {
    const safeQty = Math.min(
      Math.max(
        Math.floor(qty),
        0
      ),
      99
    );

    setLines(
      (previousLines) => {
        if (safeQty <= 0) {
          return previousLines.filter(
            (line) =>
              line.item.id !== id
          );
        }

        return previousLines.map(
          (line) =>
            line.item.id === id
              ? {
                  ...line,
                  qty: safeQty,
                }
              : line
        );
      }
    );
  };

  /**
   * Vide complètement le panier.
   */
  const clear = () => {
    setLines([]);
  };

  /**
   * Nombre total d'articles.
   */
  const count = useMemo(
    () =>
      lines.reduce(
        (sum, line) =>
          sum + line.qty,
        0
      ),
    [lines]
  );

  /**
   * Montant total du panier.
   */
  const total = useMemo(
    () =>
      lines.reduce(
        (sum, line) =>
          sum +
          line.item.price *
            line.qty,
        0
      ),
    [lines]
  );

  return (
    <CartContext.Provider
      value={{
        lines,
        add,
        remove,
        setQty,
        clear,
        count,
        total,
      }}
    >
      {children}
    </CartContext.Provider>
  );
}

/**
 * Hook permettant d'utiliser le panier.
 */
export function useCart(): CartContextValue {
  const context =
    useContext(CartContext);

  if (!context) {
    throw new Error(
      "useCart doit être utilisé à l'intérieur de CartProvider."
    );
  }

  return context;
}

/**
 * Formate un prix en FCFA.
 */
export function formatPrice(
  amount: number
): string {
  return new Intl.NumberFormat(
    "fr-FR"
  ).format(
    Number.isFinite(amount)
      ? amount
      : 0
  );
}