"use client";

import * as React from 'react';
import { ArrowLeft, ArrowRight, Download, ShieldCheck, FileText, ChevronDown, MessageSquare } from 'lucide-react';
import { useLanguage } from './LanguageContext';
import { useNavigation } from './NavigationContext';
import { useTheme } from './ThemeContext';
import ImageWithFallback from './ImageWithFallback';
import { motion } from 'motion/react';
import Link from 'next/link';
import { PREMIUM_SILIKON_COLORS, NEUTRAL_SILIKON_COLORS, LACK_SPRAY_COLORS } from '../constants';



interface ProductPageProps {
  product: {
    id: string;
    name: string;
    description: string;
    image: string;
    categoryName?: string;
  };
  categoryId?: string;
}

const ProductPage: React.FC<ProductPageProps> = ({ product: initialProduct, categoryId }) => {
  const { t, getProductByImage } = useLanguage();
  const { theme } = useTheme();

  const product = getProductByImage(initialProduct.image) || initialProduct;
  const [activeMediaIndex, setActiveMediaIndex] = React.useState(0);
  const isColorProduct = product.image.toLowerCase().includes('/products/colors/');
  const isCleaningProduct = product.image.toLowerCase().includes('/cleaning/');

  const isPremiumSilikon = product.name.toLowerCase().includes('premium') && product.name.toLowerCase().includes('sili');
  const isNeutralSilikon = product.name.toLowerCase().includes('neutral') && product.name.toLowerCase().includes('sili');
  const isLackSpray = product.name.toLowerCase().includes('lack spray') || product.name.toLowerCase().includes('paint spray') || product.name.toLowerCase().includes('llak sprej');
  const isFelgensilber = product.image.includes('felgensilber');
  const isHaftgrund = product.image.includes('haftgrund');
  const isHochtemperaturLack = product.image.includes('hochtemperatur-lack');
  const isStrukturAcryl = product.image.includes('/struktur-acryl/');
  const isUniversalAcryl = product.image.includes('/universal-acryl/');
  const isExtremKleber = product.image.includes('/extrem-kleber/');
  const isAcrylProduct = isStrukturAcryl || isUniversalAcryl;

  const [openAccordions, setOpenAccordions] = React.useState<string[]>(['details']);

  const toggleAccordion = (id: string) => {
    setOpenAccordions(prev => 
      prev.includes(id) ? prev.filter(a => a !== id) : [...prev, id]
    );
  };

  const [selectedColorIndex, setSelectedColorIndex] = React.useState(() => {
    if (isLackSpray && product.image.includes('rot')) {
      return 7; // Rot is index 7 in LACK_SPRAY_COLORS
    }
    return 0;
  });

  const activeColor = isPremiumSilikon 
    ? PREMIUM_SILIKON_COLORS[Math.min(selectedColorIndex, PREMIUM_SILIKON_COLORS.length - 1)] 
    : isNeutralSilikon
      ? NEUTRAL_SILIKON_COLORS[Math.min(selectedColorIndex, NEUTRAL_SILIKON_COLORS.length - 1)]
      : isLackSpray
        ? LACK_SPRAY_COLORS[Math.min(selectedColorIndex, LACK_SPRAY_COLORS.length - 1)]
        : undefined;

  const isBauProduct = product.categoryName?.toLowerCase() === 'bau';
  const isServiceProduct = categoryId === 'service' || categoryId === 'service--kfz' || product.categoryName?.toLowerCase() === 'service & kfz' || product.categoryName?.toLowerCase() === 'service & kfz';

  const imageSrc = isPremiumSilikon
    ? `/products/premium-silikon/PREMIUM SILIKON ${activeColor!.fileSuffix}.webp`
    : isNeutralSilikon
      ? `/products/neutral-silikon/M-ONE BAU SILIKON ${activeColor!.fileSuffix}.webp`
      : isLackSpray
        ? `/products/colors/lack-spray/LACK SPRAY M ONE ${activeColor!.fileSuffix}.webp`
        : isColorProduct && product.image.includes('-hell.webp')
          ? product.image.replace('-hell.webp', `-${theme === 'light' ? 'hell' : 'dunkel'}.webp`)
          : product.image;

  const getPaddingClass = () => {
    if (isCleaningProduct) return 'p-4 lg:p-12';
    if (isBauProduct) return 'p-4 lg:p-20';
    if (isServiceProduct || isColorProduct || isLackSpray) return 'p-4 lg:p-6';
    return 'p-1 lg:p-20';
  };

  const getBaseScaleClass = () => {
    if (isCleaningProduct) {
      const path = imageSrc.toLowerCase();
      if (path.includes('-4l')) return 'scale-100 lg:scale-[1.35]';
      if (path.includes('universal-750ml')) return 'scale-[2.42] lg:scale-[1.58]';
      return 'scale-[1.00]';
    }
    return '';
  };

  const getImgScaleClasses = () => {
    if (isCleaningProduct) return 'scale-100'; // Base scale handled by wrapper
    if (isServiceProduct) return 'scale-100 lg:scale-[1.56]';
    if (isColorProduct || isLackSpray) return 'scale-100 lg:scale-[1.30]';
    return isBauProduct ? 'scale-[0.90] lg:scale-100' : 'scale-[0.90] lg:scale-100';
  };

  const modelSrc = isPremiumSilikon
    ? `/products/premium-silikon/PREMIUM SILIKON ${activeColor!.fileSuffix} 3D.glb`
    : isNeutralSilikon
      ? `/products/neutral-silikon/M-ONE BAU SILIKON ${activeColor!.fileSuffix}.glb`
      : isLackSpray
        ? `/products/colors/lack-spray/LACK SPRAY M ONE ${activeColor!.fileSuffix} 3D.glb`
        : isFelgensilber
          ? '/products/colors/felgensilber-3D.glb'
          : isHaftgrund
            ? '/products/colors/haftgrund-3D.glb'
            : isHochtemperaturLack
              ? '/products/colors/hochtemperatur-lack-3D.glb'
              : isStrukturAcryl
              ? '/products/struktur-acryl/M-ONE ACRYL STRUKTUR 3D.glb'
              : isUniversalAcryl
                ? '/products/universal-acryl/M-ONE UNIVERSAL ACRYL.glb'
                : isExtremKleber
                  ? '/products/extrem-kleber/profi mont extrem 3D.glb'
                  : product.image.replace('-3D-4K-Transparent.webp', '-3D.glb');

  const has3D = isPremiumSilikon || isNeutralSilikon || isLackSpray || isFelgensilber || isHaftgrund || isHochtemperaturLack || isAcrylProduct || isExtremKleber || product.image.includes('3D-4K');

  // Load @google/model-viewer only on client (it uses 'self' which doesn't exist in SSR)
  React.useEffect(() => {
    import('@google/model-viewer');
  }, []);

  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'auto' });
  }, []);

  // Preload assets for lightning-fast switching
  React.useEffect(() => {
    if (isPremiumSilikon) {
      PREMIUM_SILIKON_COLORS.forEach((color) => {
        const img = new Image();
        img.src = `/products/premium-silikon/PREMIUM SILIKON ${color.fileSuffix}.webp`;
        fetch(`/products/premium-silikon/PREMIUM SILIKON ${color.fileSuffix} 3D.glb`, { priority: 'low' as RequestPriority }).catch(() => {});
      });
    } else if (isNeutralSilikon) {
      NEUTRAL_SILIKON_COLORS.forEach((color) => {
        const img = new Image();
        img.src = `/products/neutral-silikon/M-ONE BAU SILIKON ${color.fileSuffix}.webp`;
        fetch(`/products/neutral-silikon/M-ONE BAU SILIKON ${color.fileSuffix}.glb`, { priority: 'low' as RequestPriority }).catch(() => {});
      });
    } else if (isLackSpray) {
      LACK_SPRAY_COLORS.forEach((color) => {
        const img = new Image();
        img.src = `/products/colors/lack-spray/LACK SPRAY M ONE ${color.fileSuffix}.webp`;
        fetch(`/products/colors/lack-spray/LACK SPRAY M ONE ${color.fileSuffix} 3D.glb`, { priority: 'low' as RequestPriority }).catch(() => {});
      });
    } else if (isFelgensilber) {
      const img = new Image();
      img.src = '/products/colors/felgensilber-transparent.webp';
      fetch('/products/colors/felgensilber-3D.glb', { priority: 'low' as RequestPriority }).catch(() => {});
    } else if (isHaftgrund) {
      const img = new Image();
      img.src = '/products/colors/haftgrund-transparent.webp';
      fetch('/products/colors/haftgrund-3D.glb', { priority: 'low' as RequestPriority }).catch(() => {});
    }
  }, [isPremiumSilikon, isNeutralSilikon, isLackSpray, isFelgensilber, isHaftgrund]);

  const handleDownload = (type: string) => {
    alert(`${type} ${t.products.downloadStarted}`);
  };

  const getVariantFolder = () => {
    if (isPremiumSilikon) return 'premium-silikon';
    if (isNeutralSilikon) return 'neutral-silikon';
    if (isLackSpray) return 'colors/lack-spray';
    return '';
  };

  const getVariantList = () => {
    if (isPremiumSilikon) return PREMIUM_SILIKON_COLORS;
    if (isNeutralSilikon) return NEUTRAL_SILIKON_COLORS;
    if (isLackSpray) return LACK_SPRAY_COLORS;
    return [];
  };

  const hasVariants = isPremiumSilikon || isNeutralSilikon || isLackSpray;

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.8, ease: [0.25, 1, 0.5, 1] }}
      className="min-h-screen bg-white dark:bg-neutral-950 pt-24 lg:pt-24 pb-32"
    >
      <div className="container mx-auto px-6">
        {categoryId ? (
          <Link
            href={`/produkte/${categoryId === 'service' ? 'service--kfz' : categoryId}`}
            className="text-neutral-400 hover:text-brand-500 mb-6 lg:mb-10 flex items-center gap-2 transition-colors font-bold uppercase tracking-widest text-xs"
          >
            <ArrowLeft size={16} />
            {t.products.backToCategory}
          </Link>
        ) : (
          <button
            onClick={() => window.history.back()}
            className="text-neutral-400 hover:text-brand-500 mb-6 lg:mb-10 flex items-center gap-2 transition-colors font-bold uppercase tracking-widest text-xs"
          >
            <ArrowLeft size={16} />
            {t.products.backToCategory}
          </button>
        )}

        <div className="flex flex-col lg:flex-row gap-12 lg:gap-16 items-start lg:mt-4">
          {/* Left Column: Visual Excellence (35%) + Mobile Color Selection */}
          <div className="w-full lg:w-[35%] flex flex-row lg:flex-col gap-3 sm:gap-6 lg:gap-0 lg:sticky lg:top-32 h-auto lg:h-min">
            <motion.div
              initial={{ opacity: 0, scale: 0.98 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 1, ease: [0.25, 1, 0.5, 1] }}
              className="w-[65%] lg:w-full relative aspect-[2/3] lg:aspect-[3/4] rounded-[2.5rem] bg-[#F9F9F9] dark:bg-neutral-900/40 border border-neutral-100 dark:border-neutral-900 flex items-center justify-center overflow-hidden group/visual shadow-2xl shadow-black/5 dark:shadow-[0_40px_100px_-30px_rgba(0,0,0,0.4)]"
            >
              {/* 2D Image View */}
              <div
                className={`absolute inset-0 transition-opacity duration-500 flex items-center justify-center ${activeMediaIndex === 0 ? 'opacity-100 z-50' : 'opacity-0 z-0 pointer-events-none'
                  } ${getBaseScaleClass()}`}
              >
                {hasVariants ? (
                  <img
                    src={imageSrc}
                    alt={`${product.name} ${activeColor!.name}`}
                    className={`w-full h-full ${getPaddingClass()} object-contain ${getImgScaleClasses()} origin-center transition-transform duration-1000 ease-[cubic-bezier(0.25,1,0.5,1)] group-hover/visual:scale-110`}
                    loading="eager"
                    decoding="sync"
                    fetchPriority="high"
                  />
                ) : (
                  <ImageWithFallback
                    src={imageSrc}
                    alt={product.name}
                    className={`w-full h-full ${getPaddingClass()}`}
                    imgClassName={`object-contain ${getImgScaleClasses()} origin-center transition-transform duration-1000 ease-[cubic-bezier(0.25,1,0.5,1)] group-hover/visual:scale-110`}
                    fallbackStrategy="picsum"
                  />
                )}
              </div>

              {/* 3D Model View */}
              {has3D && (
                <div
                  className={`absolute inset-0 transition-opacity duration-500 ${activeMediaIndex === 1 ? 'opacity-100 z-50' : 'opacity-0 z-0 pointer-events-none'
                    }`}
                >
                  {/* @ts-ignore */}
                  <model-viewer
                    key={modelSrc}
                    src={modelSrc}
                    alt={`${product.name} ${hasVariants ? activeColor!.name : ''} 3D`}
                    shadow-intensity="1"
                    camera-controls
                    auto-rotate
                    ar
                    loading="eager"
                    style={{ width: '100%', height: '100%', backgroundColor: 'transparent' }}
                  ></model-viewer>
                </div>
              )}

              {/* Gallery Toggle */}
              {has3D && (
                <motion.div 
                  initial={{ opacity: 0, x: -20 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="absolute bottom-4 left-4 flex gap-1.5 p-1 glass-panel rounded-full border border-white/10 shadow-2xl z-[60]"
                >
                  {[0, 1].map((idx) => (
                    <button
                      key={idx}
                      onClick={() => setActiveMediaIndex(idx)}
                      className={`px-3 py-1.5 rounded-full text-[9px] lg:text-[11px] font-black uppercase tracking-[0.15em] transition-all duration-500 ${activeMediaIndex === idx
                        ? 'bg-brand-500 text-white shadow-lg shadow-brand-500/20'
                        : 'text-neutral-500 hover:text-neutral-950 dark:hover:text-white'
                        }`}
                    >
                      {idx === 0 ? 'IMG' : '3D'}
                    </button>
                  ))}
                  {/* Subtle attention pulse */}
                  <motion.div
                    animate={{ opacity: [0, 0.4, 0] }}
                    transition={{ duration: 3, repeat: Infinity }}
                    className="absolute inset-0 rounded-full bg-brand-500/20 blur-md pointer-events-none -z-10"
                  />
                </motion.div>
              )}
            </motion.div>

            {/* Mobile Color Selection (35% width, 2 columns) */}
            {hasVariants && (
              <div className="w-[35%] lg:hidden block">
                <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-neutral-400 dark:text-neutral-600 mb-2">
                  Farbe
                </h3>
                <div className="grid grid-cols-2 gap-2 pb-2">
                  {getVariantList().map((color, idx) => (
                    <div key={color.id} className="flex flex-col items-center">
                      <button
                        onClick={() => setSelectedColorIndex(idx)}
                        className={`relative w-12 h-12 rounded-full overflow-hidden transition-all duration-300 ${
                          selectedColorIndex === idx 
                            ? 'ring-2 ring-brand-500 ring-offset-2 dark:ring-offset-neutral-950 shadow-lg shadow-brand-500/30 scale-105' 
                            : 'border border-neutral-200 dark:border-neutral-800 opacity-60'
                        }`}
                        title={color.name}
                      >
                        <img 
                          src={`/products/${getVariantFolder()}/punkt ${color.fileSuffix}.webp`} 
                          alt={color.name}
                          className="w-full h-full object-cover scale-110"
                        />
                      </button>
                    </div>
                  ))}
                </div>
                <div className="mt-2 pt-2 border-t border-neutral-100 dark:border-neutral-900">
                  <p className="text-[9px] font-black text-brand-500 uppercase tracking-widest leading-none">
                    {activeColor!.name}
                  </p>
                </div>
              </div>
            )}
          </div>



          {/* Right Column: Premium Engineering Details */}
          <div className="w-full lg:w-[65%] flex flex-col lg:pl-8">
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.8, ease: [0.25, 1, 0.5, 1], delay: 0.2 }}
            >
              {/* Breadcrumbs */}
              <div className="flex items-center gap-2 text-[10px] uppercase tracking-widest font-black text-neutral-400 mb-6 mt-2">
                <Link href="/#categories" className="hover:text-brand-500 transition-colors">Produkte</Link>
                <span className="text-neutral-300">/</span>
                {product.categoryName && (
                  <>
                    <Link 
                      href={`/produkte/${categoryId === 'service' ? 'service--kfz' : categoryId}`} 
                      className="hover:text-brand-500 transition-colors"
                    >
                      {product.categoryName}
                    </Link>
                    <span className="text-neutral-300">/</span>
                  </>
                )}
                <span className="text-brand-500">{product.name}</span>
              </div>

              {/* Title */}
              <h1 className="text-4xl md:text-5xl lg:text-6xl font-black text-neutral-950 dark:text-white leading-[0.95] tracking-tighter mb-6">
                {product.name}
              </h1>
              
              {/* Desktop Color Selection */}
              {hasVariants && (
                <div className="mb-12 hidden lg:block">
                  <h3 className="text-[10px] font-black uppercase tracking-[0.4em] text-neutral-400 dark:text-neutral-600 mb-6 flex items-center gap-4">
                    Farbe Auswählen
                  </h3>
                  <div className={`grid grid-cols-4 ${isLackSpray ? 'lg:grid-cols-5' : 'lg:grid-cols-6'} gap-6`}>
                    {getVariantList().map((color, idx) => (
                      <div key={color.id} className="flex flex-col items-center gap-3">
                        <motion.button
                          whileHover={{ rotate: [0, -5, 5, -5, 5, 0], scale: 1.1 }}
                          transition={{ rotate: { duration: 0.5, ease: "easeInOut" }, scale: { duration: 0.2 } }}
                          onClick={() => setSelectedColorIndex(idx)}
                          className={`relative w-[64px] h-[64px] rounded-full overflow-hidden transition-all duration-300 ${
                            selectedColorIndex === idx 
                              ? 'ring-2 ring-brand-500 ring-offset-2 dark:ring-offset-neutral-950 shadow-lg shadow-brand-500/30' 
                              : 'border border-neutral-200 dark:border-neutral-800'
                          }`}
                          title={color.name}
                        >
                          <img 
                            src={`/products/${getVariantFolder()}/punkt ${color.fileSuffix}.webp`} 
                            alt={color.name}
                            className="w-full h-full object-cover scale-110"
                          />
                        </motion.button>
                        <span className={`text-[10px] font-black uppercase tracking-widest text-center transition-colors ${
                          selectedColorIndex === idx ? 'text-brand-500' : 'text-neutral-400 dark:text-neutral-600'
                        }`}>
                          {color.name}
                        </span>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* Accordions */}
              <div className="space-y-4 border-t border-neutral-100 dark:border-neutral-900 pt-8">
                
                {/* Accordion 1: Details */}
                <div className="border border-neutral-100 dark:border-neutral-900 rounded-2xl overflow-hidden bg-white dark:bg-neutral-950 transition-shadow hover:shadow-lg hover:shadow-black/5">
                  <button 
                    onClick={() => toggleAccordion('details')}
                    className="w-full px-6 py-5 flex items-center justify-between bg-neutral-50/50 dark:bg-neutral-900/20"
                  >
                    <span className="text-xs font-black uppercase tracking-[0.2em] text-neutral-950 dark:text-white">
                      Produktdetails
                    </span>
                    <ChevronDown size={18} className={`text-neutral-400 transition-transform duration-300 ${openAccordions.includes('details') ? 'rotate-180' : ''}`} />
                  </button>
                  <motion.div 
                    initial={false}
                    animate={{ height: openAccordions.includes('details') ? 'auto' : 0, opacity: openAccordions.includes('details') ? 1 : 0 }}
                    className="overflow-hidden"
                  >
                    <div className="p-6 text-sm text-neutral-500 dark:text-neutral-400 font-medium leading-relaxed whitespace-pre-line">
                      {product.description}
                    </div>
                  </motion.div>
                </div>

                {/* Accordion 2: Features */}
                <div className="border border-neutral-100 dark:border-neutral-900 rounded-2xl overflow-hidden bg-white dark:bg-neutral-950 transition-shadow hover:shadow-lg hover:shadow-black/5">
                  <button 
                    onClick={() => toggleAccordion('features')}
                    className="w-full px-6 py-5 flex items-center justify-between bg-neutral-50/50 dark:bg-neutral-900/20"
                  >
                    <span className="text-xs font-black uppercase tracking-[0.2em] text-neutral-950 dark:text-white">
                      Technische Daten
                    </span>
                    <ChevronDown size={18} className={`text-neutral-400 transition-transform duration-300 ${openAccordions.includes('features') ? 'rotate-180' : ''}`} />
                  </button>
                  <motion.div 
                    initial={false}
                    animate={{ height: openAccordions.includes('features') ? 'auto' : 0, opacity: openAccordions.includes('features') ? 1 : 0 }}
                    className="overflow-hidden"
                  >
                    <div className="p-6 space-y-4">
                      {['Profi-Qualität', 'Nach DIN Norm', 'Lange Haltbarkeit'].map((feature, idx) => (
                        <div key={idx} className="flex items-center gap-4 text-sm font-bold text-neutral-700 dark:text-neutral-300 group/feat cursor-default">
                          <div className="w-1.5 h-1.5 rounded-full bg-brand-500 transition-transform duration-300 group-hover/feat:scale-150"></div>
                          {feature}
                        </div>
                      ))}
                    </div>
                  </motion.div>
                </div>

                {/* Accordion 3: Downloads */}
                <div className="border border-neutral-100 dark:border-neutral-900 rounded-2xl overflow-hidden bg-white dark:bg-neutral-950 transition-shadow hover:shadow-lg hover:shadow-black/5">
                  <button 
                    onClick={() => toggleAccordion('downloads')}
                    className="w-full px-6 py-5 flex items-center justify-between bg-neutral-50/50 dark:bg-neutral-900/20"
                  >
                    <span className="text-xs font-black uppercase tracking-[0.2em] text-neutral-950 dark:text-white">
                      Datenblätter & Downloads
                    </span>
                    <ChevronDown size={18} className={`text-neutral-400 transition-transform duration-300 ${openAccordions.includes('downloads') ? 'rotate-180' : ''}`} />
                  </button>
                  <motion.div 
                    initial={false}
                    animate={{ height: openAccordions.includes('downloads') ? 'auto' : 0, opacity: openAccordions.includes('downloads') ? 1 : 0 }}
                    className="overflow-hidden"
                  >
                    <div className="p-2">
                      {[
                        { label: t.products.technicalSheet, icon: FileText, type: 'TDB' },
                        { label: t.products.safetySheet, icon: ShieldCheck, type: 'SDB' }
                      ].map((doc, idx) => (
                        <button
                          key={idx}
                          onClick={() => handleDownload(doc.type)}
                          className="w-full group flex items-center justify-between p-4 hover:bg-neutral-50 dark:hover:bg-neutral-900/40 rounded-xl transition-all duration-300 text-left"
                        >
                          <div className="flex items-center gap-5">
                            <div className="p-3 rounded-lg bg-neutral-100 dark:bg-neutral-900 text-neutral-400 group-hover:text-brand-500 group-hover:bg-brand-50 dark:group-hover:bg-brand-500/10 transition-colors">
                              <doc.icon size={20} />
                            </div>
                            <div>
                              <p className="font-bold text-neutral-950 dark:text-white uppercase tracking-wider text-xs">{doc.label}</p>
                              <p className="text-[10px] text-neutral-400 font-black tracking-widest mt-1">PDF • 1.2 MB</p>
                            </div>
                          </div>
                          <Download size={18} className="text-neutral-300 dark:text-neutral-700 group-hover:text-brand-500 transition-colors" />
                        </button>
                      ))}
                    </div>
                  </motion.div>
                </div>

              </div>

            </motion.div>
          </div>
        </div>
      </div>
    </motion.div>

  );
};

export default ProductPage;
