/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import { useRef, useState, useCallback, useEffect } from 'react';
import Image from 'next/image';
import { ChevronRight, ChevronLeft } from 'lucide-react';
import { ProductCard } from './ProductCard';
import { SectionHeader } from './SectionHeader';
import { useProducts } from '@/hooks';
import { Product } from '@/lib/services';
import Link from 'next/link';

const PRODUCT_DATA: any[] = [
  {
    id: '019e53ed-4495-7396-b458-0f09885bbfb9',
    name: 'Garam Cap Kapal',
    slug: 'garam-beriodium-cap-kapal',
    sku: 'GRM-CK-01',
    short_description: 'Garam Cap Kapal merupakan garam bekualitas tinggi',
    base_price: '20000.00',
    min_price: 20000,
    max_price: 40000,
    status: 'active',
    is_featured: false,
    in_stock: true,
    rating_avg: '0.00',
    review_count: 0,
    total_sold: 0,
    primary_image_url: '/images/products/list-product.avif',
    category: {
      id: '019dc873-6f18-7212-a8a8-bee645640456',
      name: 'Garam Capkapal',
      slug: 'garam-capkapal',
      description: 'Garam Capkapal adalah garam untuk para Member',
      image_url: null,
      sort_order: 0,
    },
    variants: [
      {
        id: '019e53ed-449d-735c-8f0f-e18ee0368cb3',
        name: '250g',
        sku: 'GRM-CK-01-250G',
        price: 20000,
        stock: 100,
        weight: '250.00',
        attributes: {
          unit: 'gram',
          packaging: 'Plastik',
        },
        is_active: true,
        is_low_stock: false,
        is_out_of_stock: false,
      },
      {
        id: '019e53ed-44a0-70a6-8fcd-18150e32ca50',
        name: '500g',
        sku: 'GRM-CK-01-500G',
        price: 40000,
        stock: 100,
        weight: '500.00',
        attributes: {
          unit: 'gram',
          packaging: 'Plastik',
        },
        is_active: true,
        is_low_stock: false,
        is_out_of_stock: false,
      },
      {
        id: 'id_need_to_update',
        name: '1kg',
        sku: 'GRM-CK-01-1KG',
        price: 40000,
        stock: 100,
        weight: '1000',
        attributes: {
          unit: 'gram',
          packaging: 'Plastik',
        },
        is_active: true,
        is_low_stock: false,
        is_out_of_stock: false,
      },
    ],
    created_at: '2026-05-23T08:21:59.000000Z',
  },
];

