defmodule BerrypodWeb.Shop.Pages.OrderDetail do
  @moduledoc """
  Order detail page handler for the unified Shop.Page LiveView.
  """

  import Phoenix.Component, only: [assign: 3]
  import Phoenix.LiveView, only: [push_navigate: 2]

  alias Berrypod.{Orders, Pages, Reviews}
  alias BerrypodWeb.R
  alias Berrypod.Products
  alias Berrypod.Products.ProductImage

  def init(socket, _params, _uri, session) do
    page = Pages.get_page("order_detail")

    socket =
      socket
      |> assign(:lookup_email, session["email_session"])
      |> assign(:page, page)

    {:noreply, socket}
  end

  def handle_params(%{"order_number" => order_number}, _uri, socket) do
    email = socket.assigns.lookup_email

    order = Orders.get_order_by_number(order_number)

    normalised = fn e -> String.downcase(String.trim(e || "")) end

    if order && order.payment_status == "paid" &&
         email && normalised.(order.customer_email) == normalised.(email) do
      variant_ids = Enum.map(order.items, & &1.variant_id)
      variants = Products.get_variants_with_products(variant_ids)

      thumbnails =
        Map.new(variants, fn {id, variant} ->
          thumb =
            case variant.product.images do
              [first | _] -> ProductImage.thumbnail_url(first)
              _ -> nil
            end

          slug = if variant.product.visible, do: variant.product.slug, else: nil

          # Check if user has reviewed this product
          existing_review = Reviews.get_review_by_email_and_product(email, variant.product_id)

          {id,
           %{
             thumb: thumb,
             slug: slug,
             product_id: variant.product_id,
             existing_review: existing_review
           }}
        end)

      socket =
        socket
        |> assign(:page_title, "Order #{order_number}")
        |> assign(:order, order)
        |> assign(:thumbnails, thumbnails)

      {:noreply, socket}
    else
      {:noreply, push_navigate(socket, to: R.orders())}
    end
  end

  def handle_event(_event, _params, _socket), do: :cont
end
