"use client";

import {
  useMemo,
  useState,
} from "react";

import Link from "next/link";

import {
  useCart,
} from "../../context/CartContext";


type Product = {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  price: number;
  is_available: boolean;
  featured_image_url: string | null;
};


type Variant = {
  id: string;
  name: string;
  price: number;
  is_available: boolean;
};


type Props = {
  product: Product;
  variants: Variant[];
};


export default function ProductDetailsClient({
  product,
  variants,
}: Props) {

  const {
    addItem,
  } = useCart();


  const [
    selectedVariantId,
    setSelectedVariantId,
  ] = useState<string | null>(
    variants.length > 0
      ? variants[0].id
      : null
  );


  const [
    quantity,
    setQuantity,
  ] = useState(1);


  const [
    addedMessage,
    setAddedMessage,
  ] = useState("");


  // =============================================
  // SELECTED VARIANT
  // =============================================

  const selectedVariant =
    useMemo(
      () =>
        variants.find(
          (variant) =>
            variant.id ===
            selectedVariantId
        ) ?? null,
      [
        variants,
        selectedVariantId,
      ]
    );


  // =============================================
  // UNIT PRICE
  // =============================================

  const unitPrice =
    selectedVariant
      ? selectedVariant.price
      : product.price;


  // =============================================
  // TOTAL
  // =============================================

  const total =
    unitPrice *
    quantity;


  // =============================================
  // QUANTITY
  // =============================================

  function decreaseQuantity() {
    setQuantity(
      (current) =>
        Math.max(
          1,
          current - 1
        )
    );
  }


  function increaseQuantity() {
    setQuantity(
      (current) =>
        current + 1
    );
  }


  // =============================================
  // ADD TO CART
  // =============================================

  function handleAddToCart() {

    if (
      variants.length > 0 &&
      !selectedVariant
    ) {
      return;
    }


    addItem({
      productId:
        product.id,

      productSlug:
        product.slug,

      productName:
        product.name,

      variantId:
        selectedVariant?.id ??
        null,

      variantName:
        selectedVariant?.name ??
        null,

      unitPrice,

      quantity,

      imageUrl:
        product.featured_image_url,
    });


    setAddedMessage(
      `${quantity} item${
        quantity > 1
          ? "s"
          : ""
      } added to cart.`
    );


    window.setTimeout(
      () => {
        setAddedMessage("");
      },
      3000
    );
  }


  return (
    <div className="grid gap-10 lg:grid-cols-2 lg:gap-16">

      {/* =========================================
          IMAGE
      ========================================= */}

      <div>

        <div className="overflow-hidden rounded-[36px] bg-[#ead7c2]">

          {product.featured_image_url ? (

            <img
              src={
                product.featured_image_url
              }
              alt={
                product.name
              }
              className="aspect-square w-full object-cover"
            />

          ) : (

            <div className="flex aspect-square items-center justify-center text-black/40">
              No product image
            </div>

          )}

        </div>

      </div>


      {/* =========================================
          INFORMATION
      ========================================= */}

      <div className="flex flex-col justify-center">

        <p className="text-sm font-bold uppercase tracking-[0.2em] text-[#9b6a44]">
          PELCY Product
        </p>


        <h1 className="mt-3 text-4xl font-black md:text-5xl">
          {product.name}
        </h1>


        <p className="mt-5 max-w-xl text-lg leading-8 text-black/60">
          {
            product.description ??
            "Fresh PELCY product."
          }
        </p>


        {/* =====================================
            VARIANTS
        ===================================== */}

        {variants.length > 0 && (

          <div className="mt-8">

            <h2 className="text-lg font-black">
              Choose Size
            </h2>


            <div className="mt-4 grid gap-3 sm:grid-cols-2">

              {variants.map(
                (variant) => {

                  const selected =
                    selectedVariantId ===
                    variant.id;


                  return (

                    <button
                      type="button"
                      key={
                        variant.id
                      }
                      onClick={() =>
                        setSelectedVariantId(
                          variant.id
                        )
                      }
                      className={`flex items-center justify-between rounded-2xl border p-4 text-left transition ${
                        selected
                          ? "border-[#2b2118] bg-[#2b2118] text-white"
                          : "border-black/10 bg-white hover:border-black/30"
                      }`}
                    >

                      <span className="font-bold">
                        {
                          variant.name
                        }
                      </span>

                      <span className="font-black">
                        ₦
                        {variant.price.toLocaleString()}
                      </span>

                    </button>

                  );
                }
              )}

            </div>

          </div>

        )}


        {/* =====================================
            PRICE
        ===================================== */}

        <div className="mt-8">

          <p className="text-sm text-black/40">
            Price
          </p>

          <p className="mt-1 text-3xl font-black">
            ₦
            {unitPrice.toLocaleString()}
          </p>

        </div>


        {/* =====================================
            QUANTITY
        ===================================== */}

        <div className="mt-8">

          <p className="text-sm font-bold">
            Quantity
          </p>


          <div className="mt-3 inline-flex items-center rounded-full border border-black/10 bg-white">

            <button
              type="button"
              onClick={
                decreaseQuantity
              }
              className="flex h-12 w-12 items-center justify-center text-2xl font-bold"
            >
              −
            </button>


            <div className="min-w-[55px] text-center text-lg font-black">
              {quantity}
            </div>


            <button
              type="button"
              onClick={
                increaseQuantity
              }
              className="flex h-12 w-12 items-center justify-center text-2xl font-bold"
            >
              +
            </button>

          </div>

        </div>


        {/* =====================================
            TOTAL
        ===================================== */}

        <div className="mt-8 rounded-[24px] bg-[#f1e9e0] p-5">

          <div className="flex items-center justify-between">

            <span className="font-bold">
              Total
            </span>

            <span className="text-2xl font-black">
              ₦
              {total.toLocaleString()}
            </span>

          </div>

        </div>


        {/* =====================================
            ADD TO CART
        ===================================== */}

        <button
          type="button"
          onClick={
            handleAddToCart
          }
          className="mt-5 w-full rounded-full bg-[#2b2118] px-8 py-5 text-lg font-black text-white transition hover:opacity-90"
        >
          Add to Cart
        </button>


        {addedMessage && (

          <div className="mt-4 rounded-2xl bg-green-100 p-4 text-center font-bold text-green-700">
            ✓ {addedMessage}
          </div>

        )}


        <Link
          href="/#products"
          className="mt-6 text-center text-sm font-bold text-black/40 hover:text-black"
        >
          ← Continue Shopping
        </Link>

      </div>

    </div>
  );
}