"use client";

import { useEffect, useState, useTransition } from "react";
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Loader2, Minus, Plus, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { updateCartItemAction, removeCartItemAction } from "@/app/actions/cart";
import { formatPrice } from "@/lib/money";
import { cn } from "@/lib/utils";

export function CartLineItem({
  item,
  locale,
  labels,
}: {
  item: {
    id: string;
    slug: string;
    name: string;
    variantName: string | null;
    image: string | null;
    imageAlt: string;
    unitPrice: number;
    lineTotal: number;
    quantity: number;
    stock: number;
    available: boolean;
  };
  locale: string;
  labels: { remove: string; unavailable: string; quantity: string };
}) {
  const [quantity, setQuantity] = useState(item.quantity);
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  useEffect(() => {
    setQuantity(item.quantity);
  }, [item.quantity]);

  const change = (next: number) => {
    const bounded = Math.min(Math.max(next, 0), Math.min(item.stock, 20));
    if (bounded === quantity) return;
    setQuantity(bounded);
    startTransition(async () => {
      const result = await updateCartItemAction({ itemId: item.id, quantity: bounded, locale });
      if (!result.ok) {
        toast.error(result.message ?? labels.unavailable);
        setQuantity(item.quantity);
      }
      router.refresh();
    });
  };

  const remove = () => {
    startTransition(async () => {
      const result = await removeCartItemAction({ itemId: item.id, locale });
      if (!result.ok) toast.error(labels.unavailable);
      else router.refresh();
    });
  };

  return (
    <article className="grid grid-cols-[92px_1fr] gap-4 border-b border-border py-6 sm:grid-cols-[120px_1fr_auto] sm:gap-6">
      <Link
        href={`/${locale}/product/${item.slug}`}
        className="relative aspect-[3/4] overflow-hidden bg-sand/20"
      >
        {item.image ? (
          <Image src={item.image} alt={item.imageAlt} fill sizes="120px" className="object-cover" />
        ) : null}
      </Link>

      <div className="flex flex-col justify-between">
        <div>
          <div className="flex items-start justify-between gap-3">
            <div>
              <Link
                href={`/${locale}/product/${item.slug}`}
                className="font-serif text-lg leading-snug text-charcoal hover:text-terracotta md:text-xl"
              >
                {item.name}
              </Link>
              {item.variantName && (
                <p className="mt-1 text-[12px] uppercase tracking-[0.1em] text-charcoal/40">
                  {item.variantName}
                </p>
              )}
              {!item.available && (
                <p className="mt-2 text-[12px] uppercase tracking-[0.1em] text-terracotta">
                  {labels.unavailable}
                </p>
              )}
            </div>
            <button
              type="button"
              onClick={remove}
              disabled={pending}
              aria-label={labels.remove}
              className="text-charcoal/30 transition-colors hover:text-terracotta disabled:opacity-40 sm:hidden"
            >
              <Trash2 className="h-4 w-4" strokeWidth={1.3} />
            </button>
          </div>
          <p className="mt-2 text-[14px] text-charcoal/45">{formatPrice(item.unitPrice, locale)}</p>
        </div>

        <div className="mt-4 flex items-center justify-between gap-4">
          <div className="flex h-9 items-center border border-charcoal/20">
            <button
              type="button"
              onClick={() => change(quantity - 1)}
              disabled={pending || quantity <= 0}
              aria-label="-"
              className="flex h-full w-8 items-center justify-center text-charcoal/50 hover:text-charcoal disabled:opacity-30"
            >
              <Minus className="h-3 w-3" />
            </button>
            <span className="flex w-7 items-center justify-center text-[13px]">
              {pending ? <Loader2 className="h-3 w-3 animate-spin" /> : quantity}
            </span>
            <button
              type="button"
              onClick={() => change(quantity + 1)}
              disabled={pending || quantity >= Math.min(item.stock, 20)}
              aria-label="+"
              className="flex h-full w-8 items-center justify-center text-charcoal/50 hover:text-charcoal disabled:opacity-30"
            >
              <Plus className="h-3 w-3" />
            </button>
          </div>

          <p className={cn("text-[14px] text-charcoal sm:hidden")}>
            {formatPrice(item.unitPrice * quantity, locale)}
          </p>
        </div>
      </div>

      <div className="hidden flex-col items-end justify-between sm:flex">
        <button
          type="button"
          onClick={remove}
          disabled={pending}
          aria-label={labels.remove}
          className="text-charcoal/30 transition-colors hover:text-terracotta disabled:opacity-40"
        >
          <Trash2 className="h-4 w-4" strokeWidth={1.3} />
        </button>
        <p className="text-[15px] text-charcoal">{formatPrice(item.lineTotal, locale)}</p>
      </div>
    </article>
  );
}
