// app/components/user-dashboard/bag-item.tsx
"use client";
import React, { useState, useEffect } from "react";
import Image from "next/image";
import {AWS_CDN_URL, CDN_URL } from "@/utils/staticValues";
import Cookies from "js-cookie";
import { toast } from "react-toastify";
interface BagItem {
  product_image: string;
  product_name: string;
  price: number | string;
  size: string;
  quantity: number;
  product_id: number;
  cart_id: number;
  cart_type: string; // e.g., "STORE" o"
  total_price: string; // Total price for the item in the bag
  external_id: string; // External ID for co-creation items
  order_summary: {
    category: { name: string }[];
    fabric: string;
    art_data: string;
    vibe: string;
    silhouette: {
      piece_name: string;
      silhouette: { silhouette_name: string };
    }[];
    technique_family: string;
    prominence: string;
    color: string;
  };
}

interface ProductInBagProps {
  bagItem: BagItem;
  onQuantityChange?: (newQty: number) => void;
  onRemove?: () => void;
}

export default function ProductinBag({
  bagItem,
  onQuantityChange,
  onRemove,
}: ProductInBagProps) {
  const [count, setCount] = useState<number>(() => Number(bagItem.quantity));

  // Sync if parent ever changes bagItem.quantity
  useEffect(() => {
    setCount(Number(bagItem.quantity));
  }, [bagItem.quantity]);

  // Central updater: local state, parent callback, and API call
  const updateCount = (raw: number) => {
    const newQty = Math.max(1, Math.min(raw, 99));
    console.log("Updating quantity:", { raw, newQty, cartId: bagItem.cart_id });
    setCount(newQty);
    onQuantityChange?.(newQty);
  };

  const inc = () => updateCount(count + 1);
  const dec = () => updateCount(count - 1);
  const onInput = (e: React.ChangeEvent<HTMLInputElement>) =>
    updateCount(parseInt(e.target.value, 10) || 1);

  // Price math
  const unitPrice =
    typeof bagItem.price === "string"
      ? parseFloat(bagItem.price)
      : bagItem.price;

  const totalPrice =
    bagItem.cart_type === "STORE"
      ? (unitPrice * count).toFixed(2)
      : bagItem.total_price;

      console.log("Bag Item:", bagItem);
  // --- Add to Wishlist API call ---
  const handleAddToWishlist = () => {
    const confirmed = window.confirm("Do you want to add this item to your wishlist?");
  if (!confirmed) return;
    fetch(`/api/wishlist/add`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: "include", // Include cookies for authentication
      body: JSON.stringify({ product_id: bagItem.product_id }),
    })
      .then((res) => {
        if (!res.ok) throw new Error(res.statusText);
        return res.json();
      })
      .then(() => {
        console.log("Added to wishlist:", bagItem.product_id);
        // Optionally show a success toast
        toast.success("Item added to wishlist!", {
          toastId: "move_to_bag", // prevents duplicate toasts
        });
      })
      .catch((err) => {
        console.error("Wishlist add failed:", err);
        toast.error("system error", {
          toastId: "move_to_bag_error", // prevents duplicate toasts
        });
      });
  };

  return (
    <div className="grid grid-cols-1 bg-gray-50 p-5 py-8 md:p-12">
      <div className="grid grid-cols-5 gap-4 md:gap-12">
        <div className="col-span-1">
          {bagItem.cart_type === "CO_CREATION" ? (
            <div className="flex flex-col gap-2">
              {Array.isArray(bagItem.order_summary.category)
                ? bagItem.order_summary.category.slice(1).map((cat: any, idx: number) => (
                    <Image
                      key={idx}
                      src={`${AWS_CDN_URL}/${cat.image || cat.silhouette.silhouette_image}`}
                      width={120}
                      height={160}
                      alt={bagItem.product_name}
                      className="img-responsive"
                    />
                  ))
                : (
                  <Image
                    src={`${AWS_CDN_URL}/${bagItem.product_image}`}
                    width={120}
                    height={160}
                    alt={bagItem.product_name}
                    className="img-responsive"
                  />
                )}
            </div>
          ) : (
            <Image
              src={`${AWS_CDN_URL}/${bagItem.product_image}`}
              width={120}
              height={160}
              alt={bagItem.product_name}
              className="img-responsive"
            />
          )}
        </div>
        <div className="col-span-4 flex w-full flex-col gap-2">
          {/* Name + total */}
          <div className="flex justify-between">
            <p className="">{bagItem.product_name}</p>
            <p className="font-medium">${totalPrice}</p>
          </div>
          {/* Co-Creation Details */}
          {bagItem.cart_type === "CO_CREATION" && (
            <div className="mt-1 flex flex-col gap-1 border-1 border-dashed border-gray-950/25 bg-gray-100/50 p-4 md:p-8">
              <div className="grid grid-cols-1 gap-2 md:gap-4">
                <p className="text-xs text-gray-950">
                  <span className="font-medium">Vibe:</span>{" "}
                  {bagItem.order_summary.vibe}
                </p>
                {bagItem.order_summary.category.length > 0 && (
                  <p className="text-xs text-gray-950">
                    <span className="font-medium">Category:</span>{" "}
                    {bagItem.order_summary.category[0].name}
                  </p>
                )}
                <div className="text-xs text-gray-950">
                  <span className="font-medium">Silhouette:</span>
                  <div className="flex flex-col">
                    {bagItem.order_summary.silhouette.map(
                      (silhouette_data: any, index: number) => (
                        <span key={index} className="text-xs text-gray-950">
                          {silhouette_data.piece_name}-{" "}
                          {silhouette_data.silhouette.silhouette_name}
                        </span>
                      ),
                    )}
                  </div>
                </div>
                <p className="text-xs text-gray-950">
                  <span className="font-medium">Fabric:</span>{" "}
                  {bagItem.order_summary.fabric}
                </p>
                <p className="text-xs text-gray-950">
                  <span className="font-medium">Color:</span>{" "}
                  {bagItem.order_summary.color}
                </p>
                <p className="text-xs text-gray-950">
                  <span className="font-medium">ArtWork:</span>{" "}
                  {bagItem.order_summary.art_data}
                </p>
                <p className="text-xs text-gray-950">
                  <span className="font-medium">Craft Family:</span>{" "}
                  {bagItem.order_summary.technique_family}
                </p>
                <p className="text-xs text-gray-950">
                  <span className="font-medium">Prominence:</span>{" "}
                  {bagItem.order_summary.prominence}
                </p>
              </div>

              <div className="mt-4">
                <a
                  href={`/morni-guidance?group=base_canvas&step=define_vibe&external=${bagItem.external_id}&vbshow=true`}
                  className="btn-link"
                >
                  Edit this
                </a>
              </div>
            </div>
          )}

          {/* Size + qty controls */}
          <div className="flex items-center justify-between">
            {bagItem.cart_type == "STORE" && (
              <div className="mt-2">
                Size: <span className="font-medium">{bagItem.size}</span>
              </div>
            )}
            <div className="flex items-center space-x-2">
              <button
                type="button"
                onClick={dec}
                className="p-2 text-lg font-medium"
              >
                −
              </button>
              <input
                type="number"
                value={count}
                min={1}
                max={99}
                onChange={onInput}
                className="w-14 px-1 text-center outline-none"
                aria-label="Quantity"
              />
              <button
                type="button"
                onClick={inc}
                className="p-2 text-lg font-medium"
              >
                +
              </button>
            </div>
          </div>

          {/* Actions */}
          <div className="flex gap-8">
            <button
              className="btn-link flex items-center"
              onClick={handleAddToWishlist}
            >
              <i className="icon-[mdi--heart-outline] mr-1" />
              Wishlist
            </button>

            <button
              onClick={() => {
                const confirmed = window.confirm(
                  "Are you sure you want to remove this item from the bag?",
                );
                if (confirmed) {
                  onRemove?.();
                }
              }}
              className="btn-link"
            >
              Remove
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