export default function ProductSection() {
  const products = useProducts();
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  const displayProducts: Product[] = products.data?.data?.length
    ? products.data.data
    : PRODUCT_DATA;

  // Filter by category 'Garam Capkapal' and sort by weight
  const sortedProducts = displayProducts
    .filter((product) => {
      const catName = product.category?.name?.toLowerCase() ?? '';
      return catName === 'garam capkapal' || catName === 'garam cap kapal';
    })
    .sort((a, b) => {
      const weightA = parseFloat(a.variants?.[0]?.weight ?? '0');
      const weightB = parseFloat(b.variants?.[0]?.weight ?? '0');
      return weightA - weightB;
    });

  const updateScrollState = useCallback(() => {
    const el = scrollRef.current;
    if (!el) return;
    setCanScrollLeft(el.scrollLeft > 0);
    setCanScrollRight(el.scrollLeft + el.clientWidth < el.scrollWidth - 1);
  }, []);

  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    updateScrollState();
    el.addEventListener('scroll', updateScrollState, { passive: true });
    window.addEventListener('resize', updateScrollState);
    return () => {
      el.removeEventListener('scroll', updateScrollState);
      window.removeEventListener('resize', updateScrollState);
    };
  }, [updateScrollState, sortedProducts]);

  const scroll = useCallback((direction: 'left' | 'right') => {
    const el = scrollRef.current;
    if (!el) return;
    // Scroll by roughly one card width + gap
    const cardWidth =
      el.querySelector<HTMLElement>(':scope > *')?.offsetWidth ?? 300;
    const gap = 16;
    const scrollAmount = cardWidth + gap;
    el.scrollBy({
      left: direction === 'left' ? -scrollAmount : scrollAmount,
      behavior: 'smooth',
    });
  }, []);

  return (
    <section className="pt-15 md:py-20 pb-16 bg-[#FFFDF5] relative overflow-hidden">
      <div className="container mx-auto px-4 relative z-10 text-center">
        <SectionHeader title="PRODUK" accent="KAMI" />
        <p className="text-[#4A5565] text-sm sm:text-base md:text-2xl max-w-3xl mx-auto mb-8 tracking-[-0.31px]">
          Setiap kristal garam kami melalui{' '}
          <span className="font-bold">5 tahap pemurnian</span> untuk menjamin
          kualitas terbaik sampai ke dapur Anda.
        </p>

        <div className="relative mt-20 md:mt-52 max-w-[1440px] mx-auto">
          {/* Top Brand Logo */}
          <div className="absolute left-[-10px] sm:left-[-20px] md:left-[-40px] top-[140px] md:top-[-100px] z-30 w-[100px] h-[100px] sm:w-[140px] sm:h-[140px] md:w-[180px] md:h-[180px]">
            <Image
              src="/images/home/top-brand-products.avif"
              alt="Top Brand 2021"
              fill
              className="object-contain drop-shadow-xl hover:scale-105 transition-transform"
            />
          </div>

          {/* Mascots on top of container */}
          <div className="absolute left-1/2 -translate-x-1/2 -translate-y-3/4 md:-translate-y-5/6 z-20 w-[240px] sm:w-[280px] md:w-auto">
            {/* Decorative Stars and Circles */}
            <div className="absolute inset-0 z-0 pointer-events-none">
              {/* Top Left Area */}
              <div className="absolute -left-12 md:-left-20 top-4 md:top-8 w-2 h-2 md:w-3 md:h-3 rounded-full bg-[#FFD738]" />
              <div className="absolute -left-6 md:-left-10 -top-8 w-3 h-3 md:w-4 md:h-4 text-[#FFD738] rotate-25">
                <svg
                  viewBox="0 0 24 24"
                  fill="currentColor"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M12 0L14.59 9.41L24 12L14.59 14.59L12 24L9.41 14.59L0 12L9.41 9.41L12 0Z" />
                </svg>
              </div>

              {/* Middle Left Area */}
              <div className="absolute -left-4 md:-left-12 top-20 md:top-28 w-5 h-5 md:w-8 md:h-8 text-[#FFD738] rotate-15">
                <svg
                  viewBox="0 0 24 24"
                  fill="currentColor"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M12 0L14.59 9.41L24 12L14.59 14.59L12 24L9.41 14.59L0 12L9.41 9.41L12 0Z" />
                </svg>
              </div>
              <div className="absolute left-2 md:left-4 top-36 md:top-48 w-1.5 h-1.5 md:w-2.5 md:h-2.5 rounded-full bg-[#FFD738]" />

              {/* Top Center Area */}
              <div className="absolute left-1/3 -top-2 md:-top-4 w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-[#FFD738]" />
              <div className="absolute left-1/2 -translate-x-1/2 -top-4 md:-top-8 w-2 h-2 md:w-3 md:h-3 rounded-full bg-[#FFD738]" />
              <div className="absolute left-2/3 -top-6 w-3 h-3 md:w-5 md:h-5 text-[#FFD738] rotate-[-15deg]">
                <svg
                  viewBox="0 0 24 24"
                  fill="currentColor"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M12 0L14.59 9.41L24 12L14.59 14.59L12 24L9.41 14.59L0 12L9.41 9.41L12 0Z" />
                </svg>
              </div>

              {/* Top Right Area */}
              <div className="absolute right-12 md:right-24 top-0 md:-top-4 w-3 h-3 md:w-4 md:h-4 text-[#FFD738] rotate-[-10deg]">
                <svg
                  viewBox="0 0 24 24"
                  fill="currentColor"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M12 0L14.59 9.41L24 12L14.59 14.59L12 24L9.41 14.59L0 12L9.41 9.41L12 0Z" />
                </svg>
              </div>
              <div className="absolute -right-4 md:-right-8 -top-8 md:-top-16 w-8 h-8 md:w-12 md:h-12 text-[#FFD738] rotate-20">
                <svg
                  viewBox="0 0 24 24"
                  fill="currentColor"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M12 0L14.59 9.41L24 12L14.59 14.59L12 24L9.41 14.59L0 12L9.41 9.41L12 0Z" />
                </svg>
              </div>

              {/* Middle Right Area */}
              <div className="absolute right-2 md:right-8 top-24 md:top-32 w-4 h-4 md:w-6 md:h-6 text-[#FFD738] rotate-45 opacity-80">
                <svg
                  viewBox="0 0 24 24"
                  fill="currentColor"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path d="M12 0L14.59 9.41L24 12L14.59 14.59L12 24L9.41 14.59L0 12L9.41 9.41L12 0Z" />
                </svg>
              </div>
              <div className="absolute -right-8 md:-right-16 top-32 md:top-40 w-1.5 h-1.5 md:w-2 md:h-2 rounded-full bg-[#FFD738]" />
              <div className="absolute right-6 top-48 w-2 h-2 md:w-3 md:h-3 rounded-full bg-[#FFD738]" />
            </div>

            <Image
              src="/mascots/salta-saltu-salto-please-pose.avif"
              alt="Mascots"
              width={574}
              height={326}
              loading="lazy"
              sizes="(max-width: 640px) 240px, (max-width: 768px) 280px, 574px"
              className="object-contain drop-shadow-xl relative z-10"
            />
          </div>

          {/* Yellow Rounded Container */}
          <div className="bg-[#FFD738] rounded-[30px] md:rounded-[50px] pt-16 md:pt-24 pb-10 md:pb-16 px-4 md:px-8 shadow-[4px_4px_4.5px_0px_rgba(0,0,0,0.25)] relative overflow-hidden">
            {/* Scrollable product row with arrows */}
            <div className="relative z-10">
              {/* Arrow Left */}
              <button
                type="button"
                onClick={() => scroll('left')}
                disabled={!canScrollLeft}
                aria-label="Scroll left"
                className="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-1/2 z-20 w-10 h-10 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center shadow-lg hover:bg-white hover:scale-110 transition-all duration-200 disabled:opacity-0 disabled:pointer-events-none"
              >
                <ChevronLeft size={20} className="text-[#6E5904]" />
              </button>

              {/* Arrow Right */}
              <button
                type="button"
                onClick={() => scroll('right')}
                disabled={!canScrollRight}
                aria-label="Scroll right"
                className="absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 z-20 w-10 h-10 rounded-full bg-white/90 backdrop-blur-sm flex items-center justify-center shadow-lg hover:bg-white hover:scale-110 transition-all duration-200 disabled:opacity-0 disabled:pointer-events-none"
              >
                <ChevronRight size={20} className="text-[#6E5904]" />
              </button>

              <div
                ref={scrollRef}
                className="flex gap-4 xl:gap-6 overflow-x-auto scroll-smooth pb-2 pt-4 scrollbar-hide justify-center md:justify-center font-bold"
              >
                {sortedProducts.map((product: Product, idx: number) => (
                  <div
                    key={product.id}
                    className="shrink-0 w-[260px] sm:w-[280px] md:w-[300px]"
                  >
                    <ProductCard product={product} index={idx} />
                  </div>
                ))}
              </div>
            </div>

            {/* Footer: line, view all */}
            <div className="flex justify-end items-center mt-12 px-4 relative z-10">
              <div className="flex items-center gap-3 shrink-0 ml-4">
                <Link
                  href="/products"
                  className="font-bold text-[#6E5904] text-lg tracking-[-0.31px] hover:underline flex items-center gap-2"
                >
                  View All
                  <ChevronRight size={20} className="text-[#6E5904]" />
                </Link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
