'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { motion } from 'framer-motion';
import {
  ArrowLeft,
  ShoppingCart,
  Minus,
  Plus,
  Package,
  Truck,
  Shield,
  Sparkles,
  ShieldCheck,
  Award,
} from 'lucide-react';

import { useProduct } from '@/hooks';
import { useIsAdmin, useUser } from '@/store/auth.store';
import { cn, formatIDR } from '@/lib/utils';
import type { ProductVariant } from '@/lib/services/product.service';

import Image from 'next/image';
import { Button } from '@/components/ui/button';
// ── Add to cart block ──────────────────────────────────────────────────
function AddToCart({
  variants,
}: {
  variants: ProductVariant[];
  productName: string;
}) {
  const isAdmin = useIsAdmin();
  const user = useUser();
  const [selected, setSelected] = useState<ProductVariant>(
    variants.find((v) => !v.is_out_of_stock) ?? variants[0]
  );
  const [qty, setQty] = useState(1);

  const handleAdd = () => {
    window.open('https://shopee.co.id/garamcapkapal', '_blank');
  };

  const handleBuyNow = () => {
    window.open('https://shopee.co.id/garamcapkapal', '_blank');
  };

  return (
    <div className="space-y-6">
      {/* Variant Selector */}
      {variants.length > 1 && (
        <div>
          <p className="text-[11px] font-bold text-gray-400 uppercase tracking-widest mb-3">
            Pilih Ukuran / Varian
          </p>
          <div className="flex flex-wrap gap-3">
            {variants.map((v) => (
              <button
                key={v.id}
                disabled={v.is_out_of_stock}
                onClick={() => {
                  setSelected(v);
                  setQty(1);
                }}
                className={cn(
                  'relative px-4 py-2 md:px-5 md:py-2.5 rounded-xl text-[10px] md:text-sm font-bold uppercase tracking-wider transition-all duration-200 border',
                  v.is_out_of_stock
                    ? 'border-gray-200 text-gray-400 cursor-not-allowed bg-gray-50 line-through'
                    : selected.id === v.id
                      ? 'border-[#FFD738] bg-yellow-50 text-yellow-700 shadow-sm'
                      : 'border-white/50 text-gray-600 bg-white/50 hover:border-[#FFD738]/50 hover:text-gray-900 hover:bg-white shadow-sm'
                )}
              >
                {v.name}
                {v.is_out_of_stock && (
                  <span className="absolute -top-2 -right-2 text-[9px] font-black bg-rose-500 text-white px-2 py-0.5 rounded-full uppercase shadow-md shadow-rose-500/20">
                    Habis
                  </span>
                )}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Price & Stock info */}
      <div className="flex items-center justify-between border-y border-gray-200/50 py-3 md:py-5">
        <div>
          <p className="text-2xl md:text-4xl font-black text-yellow-600 tracking-tight">
            {formatIDR(
              user?.user_type === 'agen' && selected.price_distributor
                ? Number(selected.price_distributor)
                : Number(selected.price)
            )}
          </p>
          {selected.weight && (
            <p className="text-[10px] md:text-xs text-gray-500 mt-1 md:mt-1.5 font-medium tracking-wide">
              Berat:{' '}
              <span className="text-gray-900 font-bold">
                {Number(selected.weight).toFixed(0)} {selected.attributes?.unit}
              </span>{' '}
              · Kemasan:{' '}
              <span className="text-gray-900 font-bold">
                {selected.attributes?.packaging ?? 'Standar'}
              </span>
            </p>
          )}
        </div>
        <div>
          {selected.is_out_of_stock ? (
            <span className="text-[8px] md:text-[10px] font-bold text-rose-400 border border-rose-500/20 bg-rose-500/10 px-2 py-1 md:px-3 md:py-1.5 rounded-lg uppercase tracking-widest">
              Stok Habis
            </span>
          ) : selected.is_low_stock ? (
            <span className="text-[8px] md:text-[10px] font-bold text-[#FFD738] border border-[#FFD738]/20 bg-[#FFD738]/10 px-2 py-1 md:px-3 md:py-1.5 rounded-lg uppercase tracking-widest">
              Sisa {selected.stock}
            </span>
          ) : (
            <span className="text-[8px] md:text-[10px] font-bold text-emerald-400 border border-emerald-500/20 bg-emerald-500/10 px-2 py-1 md:px-3 md:py-1.5 rounded-lg uppercase tracking-widest">
              Stok {selected.stock}
            </span>
          )}
        </div>
      </div>

      {!isAdmin && (
        <div>
          {/* Quantity & Subtotal */}
          {!selected.is_out_of_stock && (
            <div className="flex flex-col sm:flex-row sm:items-center gap-4 sm:gap-6">
              <div className="flex items-center bg-white/60 backdrop-blur-md border border-white/50 rounded-xl overflow-hidden p-1 shadow-sm">
                <button
                  onClick={() => setQty((q) => Math.max(1, q - 1))}
                  className="p-1.5 md:p-2.5 rounded-lg hover:bg-white text-gray-500 hover:text-gray-900 transition-colors"
                >
                  <Minus className="w-3 h-3 md:w-4 md:h-4" />
                </button>
                <span className="w-8 md:w-12 text-center font-bold text-gray-900 text-sm md:text-base">
                  {qty}
                </span>
                <button
                  onClick={() => setQty((q) => Math.min(q + 1, selected.stock))}
                  disabled={qty >= selected.stock}
                  className="p-1.5 md:p-2.5 rounded-lg hover:bg-white text-gray-500 hover:text-gray-900 disabled:opacity-30 transition-colors"
                >
                  <Plus className="w-3 h-3 md:w-4 md:h-4" />
                </button>
              </div>
              <div className="flex-1">
                <p className="text-[9px] md:text-[11px] font-bold text-gray-500 uppercase tracking-widest mb-0.5">
                  Subtotal
                </p>
                <p className="text-base md:text-lg font-black text-gray-900">
                  {formatIDR(
                    (user?.user_type === 'agen' && selected.price_distributor
                      ? Number(selected.price_distributor)
                      : Number(selected.price)) * qty
                  )}
                </p>
              </div>
            </div>
          )}

          {/* Actions / CTA */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2">
            {!selected.is_out_of_stock && (
              <Button
                variant="outline"
                onClick={handleBuyNow}
                className="w-full border-2 border-yellow-500 text-yellow-600 font-bold uppercase tracking-wider hover:bg-yellow-50 hover:text-yellow-700 hover:border-yellow-600 h-auto py-2.5 md:py-3.5 rounded-xl text-xs md:text-sm"
              >
                Beli di Shopee
              </Button>
            )}

            <button
              onClick={handleAdd}
              disabled={selected.is_out_of_stock}
              className={cn(
                'w-full py-2.5 md:py-3.5 rounded-xl text-xs md:text-sm font-bold uppercase tracking-wider flex items-center justify-center gap-2 md:gap-2.5 transition-all duration-300 active:scale-[0.98]',
                selected.is_out_of_stock
                  ? 'bg-gray-100 text-gray-400 cursor-not-allowed border border-gray-200'
                  : 'bg-[#FFD738] hover:bg-yellow-400 text-[#1C1D1F] shadow-md shadow-[#FFD738]/20'
              )}
              style={{
                gridColumn: selected.is_out_of_stock ? '1 / -1' : 'auto',
              }}
            >
              <span className="flex items-center gap-2">
                <ShoppingCart className="w-5 h-5" />
                {selected.is_out_of_stock ? 'Stok Habis' : 'Ke Shopee'}
              </span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ── Page ───────────────────────────────────────────────────────────────
export default function ProductDetailPage() {
  const params = useParams();
  const slug = params.slug as string;
  const [descExpanded, setDescExpanded] = useState(false);

  const { data: product, isLoading } = useProduct(slug);

  // ── Loading State ───────────────────────────────────────────────────
  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 pt-20 md:pt-24 pb-8 md:pb-12">
        <div className="max-w-6xl mx-auto px-4 sm:px-6">
          <div className="bg-white/50 backdrop-blur-xl border border-white/50 shadow-sm rounded-3xl overflow-hidden animate-pulse">
            <div className="grid md:grid-cols-2">
              <div className="h-64 md:h-[600px] bg-white/40" />
              <div className="p-5 md:p-12 space-y-6">
                <div className="h-4 bg-white/40 rounded-full w-1/4" />
                <div className="h-12 bg-white/40 rounded-xl w-3/4" />
                <div className="h-4 bg-white/40 rounded-full w-1/2" />
                <div className="h-32 bg-white/40 rounded-xl mt-8" />
                <div className="h-14 bg-white/40 rounded-xl" />
                <div className="h-14 bg-white/40 rounded-xl" />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ── Not Found State ─────────────────────────────────────────────────
  if (!product) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center p-4">
        <div className="bg-white/60 backdrop-blur-xl border border-white/50 rounded-3xl p-6 md:p-12 text-center max-w-lg w-full shadow-lg">
          <div className="w-20 h-20 bg-white/50 border border-white/50 shadow-sm rounded-2xl flex items-center justify-center mx-auto mb-6">
            <Package className="w-10 h-10 text-gray-500" />
          </div>
          <h1 className="font-black text-gray-900 text-2xl tracking-tight mb-2">
            Produk Tidak Ditemukan
          </h1>
          <p className="text-sm text-gray-600 mb-8">
            Produk yang Anda cari mungkin telah dihapus atau tidak tersedia saat
            ini.
          </p>
          <Link
            href="/products"
            className="inline-flex items-center justify-center w-full gap-2 px-6 py-3.5 bg-[#FFD738] rounded-xl text-[#1C1D1F] font-bold text-sm uppercase tracking-wider hover:bg-[#FFD738]/90 transition-all shadow-lg shadow-[#FFD738]/20"
          >
            <ArrowLeft className="w-4 h-4" /> Lihat Produk Lainnya
          </Link>
        </div>
      </div>
    );
  }

  const desc = product.description ?? '';
  const shortDesc =
    desc.length > 300 && !descExpanded ? desc.slice(0, 300) + '...' : desc;

  return (
    <div className="min-h-screen bg-gray-50 text-gray-900 relative overflow-hidden pb-20 md:pb-52">
      {/* Global Background for Glassmorphism */}
      <div className="fixed inset-0 z-[-1]">
        <div className="absolute top-0 right-0 w-[800px] h-[800px] bg-yellow-300/30 rounded-full blur-[120px] -translate-y-1/3 translate-x-1/3 opacity-50" />
        <div className="absolute bottom-[-20%] left-[-10%] w-[600px] h-[600px] bg-blue-300/30 rounded-full blur-[120px] opacity-50" />
      </div>

      <div className="relative z-10 pt-20 md:pt-24 pb-12">
        <div className="max-w-6xl mx-auto px-4 sm:px-6 mt-4 sm:mt-10 flex flex-col items-start">
          <button
            onClick={() => window.history.back()}
            className="inline-flex items-center gap-2 px-4 py-2 md:px-5 md:py-2.5 rounded-full bg-white/60 backdrop-blur-md border border-white/50 text-xs md:text-sm font-bold text-gray-600 hover:bg-white hover:text-gray-900 transition-all mb-6 md:mb-8 group shadow-sm cursor-pointer"
          >
            <ArrowLeft className="w-3 h-3 md:w-4 md:h-4 group-hover:-translate-x-1 transition-transform" />
            Kembali
          </button>

          {/* ── Top Section: Main Card ── */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
            className="bg-white/60 backdrop-blur-xl border border-white/50 rounded-3xl overflow-hidden shadow-lg w-full"
          >
            <div className="grid grid-cols-1 lg:grid-cols-2">
              {/* Image Panel */}
              <div className="relative h-64 md:h-[500px] lg:h-auto bg-white/40 flex items-center justify-center p-4 md:p-12 border-r border-white/50">
                <div className="absolute top-3 left-3 md:top-6 md:left-6 z-10">
                  <span className="bg-[#FFD738]/10 border border-[#FFD738]/20 text-[#FFD738] px-2.5 py-1 md:px-4 md:py-1.5 rounded-full font-bold uppercase tracking-wider text-[8px] md:text-[10px] shadow-sm">
                    {product.category.name}
                  </span>
                </div>

                {product.is_featured && (
                  <div className="absolute top-3 right-3 md:top-6 md:right-6 z-10 flex items-center gap-1 md:gap-1.5 bg-white/80 backdrop-blur-md border border-white/50 text-gray-900 text-[8px] md:text-[10px] font-bold px-2.5 py-1 md:px-3 md:py-1.5 rounded-full uppercase tracking-wider shadow-sm">
                    <Sparkles className="w-2.5 h-2.5 md:w-3 md:h-3 text-yellow-500" />{' '}
                    Unggulan
                  </div>
                )}

                <motion.div
                  initial={{ scale: 0.9, opacity: 0 }}
                  animate={{ scale: 1, opacity: 1 }}
                  transition={{ duration: 0.6, delay: 0.1 }}
                  className="w-full h-full relative rounded-lg"
                >
                  {product.primary_image_url ? (
                    <Image
                      src={product.primary_image_url}
                      alt={product.name}
                      className="w-full h-full object-contain drop-shadow-[0_20px_50px_rgba(0,0,0,0.15)] rounded-lg"
                      width={500}
                      height={500}
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <Package className="w-32 h-32 text-gray-300" />
                    </div>
                  )}
                </motion.div>
              </div>

              {/* Info Panel */}
              <div className="p-5 md:p-10 lg:p-12 flex flex-col justify-center">
                {/* Title & SKU */}
                <h1 className="text-2xl md:text-4xl lg:text-5xl font-black text-gray-900 tracking-tight leading-tight mb-2 md:mb-3">
                  {product.name}
                </h1>
                <p className="text-[10px] md:text-xs font-mono text-gray-500 mb-4 md:mb-6 bg-white/60 border border-white/50 shadow-sm inline-flex px-2 py-0.5 md:px-3 md:py-1 rounded-md tracking-widest">
                  SKU: {product.sku}
                </p>

                {/* Short Desc */}
                {product.short_description && (
                  <div className="flex items-start gap-2 md:gap-3 mb-6 md:mb-8 bg-white/60 p-3 md:p-4 rounded-2xl border border-white/50 shadow-sm">
                    <ShieldCheck className="text-yellow-600 shrink-0 w-4 h-4 md:w-5 md:h-5" />
                    <p className="text-gray-700 text-xs md:text-sm leading-relaxed font-medium">
                      {product.short_description}
                    </p>
                  </div>
                )}

                {/* Sold Count */}
                {product.total_sold > 0 && (
                  <div className="inline-flex items-center gap-1.5 md:gap-2 mb-4 md:mb-6 text-[9px] md:text-[11px] font-bold text-yellow-700 bg-yellow-100 border border-yellow-200 px-2.5 py-1 md:px-3 md:py-1.5 rounded-full uppercase tracking-widest shadow-sm self-start">
                    <Award className="w-3 h-3 md:w-3.5 md:h-3.5" />
                    Telah terjual {product.total_sold.toLocaleString('id-ID')}+
                  </div>
                )}

                {/* Interactive Block */}
                <AddToCart
                  variants={product.variants}
                  productName={product.name}
                />
              </div>
            </div>
          </motion.div>

          {/* ── Details Grid ── */}
          <div className="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
            {/* Specs */}
            <div className="bg-white/60 backdrop-blur-lg p-5 md:p-8 border border-white/50 rounded-3xl shadow-lg relative overflow-hidden group">
              <div className="absolute -right-6 -bottom-6 opacity-10 group-hover:opacity-20 transition-opacity">
                <Image
                  src="/mascots/saltu-happy.avif"
                  alt="Mascot"
                  className="w-32 h-32"
                  width={500}
                  height={500}
                />
              </div>
              <h4 className="font-black text-sm md:text-base text-gray-900 tracking-wide mb-4 md:mb-6 flex items-center gap-2 relative z-10">
                <div className="w-1.5 h-5 md:h-6 bg-[#FFD738] rounded-full" />{' '}
                Spesifikasi
              </h4>
              <div className="space-y-3 md:space-y-4 relative z-10">
                {product.variants.map((v) => (
                  <div
                    key={v.id}
                    className="flex items-center justify-between py-1.5 md:py-2 border-b border-gray-200/50 last:border-0"
                  >
                    <span className="font-bold text-gray-500 text-[10px] md:text-xs tracking-wide">
                      {v.name}
                    </span>
                    <span className="font-black text-gray-900 text-xs md:text-sm">
                      {v.weight}g
                    </span>
                  </div>
                ))}
                <div className="flex items-center justify-between py-1.5 md:py-2 border-t border-gray-200/50 mt-2">
                  <span className="font-bold text-gray-500 text-[10px] md:text-xs tracking-wide">
                    Kemasan
                  </span>
                  <span className="font-black text-gray-900 text-xs md:text-sm text-right max-w-[150px]">
                    {product.variants[0]?.attributes?.packaging ??
                      'Plastik Food Grade'}
                  </span>
                </div>
              </div>
            </div>

            {/* Description / Storage */}
            <div className="bg-white/60 backdrop-blur-lg p-5 md:p-8 border border-white/50 rounded-3xl shadow-lg relative overflow-hidden group">
              <div className="absolute -right-6 -bottom-6 opacity-10 group-hover:opacity-20 transition-opacity">
                <Image
                  src="/mascots/salto-happy.avif"
                  alt="Mascot"
                  className="w-32 h-32"
                  width={500}
                  height={500}
                />
              </div>
              <h4 className="font-black text-sm md:text-base text-gray-900 tracking-wide mb-4 md:mb-6 flex items-center gap-2 relative z-10">
                <div className="w-1.5 h-5 md:h-6 bg-[#FFD738] rounded-full" />{' '}
                Penyimpanan
              </h4>
              {desc ? (
                <div className="relative z-10">
                  <p className="text-[11px] md:text-sm text-gray-600 leading-relaxed font-medium">
                    {shortDesc}
                  </p>
                  {desc.length > 300 && (
                    <button
                      onClick={() => setDescExpanded((v) => !v)}
                      className="mt-4 text-xs text-yellow-600 font-bold tracking-wide hover:underline flex items-center gap-1"
                    >
                      {descExpanded ? 'Tutup detail' : 'Baca selengkapnya'}
                    </button>
                  )}
                </div>
              ) : (
                <p className="text-[11px] md:text-sm text-gray-600 leading-relaxed font-medium relative z-10">
                  Simpan di tempat sejuk dan kering. Hindari sinar matahari
                  langsung. Pastikan kemasan tertutup rapat setelah dibuka untuk
                  menjaga kualitas produk tetap prima.
                </p>
              )}
            </div>

            {/* Certifications */}
            <div className="bg-white/60 backdrop-blur-lg p-5 md:p-8 border border-white/50 rounded-3xl shadow-lg relative overflow-hidden group">
              <div className="absolute -right-6 -bottom-6 opacity-10 group-hover:opacity-20 transition-opacity">
                <Image
                  src="/mascots/salta-happy.avif"
                  alt="Mascot"
                  className="w-32 h-32"
                  width={500}
                  height={500}
                />
              </div>
              <h4 className="font-black text-sm md:text-base text-gray-900 tracking-wide mb-4 md:mb-6 flex items-center gap-2 relative z-10">
                <div className="w-1.5 h-5 md:h-6 bg-[#FFD738] rounded-full" />{' '}
                Sertifikasi
              </h4>
              <div className="flex gap-1.5 md:gap-2 flex-wrap mb-6 md:mb-8 relative z-10">
                {['HALAL MUI', 'BPOM RI', 'ISO 9001'].map((cert) => (
                  <span
                    key={cert}
                    className="bg-white/60 text-gray-700 px-2 py-1 md:px-3 md:py-1.5 rounded-lg text-[8px] md:text-[10px] font-bold uppercase tracking-widest border border-white/50 shadow-sm"
                  >
                    {cert}
                  </span>
                ))}
              </div>
              <div className="space-y-3 md:space-y-4 relative z-10">
                {[
                  { icon: Truck, text: 'Pengiriman ke seluruh Indonesia' },
                  { icon: Shield, text: 'Produk terjamin & bersertifikat' },
                  { icon: Package, text: 'Kemasan standar keamanan tinggi' },
                ].map(({ icon: Icon, text }) => (
                  <div key={text} className="flex items-center gap-2 md:gap-3">
                    <div className="p-1.5 md:p-2 bg-yellow-100 rounded-lg shadow-sm">
                      <Icon className="w-3 h-3 md:w-4 md:h-4 text-yellow-600 shrink-0" />
                    </div>
                    <span className="text-[10px] md:text-xs font-bold text-gray-600 tracking-wide">
                      {text}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
