defmodule SimpleshopThemeWeb.ShopComponents.Cart do
  @moduledoc false

  use Phoenix.Component

  import SimpleshopThemeWeb.ShopComponents.Base

  alias SimpleshopTheme.Products.{Product, ProductImage}

  defp close_cart_drawer_js do
    Phoenix.LiveView.JS.push("close_cart_drawer")
  end

  @doc """
  Renders the cart drawer (floating sidebar).

  The drawer slides in from the right when opened. It displays cart items
  and checkout options. Follows WAI-ARIA dialog pattern for accessibility.

  ## Attributes

  * `cart_items` - List of cart items to display. Each item should have
    `image`, `name`, `variant`, `price`, and `variant_id` keys. Default: []
  * `subtotal` - The subtotal to display. Default: nil (shows "£0.00")
  * `cart_count` - Number of items for screen reader description. Default: 0
  * `mode` - Either `:live` (default) for real stores or `:preview` for theme editor.
    In preview mode, "View basket" navigates via LiveView JS commands.

  ## Examples

      <.cart_drawer cart_items={@cart.items} subtotal={@cart.subtotal} />
      <.cart_drawer cart_items={demo_items} subtotal="£72.00" mode={:preview} />
  """

  attr :cart_items, :list, default: []
  attr :subtotal, :string, default: nil
  attr :cart_count, :integer, default: 0
  attr :cart_status, :string, default: nil
  attr :mode, :atom, default: :live
  attr :open, :boolean, default: false

  def cart_drawer(assigns) do
    assigns =
      assign_new(assigns, :display_subtotal, fn ->
        assigns.subtotal || "£0.00"
      end)

    ~H"""
    <%!-- Screen reader announcements for cart changes --%>
    <div aria-live="polite" aria-atomic="true" class="sr-only">
      {@cart_status}
    </div>

    <!-- Cart Drawer Overlay -->
    <div
      id="cart-drawer-overlay"
      class={["cart-drawer-overlay", @open && "open"]}
      aria-hidden={to_string(!@open)}
      style="position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 999; opacity: 0; visibility: hidden; transition: opacity 0.3s ease, visibility 0.3s ease;"
      phx-click={close_cart_drawer_js()}
    >
    </div>

    <!-- Cart Drawer -->
    <div
      id="cart-drawer"
      role="dialog"
      aria-modal="true"
      aria-labelledby="cart-drawer-title"
      aria-describedby="cart-drawer-description"
      aria-hidden={to_string(!@open)}
      phx-hook="CartDrawer"
      class={["cart-drawer", @open && "open"]}
      style="position: fixed; top: 0; right: -400px; width: 400px; max-width: 90vw; height: 100vh; height: 100dvh; background: var(--t-surface-raised); z-index: 1001; display: flex; flex-direction: column; transition: right 0.3s ease; box-shadow: -4px 0 20px rgba(0,0,0,0.15);"
    >
      <p id="cart-drawer-description" class="sr-only">
        Shopping basket with {@cart_count} {if @cart_count == 1, do: "item", else: "items"}. Press Escape to close.
      </p>
      <div
        class="cart-drawer-header"
        style="display: flex; justify-content: space-between; align-items: center; padding: 1rem 1.5rem; border-bottom: 1px solid var(--t-border-default);"
      >
        <h2
          id="cart-drawer-title"
          style="font-family: var(--t-font-heading); font-weight: var(--t-heading-weight); font-size: var(--t-text-large); color: var(--t-text-primary); margin: 0;"
        >
          Your basket
        </h2>
        <button
          type="button"
          class="cart-drawer-close"
          style="background: none; border: none; padding: 0.5rem; cursor: pointer; color: var(--t-text-secondary);"
          phx-click={close_cart_drawer_js()}
          aria-label="Close cart"
        >
          <svg
            class="w-5 h-5"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="2"
          >
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>

      <div class="cart-drawer-items" style="flex: 1; overflow-y: auto; padding: 1rem;">
        <%= if @cart_items == [] do %>
          <.cart_empty_state mode={@mode} />
        <% else %>
          <ul role="list" aria-label="Cart items" style="list-style: none; margin: 0; padding: 0;">
            <%= for item <- @cart_items do %>
              <li style="border-bottom: 1px solid var(--t-border-default);">
                <.cart_item_row item={item} size={:compact} show_quantity_controls mode={@mode} />
              </li>
            <% end %>
          </ul>
        <% end %>
      </div>

      <div
        class="cart-drawer-footer"
        style="padding: 1rem 1.5rem; border-top: 1px solid var(--t-border-default); background: var(--t-surface-sunken);"
      >
        <div style="display: flex; justify-content: space-between; font-family: var(--t-font-body); font-size: var(--t-text-small); color: var(--t-text-secondary); margin-bottom: 0.5rem;">
          <span>Delivery</span>
          <span>Calculated at checkout</span>
        </div>
        <div
          class="cart-drawer-total"
          style="display: flex; justify-content: space-between; font-family: var(--t-font-body); font-size: var(--t-text-base); font-weight: 600; color: var(--t-text-primary); margin-bottom: 1rem;"
        >
          <span>Subtotal</span>
          <span>{@display_subtotal}</span>
        </div>
        <%= if @mode == :preview do %>
          <button
            type="button"
            class="cart-drawer-checkout w-full mb-2"
            style="width: 100%; padding: 0.75rem 1.5rem; font-weight: 600; transition: all 0.2s ease; background: var(--t-accent-button, hsl(var(--t-accent-h) var(--t-accent-s) 42%)); color: var(--t-text-inverse); border-radius: var(--t-radius-button); border: none; cursor: pointer; font-family: var(--t-font-body);"
          >
            Checkout
          </button>
        <% else %>
          <form action="/checkout" method="post">
            <input type="hidden" name="_csrf_token" value={Phoenix.Controller.get_csrf_token()} />
            <button
              type="submit"
              class="cart-drawer-checkout w-full mb-2"
              style="width: 100%; padding: 0.75rem 1.5rem; font-weight: 600; transition: all 0.2s ease; background: var(--t-accent-button, hsl(var(--t-accent-h) var(--t-accent-s) 42%)); color: var(--t-text-inverse); border-radius: var(--t-radius-button); border: none; cursor: pointer; font-family: var(--t-font-body);"
            >
              Checkout
            </button>
          </form>
        <% end %>
      </div>
    </div>
    """
  end

  @doc """
  Shared cart item row component used by both drawer and cart page.

  ## Attributes

  * `item` - Required. Cart item with `name`, `variant`, `price`, `quantity`, `image`, `variant_id`, `product_id`.
  * `size` - Either `:compact` (drawer) or `:default` (cart page). Default: :default
  * `show_quantity_controls` - Show +/- buttons. Default: false
  * `mode` - Either `:live` or `:preview`. Default: :live
  """
  attr :item, :map, required: true
  attr :size, :atom, default: :default
  attr :show_quantity_controls, :boolean, default: false
  attr :mode, :atom, default: :live

  def cart_item_row(assigns) do
    ~H"""
    <div
      class="cart-item-row"
      style={"display: flex; gap: #{if @size == :compact, do: "0.75rem", else: "1rem"}; padding: 0.75rem 0;"}
    >
      <%= if @mode != :preview do %>
        <.link
          navigate={"/products/#{@item.product_id}"}
          class="cart-item-image"
          style={"display: block; width: #{if @size == :compact, do: "60px", else: "80px"}; height: #{if @size == :compact, do: "60px", else: "80px"}; border-radius: var(--t-radius-card); background-size: cover; background-position: center; flex-shrink: 0; #{if @item.image, do: "background-image: url('#{@item.image}');", else: "background-color: var(--t-surface-sunken);"}"}
          aria-label={"View #{@item.name}"}
        >
        </.link>
      <% else %>
        <div
          class="cart-item-image"
          style={"width: #{if @size == :compact, do: "60px", else: "80px"}; height: #{if @size == :compact, do: "60px", else: "80px"}; border-radius: var(--t-radius-card); background-size: cover; background-position: center; flex-shrink: 0; #{if @item.image, do: "background-image: url('#{@item.image}');", else: "background-color: var(--t-surface-sunken);"}"}
        >
        </div>
      <% end %>
      <div class="cart-item-details" style="flex: 1; min-width: 0;">
        <h3 style={"font-family: var(--t-font-body); font-size: #{if @size == :compact, do: "var(--t-text-small)", else: "var(--t-text-base)"}; font-weight: 500; margin: 0 0 2px;"}>
          <%= if @mode != :preview do %>
            <.link
              navigate={"/products/#{@item.product_id}"}
              style="color: var(--t-text-primary); text-decoration: none;"
              onmouseover="this.style.textDecoration='underline'"
              onmouseout="this.style.textDecoration='none'"
            >
              {@item.name}
            </.link>
          <% else %>
            <span style="color: var(--t-text-primary);">{@item.name}</span>
          <% end %>
        </h3>
        <%= if @item.variant do %>
          <p style="font-family: var(--t-font-body); font-size: var(--t-text-caption); color: var(--t-text-tertiary); margin: 0;">
            {@item.variant}
          </p>
        <% end %>

        <div style="display: flex; justify-content: space-between; align-items: center; margin-top: 4px; flex-wrap: wrap; gap: 0.5rem;">
          <%= if @show_quantity_controls do %>
            <div
              class="flex items-center"
              style="border: 1px solid var(--t-border-default); border-radius: var(--t-radius-input);"
            >
              <button
                type="button"
                phx-click="decrement"
                phx-value-id={@item.variant_id}
                class="px-3 py-1"
                style="background: none; border: none; cursor: pointer; color: var(--t-text-primary);"
                aria-label={"Decrease quantity of #{@item.name}"}
              >
                −
              </button>
              <span
                class="px-3 py-1 border-x"
                style="border-color: var(--t-border-default); color: var(--t-text-primary); min-width: 2rem; text-align: center;"
              >
                {@item.quantity}
              </span>
              <button
                type="button"
                phx-click="increment"
                phx-value-id={@item.variant_id}
                class="px-3 py-1"
                style="background: none; border: none; cursor: pointer; color: var(--t-text-primary);"
                aria-label={"Increase quantity of #{@item.name}"}
              >
                +
              </button>
            </div>
          <% else %>
            <span style="font-size: var(--t-text-caption); color: var(--t-text-tertiary);">
              Qty: {@item.quantity}
            </span>
          <% end %>

          <.cart_remove_button variant_id={@item.variant_id} item_name={@item.name} />
        </div>
      </div>

      <div class="text-right" style="flex-shrink: 0;">
        <p style={"font-weight: 500; font-size: #{if @size == :compact, do: "var(--t-text-small)", else: "var(--t-text-base)"}; color: var(--t-text-primary); margin: 0;"}>
          {SimpleshopTheme.Cart.format_price(@item.price * @item.quantity)}
        </p>
      </div>
    </div>
    """
  end

  @doc """
  Cart empty state component.
  """
  attr :mode, :atom, default: :live

  def cart_empty_state(assigns) do
    ~H"""
    <div class="text-center py-8" style="color: var(--t-text-secondary);">
      <svg
        class="w-16 h-16 mx-auto mb-4"
        width="64"
        height="64"
        style="color: var(--t-text-tertiary);"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
      >
        <path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4z"></path>
        <line x1="3" y1="6" x2="21" y2="6"></line>
        <path d="M16 10a4 4 0 01-8 0"></path>
      </svg>
      <p class="mb-4">Your basket is empty</p>
      <%= if @mode == :preview do %>
        <button
          type="button"
          phx-click="change_preview_page"
          phx-value-page="collection"
          style="color: var(--t-text-accent); text-decoration: underline; background: none; border: none; cursor: pointer;"
        >
          Continue shopping
        </button>
      <% else %>
        <.link
          navigate="/collections/all"
          style="color: var(--t-text-accent); text-decoration: underline;"
        >
          Continue shopping
        </.link>
      <% end %>
    </div>
    """
  end

  @doc """
  Remove button for cart items.
  """
  attr :variant_id, :string, required: true
  attr :item_name, :string, default: "item"

  def cart_remove_button(assigns) do
    ~H"""
    <button
      type="button"
      phx-click="remove_item"
      phx-value-id={@variant_id}
      style="background: none; border: none; padding: 0; cursor: pointer; font-family: var(--t-font-body); font-size: var(--t-text-caption); color: var(--t-text-tertiary); text-decoration: underline;"
      aria-label={"Remove #{@item_name} from cart"}
    >
      Remove
    </button>
    """
  end

  @doc """
  Renders a cart item row.

  ## Attributes

  * `item` - Required. Map with `product` (containing `image_url`, `name`, `price`), `variant`, and `quantity`.
  * `currency` - Optional. Currency symbol. Defaults to "£".

  ## Examples

      <.cart_item item={item} />
  """
  attr :item, :map, required: true

  def cart_item(assigns) do
    ~H"""
    <.shop_card class="flex gap-4 p-4">
      <div
        class="w-24 h-24 flex-shrink-0 bg-gray-200 overflow-hidden"
        style="border-radius: var(--t-radius-image);"
      >
        <img
          src={cart_item_image(@item.product)}
          alt={@item.product.title}
          width="96"
          height="96"
          loading="lazy"
          class="w-full h-full object-cover"
        />
      </div>

      <div class="flex-1">
        <h3
          class="font-semibold mb-1"
          style="font-family: var(--t-font-heading); color: var(--t-text-primary);"
        >
          {@item.product.title}
        </h3>
        <p class="text-sm mb-2" style="color: var(--t-text-secondary);">
          {@item.variant}
        </p>

        <div class="flex items-center gap-4">
          <div
            class="flex items-center"
            style="border: 1px solid var(--t-border-default); border-radius: var(--t-radius-input);"
          >
            <button class="px-3 py-1" style="color: var(--t-text-primary);">−</button>
            <span
              class="px-3 py-1 border-x"
              style="border-color: var(--t-border-default); color: var(--t-text-primary);"
            >
              {@item.quantity}
            </span>
            <button class="px-3 py-1" style="color: var(--t-text-primary);">+</button>
          </div>

          <button class="text-sm" style="color: var(--t-text-tertiary);">
            Remove
          </button>
        </div>
      </div>

      <div class="text-right">
        <p class="font-bold text-lg" style="color: var(--t-text-primary);">
          {SimpleshopTheme.Cart.format_price(@item.product.cheapest_price * @item.quantity)}
        </p>
      </div>
    </.shop_card>
    """
  end

  defp cart_item_image(product) do
    ProductImage.direct_url(Product.primary_image(product), 400)
  end

  @doc """
  Renders the order summary card.

  ## Attributes

  * `subtotal` - Required. Subtotal amount (in pence/cents).
  * `delivery` - Optional. Delivery cost. Defaults to 800 (£8.00).
  * `vat` - Optional. VAT amount. Defaults to 720 (£7.20).
  * `currency` - Optional. Currency symbol. Defaults to "£".
  * `mode` - Either `:live` (default) or `:preview`.

  ## Examples

      <.order_summary subtotal={3600} />
  """
  attr :subtotal, :integer, required: true
  attr :mode, :atom, default: :live

  def order_summary(assigns) do
    ~H"""
    <.shop_card class="p-6 sticky top-4">
      <h2
        class="text-xl font-bold mb-6"
        style="font-family: var(--t-font-heading); color: var(--t-text-primary);"
      >
        Order summary
      </h2>

      <div class="flex flex-col gap-3 mb-6">
        <div class="flex justify-between">
          <span style="color: var(--t-text-secondary);">Subtotal</span>
          <span style="color: var(--t-text-primary);">
            {SimpleshopTheme.Cart.format_price(@subtotal)}
          </span>
        </div>
        <div class="flex justify-between">
          <span style="color: var(--t-text-secondary);">Delivery</span>
          <span class="text-sm" style="color: var(--t-text-secondary);">
            Calculated at checkout
          </span>
        </div>
        <div class="border-t pt-3" style="border-color: var(--t-border-default);">
          <div class="flex justify-between text-lg">
            <span class="font-semibold" style="color: var(--t-text-primary);">Subtotal</span>
            <span class="font-bold" style="color: var(--t-text-primary);">
              {SimpleshopTheme.Cart.format_price(@subtotal)}
            </span>
          </div>
        </div>
      </div>

      <%= if @mode == :preview do %>
        <.shop_button class="w-full px-6 py-3 font-semibold transition-all mb-3">
          Checkout
        </.shop_button>
        <.shop_button_outline
          phx-click="change_preview_page"
          phx-value-page="collection"
          class="w-full px-6 py-3 font-semibold transition-all"
        >
          Continue shopping
        </.shop_button_outline>
      <% else %>
        <form action="/checkout" method="post" class="mb-3">
          <input type="hidden" name="_csrf_token" value={Phoenix.Controller.get_csrf_token()} />
          <.shop_button type="submit" class="w-full px-6 py-3 font-semibold transition-all">
            Checkout
          </.shop_button>
        </form>
        <.shop_link_outline
          href="/collections/all"
          class="block w-full px-6 py-3 font-semibold transition-all text-center"
        >
          Continue shopping
        </.shop_link_outline>
      <% end %>
    </.shop_card>
    """
  end

  @doc """
  Renders a cart items list with order summary layout.

  ## Attributes

  * `items` - Required. List of cart items.
  * `subtotal` - Required. Subtotal in pence/cents.
  * `currency` - Optional. Currency symbol. Defaults to "£".
  * `mode` - Either `:live` (default) or `:preview`.

  ## Examples

      <.cart_layout items={@cart_items} subtotal={3600} mode={:preview} />
  """
  attr :items, :list, required: true
  attr :subtotal, :integer, required: true
  attr :mode, :atom, default: :live

  def cart_layout(assigns) do
    ~H"""
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
      <div class="lg:col-span-2">
        <div class="flex flex-col gap-4">
          <%= for item <- @items do %>
            <.cart_item item={item} />
          <% end %>
        </div>
      </div>

      <div>
        <.order_summary subtotal={@subtotal} mode={@mode} />
      </div>
    </div>
    """
  end
end
