'use client';

import { useState } from 'react';
import AppImage from '@/components/ui/AppImage';
import Link from 'next/link';
import { notFound, useParams } from 'next/navigation';
import {
  ShoppingCart,
  Heart,
  ChevronLeft,
  Minus,
  Plus,
  Check,
  ShieldCheck,
} from 'lucide-react';
import CustomizationSelector from '@/components/product/CustomizationSelector';
import Button from '@/components/ui/Button';
import { getProductBySlug } from '@/lib/products';
import { getDefaultCustomization, getCustomizationLabel } from '@/lib/customization';
import { localizeProduct } from '@/lib/product-i18n';
import { formatPrice, getFormatLocale } from '@/lib/utils';
import { useCart } from '@/presentation/hooks/useCart';
import { useWishlist } from '@/presentation/hooks/useWishlist';
import { useTranslation } from '@/hooks/useTranslation';
import { ProductCustomization } from '@/types';

export default function ProductPage() {
  const params = useParams();
  const slug = params.slug as string;
  const rawProduct = getProductBySlug(slug);
  const { t, locale } = useTranslation();

  const [customization, setCustomization] = useState<ProductCustomization>(
    rawProduct ? getDefaultCustomization(rawProduct.category) : { type: 'fish' }
  );
  const [quantity, setQuantity] = useState(1);
  const [selectedImage, setSelectedImage] = useState(0);
  const [added, setAdded] = useState(false);

  const { addItem } = useCart();
  const { isInWishlist, toggleItem } = useWishlist();

  if (!rawProduct) {
    notFound();
  }

  const product = localizeProduct(rawProduct, t);
  const inWishlist = isInWishlist(product.id);

  const handleAddToCart = () => {
    const label = getCustomizationLabel(customization, t);
    addItem(rawProduct, customization, label, quantity);
    setAdded(true);
    setTimeout(() => setAdded(false), 2000);
  };

  return (
    <div className="bg-white">
      <div className="mx-auto max-w-7xl px-4 py-8 sm:px-6 lg:px-8">
        <Link
          href="/shop"
          className="mb-6 inline-flex items-center gap-1 text-sm font-medium text-gray-500 transition-colors hover:text-brand-700"
        >
          <ChevronLeft className="h-4 w-4 rtl:rotate-180" />
          {t('product.backToShop')}
        </Link>

        <div className="grid gap-10 lg:grid-cols-2">
          <div>
            <div className="relative mb-4 aspect-square overflow-hidden rounded-2xl bg-white shadow-premium ring-1 ring-gray-100">
              <AppImage
                src={product.images[selectedImage] || product.image}
                alt={product.name}
                fill
                className="object-contain p-3 sm:p-5"
                priority
                sizes="(max-width: 1024px) 100vw, 640px"
              />
              {product.badge && (
                <span className="absolute start-4 top-4 z-20 rounded-full bg-gold-500 px-4 py-1.5 text-sm font-semibold text-white shadow-gold">
                  {product.badge}
                </span>
              )}
            </div>
            {product.images.length > 1 && (
              <div className="flex gap-3">
                {product.images.map((img, i) => (
                  <button
                    key={img}
                    onClick={() => setSelectedImage(i)}
                    className={`relative h-20 w-20 overflow-hidden rounded-lg border-2 transition-all ${
                      selectedImage === i
                        ? 'border-brand-700'
                        : 'border-transparent opacity-60 hover:opacity-100'
                    }`}
                  >
                    <AppImage src={img} alt="" fill className="object-cover" sizes="80px" />
                  </button>
                ))}
              </div>
            )}
          </div>

          <div>
            <div className="mb-2 flex items-center gap-2">
              <Link
                href={`/shop?category=${product.category}`}
                className="rounded-full bg-brand-50 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-brand-700 transition-colors hover:bg-brand-100"
              >
                {t(`categories.${product.category}.name`)}
              </Link>
              {product.inStock ? (
                <span className="flex items-center gap-1 text-xs font-medium text-brand-700">
                  <Check className="h-3 w-3" /> {t('product.inStock')}
                </span>
              ) : (
                <span className="text-xs font-medium text-red-500">
                  {t('product.outOfStock')}
                </span>
              )}
            </div>

            <h1 className="mb-2 font-display text-3xl font-bold text-brand-900 lg:text-4xl">
              {product.name}
            </h1>

            <p className="mb-4 text-gray-500">{product.description}</p>

            <div className="mb-6 flex items-baseline gap-2">
              <span className="text-3xl font-bold text-brand-800">
                {formatPrice(product.price, getFormatLocale(locale))}
              </span>
              <span className="text-sm text-gray-400">{product.priceUnit}</span>
              {product.weight && (
                <span className="text-sm text-gray-400">· {product.weight}</span>
              )}
            </div>

            <div className="mb-6 flex items-center gap-2 rounded-lg border border-brand-100 bg-brand-50/50 px-4 py-3">
              <ShieldCheck className="h-5 w-5 shrink-0 text-brand-700" />
              <span className="text-sm text-brand-800">{t('product.halalTrust')}</span>
            </div>

            <div className="mb-6 rounded-2xl border border-gray-100 bg-gray-50 p-6">
              <CustomizationSelector
                category={product.category}
                customization={customization}
                onChange={setCustomization}
              />
              <div className="mt-4 rounded-lg bg-white px-4 py-3">
                <p className="text-xs text-gray-500">{t('product.yourSelection')}</p>
                <p className="text-sm font-semibold text-brand-800">
                  {getCustomizationLabel(customization, t)}
                </p>
              </div>
            </div>

            <div className="mb-6 flex items-center gap-4">
              <div className="flex items-center rounded-lg border border-gray-200">
                <button
                  onClick={() => setQuantity(Math.max(1, quantity - 1))}
                  className="flex h-12 w-12 items-center justify-center text-gray-500 transition-colors hover:text-brand-700"
                  aria-label={t('product.decreaseQty')}
                >
                  <Minus className="h-4 w-4" />
                </button>
                <span className="w-12 text-center font-semibold">{quantity}</span>
                <button
                  onClick={() => setQuantity(quantity + 1)}
                  className="flex h-12 w-12 items-center justify-center text-gray-500 transition-colors hover:text-brand-700"
                  aria-label={t('product.increaseQty')}
                >
                  <Plus className="h-4 w-4" />
                </button>
              </div>

              <Button
                onClick={handleAddToCart}
                disabled={!product.inStock}
                className="flex-1"
                size="lg"
              >
                {added ? (
                  <>
                    <Check className="h-4 w-4" />
                    {t('product.addedToCart')}
                  </>
                ) : (
                  <>
                    <ShoppingCart className="h-4 w-4" />
                    {t('product.addToCart')}
                  </>
                )}
              </Button>

              <button
                onClick={() => toggleItem(rawProduct)}
                className={`flex h-12 w-12 items-center justify-center rounded-lg border-2 transition-all ${
                  inWishlist
                    ? 'border-red-200 bg-red-50 text-red-500'
                    : 'border-gray-200 text-gray-400 hover:border-brand-300 hover:text-brand-700'
                }`}
                aria-label={
                  inWishlist ? t('product.removeWishlist') : t('product.addWishlist')
                }
              >
                <Heart className={`h-5 w-5 ${inWishlist ? 'fill-current' : ''}`} />
              </button>
            </div>

            <div className="border-t border-gray-100 pt-6">
              <h2 className="mb-3 font-display text-lg font-semibold text-brand-900">
                {t('product.aboutProduct')}
              </h2>
              <p className="text-sm leading-relaxed text-gray-600">
                {product.longDescription}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}