"use client";

import {
  addItemToBackendCart,
  increaseCartItemCount,
  decreaseCartItemCount,
  removeItemFromCart,
  removeItemFromBackendCart,
  decreaseItemFromBackendCart,
} from "@/redux/slices/cartSlice";
import { RootState, AppDispatch } from "@/redux/store";
import React, { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import Image from "next/image";
import { Loader } from "lucide-react";
import PriceDisplay from "@/components/ui/formattedPrice";
import { useSession } from "next-auth/react";
import Link from "next/link";

export default function CartClientPage() {
  const cart = useSelector((state: RootState) => state.cart);
  const total = useSelector((state: RootState) => state.cart.totalPrice);
  const dispatch = useDispatch<AppDispatch>();
  const [isMounted, setIsMounted] = useState(false);
  const { data: session } = useSession();

  useEffect(() => {
    setIsMounted(true);
  }, []);

  const increaseCartItem = (variant: ProductVariant) => {
    dispatch(increaseCartItemCount(variant.uuid));
    if (session?.user?.uuid) {
      dispatch(addItemToBackendCart(parseInt(variant.id)));
    }
  };

  const decreaseCartItem = (variant: ProductVariant) => {
    dispatch(decreaseCartItemCount(variant.uuid));
    if (session?.user?.uuid) {
      dispatch(decreaseItemFromBackendCart(parseInt(variant.id)));
    }
  };

  const removeItem = (variant: ProductVariant) => {
    dispatch(removeItemFromCart(variant.uuid));
    if (session?.user.uuid) {
      dispatch(removeItemFromBackendCart(parseInt(variant.id)));
    }
  };

  const goToCheckoutPage = () => {
    window.location.href = "/checkout";
  };

  if (!isMounted) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <Loader className="animate-spin w-10 h-10 text-indigo-600" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-indigo-50 via-white to-purple-50 py-12 px-4">
      <div className="max-w-[1250px] mx-auto w-full">
        <h1 className="text-4xl font-extrabold mb-10 text-center text-gray-900 drop-shadow-md">
          Your Cart
        </h1>

        <div className="flex flex-col lg:flex-row gap-10">
          {/* Cart Items */}
          <div className="flex-1 space-y-6">
            {cart.items.length === 0 ? (
              <p className="text-gray-500 text-center text-lg">
                Your cart is empty.
              </p>
            ) : (
              cart.items.map((item) => (
                <div
                  key={item.variant.uuid}
                  className="flex items-center gap-5 bg-white/80 backdrop-blur-lg border border-gray-200 shadow-lg rounded-2xl p-5 hover:shadow-2xl transition duration-300"
                >
                  <Image
                    src={item.variant.variant_images[0].file_url}
                    height={200}
                    width={200}
                    alt={item.variant.name}
                    className="w-[110px] h-[110px] [@media(max-width:800px)]:w-[70px] [@media(max-width:800px)]:h-[70px] rounded-xl object-cover shadow-md"
                  />
                  <div className="flex-1">
                    <Link
                      href={`/products/${item.variant.uuid}`}
                      className="hover:underline"
                    >
                      <h3 className="text-lg font-semibold text-gray-900 [@media(max-width:800px)]:text-sm">
                        {item.variant.name}
                      </h3>
                    </Link>
                    {item.variant.quantity && item.variant.quantity > 0 ? (
                      <div className="flex items-center gap-3 mt-3">
                        <button
                          className="px-3 py-1 bg-gray-200 rounded-lg hover:bg-gray-300 transition duration-200"
                          onClick={() => decreaseCartItem(item.variant)}
                        >
                          -
                        </button>
                        <span className="text-lg font-medium">
                          {item.quantity}
                        </span>
                        <button
                          className="px-3 py-1 bg-gray-200 rounded-lg hover:bg-gray-300 transition duration-200"
                          onClick={() => increaseCartItem(item.variant)}
                        >
                          +
                        </button>
                      </div>
                    ) : (
                      <div className="text-red-500 py-2 font-medium">
                        Out of Stock
                      </div>
                    )}
                  </div>

                  <div className="text-right flex flex-col items-end justify-between h-full">
                    <p className="text-lg font-bold text-gray-900">
                      <PriceDisplay price={item.price * item.quantity} />
                    </p>
                    <button
                      onClick={() => removeItem(item.variant)}
                      className="text-xs px-3 py-1 rounded-full bg-red-100 text-red-600 hover:bg-red-200 mt-3 transition duration-200"
                    >
                      Remove
                    </button>
                  </div>
                </div>
              ))
            )}
          </div>

          {/* Order Summary */}
          {cart.totalQuantity > 0 && (
            <div className="w-full lg:w-1/3 bg-white/90 backdrop-blur-md border border-gray-200 rounded-2xl shadow-xl px-8 py-10 self-start transition hover:shadow-2xl duration-300">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">
                Order Summary
              </h2>
              <div className="flex justify-between text-gray-700 mb-3">
                <span>Subtotal</span>
                <span>
                  <PriceDisplay price={total} />
                </span>
              </div>
              <div className="flex justify-between text-gray-700 mb-3">
                <span>Shipping</span>
                <span className="font-medium text-green-600">Free</span>
              </div>
              <hr className="my-5" />
              <div className="flex justify-between text-2xl font-extrabold text-gray-900 mb-8">
                <span>Total</span>
                <span>
                  <PriceDisplay price={total} />
                </span>
              </div>
              {cart.stockout ? (
                <button
                  disabled
                  className="cursor-not-allowed w-full bg-gray-400 text-white font-semibold py-3 rounded-xl transition"
                >
                  Remove Out of Stock Items to Checkout
                </button>
              ) : (
                <button
                  onClick={goToCheckoutPage}
                  className="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-semibold py-3 rounded-xl shadow-lg hover:shadow-2xl transition-transform transform hover:scale-[1.02]"
                >
                  Proceed to Checkout
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
