defmodule SimpleshopThemeWeb.ShopLive.Cart do
  use SimpleshopThemeWeb, :live_view

  alias SimpleshopTheme.Cart
  alias SimpleshopTheme.Settings
  alias SimpleshopTheme.Media
  alias SimpleshopTheme.Theme.{CSSCache, CSSGenerator}

  @impl true
  def mount(_params, _session, socket) do
    theme_settings = Settings.get_theme_settings()

    generated_css =
      case CSSCache.get() do
        {:ok, css} ->
          css

        :miss ->
          css = CSSGenerator.generate(theme_settings)
          CSSCache.put(css)
          css
      end

    logo_image = Media.get_logo()
    header_image = Media.get_header()

    socket =
      socket
      |> assign(:page_title, "Cart")
      |> assign(:theme_settings, theme_settings)
      |> assign(:generated_css, generated_css)
      |> assign(:logo_image, logo_image)
      |> assign(:header_image, header_image)
      |> assign(:mode, :shop)

    {:ok, socket}
  end

  @impl true
  def handle_event("increment", %{"id" => variant_id}, socket) do
    cart = Cart.add_item(socket.assigns.raw_cart, variant_id, 1)
    new_qty = Cart.get_quantity(cart, variant_id)

    socket =
      socket
      |> SimpleshopThemeWeb.CartHook.broadcast_and_update(cart)
      |> assign(:cart_status, "Quantity updated to #{new_qty}")

    {:noreply, socket}
  end

  @impl true
  def handle_event("decrement", %{"id" => variant_id}, socket) do
    current = Cart.get_quantity(socket.assigns.raw_cart, variant_id)
    cart = Cart.update_quantity(socket.assigns.raw_cart, variant_id, current - 1)
    new_qty = Cart.get_quantity(cart, variant_id)

    socket =
      socket
      |> SimpleshopThemeWeb.CartHook.broadcast_and_update(cart)
      |> assign(:cart_status, "Quantity updated to #{new_qty}")

    {:noreply, socket}
  end

  @impl true
  def render(assigns) do
    cart_page_subtotal = Cart.calculate_subtotal(assigns.cart_items)
    assigns = assign(assigns, :cart_page_subtotal, cart_page_subtotal)

    ~H"""
    <SimpleshopThemeWeb.PageTemplates.cart
      theme_settings={@theme_settings}
      logo_image={@logo_image}
      header_image={@header_image}
      cart_items={@cart_items}
      cart_page_subtotal={@cart_page_subtotal}
      mode={@mode}
      cart_count={@cart_count}
      cart_subtotal={@cart_subtotal}
      cart_drawer_open={@cart_drawer_open}
      cart_status={@cart_status}
    />
    """
  end
end
