'use client'

import { useEffect, useMemo, useState } from 'react'
import Image from 'next/image'
import Link from 'next/link'
import { ChevronDown, ChevronRight, Download, X } from 'lucide-react'
import { cn } from "@/lib/utils"
import HeroProductCard from '@/app/_components/HeroProductCard'
import { useParams } from 'next/navigation'
import useSWR from 'swr'
import { Dialog } from '@headlessui/react'
import { getLanguage } from '@/lib/services/utils'

interface Category {
  title: string;
  slug: string;
  subcategories?: Category[];
}

interface CategoryResponse {
  data: Category[];
}

interface ProductSpec {
  category: string;
  key: string;
  value: string;
}

interface ProductDetail {
  data: {
    name: string;
    slug: string;
    photos: string[];
    description: string;
    videos: string | null;
    brochure: string | null;
    spec: ProductSpec[];
    sub_category: string;
    category: string;
    category_slug: string;
    sub_category_slug: string;
  }
}

interface RelatedProduct {
  id: number;
  name: string;
  slug: string;
  category: string;
  sub_category: string;
  photos: string;
  category_slug: string;
  sub_category_slug: string;
}

interface RelatedProductsResponse {
  data: RelatedProduct[];
}

const fetcher = (url: string) => fetch(url).then(res => res.json());

interface GroupedSpecs {
    [key: string]: Array<{
        category: string;
        key: string;
        value: string;
    }>;
}

const getYoutubeEmbedUrl = (url: string) => {
  try {
    // Handle different YouTube URL formats
    const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
    const match = url.match(regExp);
    const videoId = (match && match[7].length === 11) ? match[7] : null;
    
    return videoId ? `https://www.youtube.com/embed/${videoId}` : null;
  } catch (error) {
    console.error('Error parsing YouTube URL:', error);
    return null;
  }
};

export default function ProductDetailPage() {
    const language = getLanguage();
    const params = useParams();
    const url_categories = `https://admin.ralikagroup.co.id/api/${language}/categories/index`;
    
    const { data: productData, error, isLoading } = useSWR<ProductDetail>(
        `https://admin.ralikagroup.co.id/api/${language}/products/slug/${params.product}`,
        fetcher,
        {
            revalidateOnFocus: true,
            revalidateOnReconnect: true
        }
    );

    const { data: categoriesData, error: categoriesError, isLoading: categoriesLoading } = useSWR<CategoryResponse>(
      url_categories,
      fetcher,
      {
        revalidateOnFocus: true,
        revalidateOnReconnect: true
      }
    );

    const { data: relatedProductsData, error: relatedError, isLoading: relatedLoading } = useSWR<RelatedProductsResponse>(
      `https://admin.ralikagroup.co.id/api/${language}/products/other/${params.product}`,
      fetcher,
      {
        revalidateOnFocus: false,
        revalidateOnReconnect: false
      }
    );

    const [expandedCategory, setExpandedCategory] = useState<string>('');
    const [selectedSubcategory, setSelectedSubcategory] = useState<string>('');

    useEffect(() => {
      if (productData?.data) {
        setExpandedCategory(productData.data.category);
        setSelectedSubcategory(productData.data.sub_category);
      }
    }, [productData?.data]);

    const [selectedImage, setSelectedImage] = useState<string>('/images/placeholder.jpg');
    useEffect(() => {
        if (productData?.data?.photos?.[0]) {
          setSelectedImage(productData.data.photos[0]);
        }
    }, [productData?.data?.photos]);
    const [showAllSpecs, setShowAllSpecs] = useState(false);

    const toggleShowAllSpecs = () => {
        setShowAllSpecs((prev) => !prev); // Toggle between showing all and showing less
    };
    
    const groupedSpecs = useMemo(() => {
        if (!productData?.data.spec) return {};
        
        return productData.data.spec.reduce<GroupedSpecs>((acc, spec) => {
          if (!acc[spec.category]) {
            acc[spec.category] = [];
          }
          acc[spec.category].push(spec);
          return acc;
        }, {});
      }, [productData]);

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [modalImage, setModalImage] = useState('');
    const [scale, setScale] = useState(1);

    const handleZoomIn = () => setScale(prev => Math.min(prev + 0.5, 3));
    const handleZoomOut = () => setScale(prev => Math.max(prev - 0.5, 1));
    const handleZoomReset = () => setScale(1);

    const [position, setPosition] = useState({ x: 0, y: 0 });
    const [isDragging, setIsDragging] = useState(false);
    const [dragStart, setDragStart] = useState({ x: 0, y: 0 });

    if (isLoading) {
        return (
          <div className="animate-pulse space-y-4">
            <div className="h-64 bg-gray-200 rounded-lg"></div>
            <div className="h-8 bg-gray-200 rounded w-1/3"></div>
            <div className="h-4 bg-gray-200 rounded w-full"></div>
          </div>
        );
      }
    
      if (error) {
        return <div>Error loading product details</div>;
      }

    return (
        <div className="min-h-screen">
            {/* Hero Section */}
                <HeroProductCard
                    title={productData?.data.name || ""}
                    subtitle={productData?.data.description || ""}
                    backgroundImage={selectedImage}
                    alt={productData?.data.name || ""}
                />

            {/* Breadcrumb */}
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                <nav className="text-sm">
                    <ol className="flex items-center space-x-2">
                        <li><Link href="/products" className="text-gray-500 hover:text-[#2D4897]">Products</Link></li>
                        <li><span className="text-gray-400 mx-2">/</span></li>
                        <li><Link href={`/products?category=${params.category}`} className="capitalize text-gray-500 hover:text-[#2D4897]">{params.category}</Link></li>
                        <li><span className="text-gray-400 mx-2">/</span></li>
                        <li className="text-[#2D4897]">
                          {isLoading ? (
                            <div className="h-4 w-32 bg-gray-200 animate-pulse rounded"></div>
                          ) : error ? (
                            "Product Not Found"
                          ) : (
                            <span className="truncate">
                              {productData?.data?.name || "Loading..."}
                            </span>
                          )}
                        </li>
                    </ol>
                </nav>
            </div>

            {/* Main Content */}
            <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-6 pb-12">
                <div className="flex flex-col lg:flex-row gap-8">
                    {/* Sidebar */}
                    <div className="w-full lg:w-64 flex-shrink-0">
                        <nav className="space-y-1">
                        <Link
                            href="/products"
                            className={cn(
                            "rounded-lg uppercase w-full flex items-center px-4 py-3 text-left text-sm font-medium hover:bg-[#2D4897] hover:text-white transition-colors duration-200",
                            !params.category ? "text-white bg-[#2D4897]" : "text-gray-900"
                            )}
                            role="button"
                            aria-current={!params.category ? "page" : undefined}
                        >
                            All Products
                        </Link>
                            {categoriesData?.data.map((category, categoryIndex) => (
                              <div key={category.slug || `category-${categoryIndex}`}>
                                <button
                                  onClick={() => setExpandedCategory(expandedCategory === category.title ? '' : category.title)}
                                  className={cn(
                                    "rounded-lg uppercase w-full flex items-center justify-between px-4 py-3 text-left text-sm font-medium hover:bg-[#2D4897] hover:text-white transition-colors duration-200",
                                    expandedCategory === category.title ? "text-white bg-[#2D4897]" : "text-gray-900"
                                  )}
                                >
                                  {category.title}
                                  {expandedCategory === category.title ? (
                                    <ChevronDown className="h-5 w-5" />
                                  ) : (
                                    <ChevronRight className="h-5 w-5" />
                                  )}
                                </button>
                                {expandedCategory === category.title && category.subcategories && (
                                  <div className="bg-white shadow-sm">
                                    {category.subcategories.map((subcategory, subIndex) => (
                                    <Link 
                                        key={subcategory.slug || `subcategory-${subIndex}`}
                                        href={`/products?category=${category.slug}&sub_category=${subcategory.slug}`}
                                        className={cn(
                                        "rounded-lg pl-7 pr-3 capitalize w-full py-2 text-left text-sm transition-colors duration-200",
                                        "hover:bg-gray-50 block",
                                        selectedSubcategory === subcategory.title
                                            ? "text-[#2D4897] font-medium"
                                            : "text-gray-600 hover:text-gray-900"
                                        )}
                                        role="button"
                                        aria-current={selectedSubcategory === subcategory.title ? "page" : undefined}
                                    >
                                        {subcategory.title}
                                    </Link>
                                    ))}
                                  </div>
                                )}
                              </div>
                            ))}
                        </nav>
                    </div>

                    {/* Product Details */}
                    <div className="flex-1">
                        <h2 className="text-2xl font-bold text-[#2D4897] mb-8">
                          {productData?.data.name}
                        </h2>
                        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                            {/* Product Images */}
                            <div>
                                {/* Main Image with Modal trigger */}
                                <div className="relative h-[400px] mb-4">
                                  <button 
                                    onClick={() => {
                                      setModalImage(selectedImage);
                                      setIsModalOpen(true);
                                    }}
                                    className="w-full aspect-[4/3] h-full "
                                  >
                                    <Image
                                      src={selectedImage}
                                      alt={productData?.data.name || "Product"}
                                      fill
                                      className="object-contain bg-center w-full h-full hover:scale-105 rounded-lg hover:brightness-90 transition-all"
                                    />
                                  </button>
                                </div>

                                {/* Photo Gallery - Thumbnails */}
                                <div className="grid grid-cols-5 gap-2">
                                  {Array.isArray(productData?.data?.photos) && productData.data.photos.map((image, index) => (
                                    <button
                                      key={`product-image-${index}`}
                                      onClick={() => setSelectedImage(image)}
                                      className={cn(
                                        "relative h-20 rounded-lg overflow-hidden",
                                        selectedImage === image ? "ring-2 ring-[#2D4897]" : ""
                                      )}
                                    >
                                      <Image
                                        src={image}
                                        alt={`${productData?.data.name || 'Product'} view ${index + 1}`}
                                        fill
                                        className="object-contain bg-center w-full h-full"
                                      />
                                    </button>
                                  ))}
                                </div>
                                {/* Download Brochure */}
                                <div className="mt-8">
                                    {/* Brochure Download Link */}
                                    {productData?.data.brochure ? (
                                        <a 
                                            href={productData.data.brochure}
                                            download
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="flex items-center justify-center w-full border border-[#2D4897] text-[#2D4897] px-6 py-3 rounded-lg hover:bg-[#2D4897] hover:text-white transition-colors duration-300"
                                            onClick={(e) => {
                                            if (!productData.data.brochure) {
                                                e.preventDefault();
                                                alert('Brochure not available');
                                            }
                                            }}
                                        >
                                            <Download className="w-5 h-5 mr-2" />
                                            Download Brochure
                                        </a>
                                    ) : null}
                                </div>

                                {/* Product Video */}
                                {productData?.data.videos && (
                                    <div className="mt-12">
                                        <h2 className="text-lg font-semibold mb-4">{productData?.data.name} Video</h2>
                                        <div className="relative aspect-video bg-gray-100 rounded-lg overflow-hidden">
                                            <iframe
                                                src={getYoutubeEmbedUrl(productData.data.videos)}
                                                title={`${productData.data.name} Video`}
                                                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                                allowFullScreen
                                                className="absolute top-0 left-0 w-full h-full rounded-lg"
                                            />
                                        </div>
                                    </div>
                                )}
                            </div>
                                    
                        {/* Specifications */}
                        <div className="space-y-6">
                            <div className={`relative overflow-hidden transition-all duration-300 ${showAllSpecs ? 'max-h-[3000px]' : 'max-h-[800px]'}`}>
                                {Object.entries(groupedSpecs).map(([category, categorySpecs]) => (
                                <div key={category} className="mb-4">
                                    <h3 className="text-white text-sm font-semibold bg-[#2D4897] px-4 py-2 mb-2">
                                    {category}
                                    </h3>
                                    <div className="border rounded-lg overflow-hidden">
                                    <table className="w-full">
                                        <tbody>
                                        {categorySpecs.map((spec, index) => (
                                            <tr key={index} className="border-b last:border-b-0">
                                            <td className="px-4 py-2 text-sm">{spec.key}</td>
                                            <td className="px-4 py-2 text-sm font-medium">{spec.value}</td>
                                            </tr>
                                        ))}
                                        </tbody>
                                    </table>
                                    </div>
                                </div>
                                ))}
                            </div>
                            {/* Toggle Button */}
                            <button
                                onClick={toggleShowAllSpecs}
                                className="w-full text-center text-[#2D4897] py-2 bg-gray-100 hover:bg-gray-200 transition-colors duration-300"
                            >
                                {showAllSpecs ? 'Show Less' : 'Show All'}
                            </button>
                        </div>
                    </div>

                        {/* Other Products */}
                        <div className="mt-12">
                        <h2 className="text-lg font-semibold mb-6">OTHER PRODUCTS</h2>
                        {relatedLoading ? (
                            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
                            {Array.from({ length: 5 }).map((_, i) => (
                                <div key={`skeleton-${i}`} className="animate-pulse">
                                <div className="bg-gray-200 rounded-lg aspect-[4/3]"></div>
                                <div className="mt-2 h-4 bg-gray-200 rounded w-3/4"></div>
                                </div>
                            ))}
                            </div>
                        ) : relatedError ? (
                            <div className="text-center py-4 text-red-500">Failed to load related products</div>
                        ) : (
                            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
                            {relatedProductsData?.data.map((product, index) => (
                            <Link
                                key={product.id ? `related-product-${product.id}` : `related-product-index-${index}`}
                                href={product.category_slug && product.slug 
                                ? `/products/${product.category_slug}/${product.slug}`
                                : '#'
                                }
                                className="group"
                            >
                                <div className="relative aspect-[4/3] rounded-lg overflow-hidden bg-gray-100">
                                {product.photos ? (
                                    <Image
                                    src={product.photos[0]}
                                    alt={product.name || `Related product ${index + 1}`}
                                    layout="fill"
                                    objectFit="cover"
                                    className="transition-transform duration-300 group-hover:scale-105"
                                    />
                                ) : (
                                    <div className="w-full h-full bg-gray-200 flex items-center justify-center">
                                    <span className="text-gray-400">No image</span>
                                    </div>
                                )}
                                </div>
                                <h3 className="mt-2 text-sm font-medium text-gray-900 group-hover:text-[#2D4897] transition-colors line-clamp-2">
                                {product.name || 'Untitled Product'}
                                </h3>
                                <p className="text-xs text-gray-500 mt-1">
                                {product.category || 'Uncategorized'}
                                </p>
                            </Link>
                            ))}
                            </div>
                        )}
                        </div>

                    </div>
                </div>
            </section>

            {/* Image Modal */}
            <Dialog
                open={isModalOpen}
                onClose={() => {
                    setIsModalOpen(false);
                    setScale(1);
                    setPosition({ x: 0, y: 0 });
                }}
                className="relative z-50"
            >
                <div className="fixed inset-0 bg-black/70" aria-hidden="true" />
                
                <div className="fixed inset-0 overflow-y-auto">
                    <div className="flex min-h-full items-center justify-center p-4">
                        <Dialog.Panel className="relative bg-white rounded-lg max-w-4xl w-full">
                            <button
                                onClick={() => {
                                    setIsModalOpen(false);
                                    setScale(1);
                                    setPosition({ x: 0, y: 0 });
                                }}
                                className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 z-10"
                            >
                                <X className="w-6 h-6" />
                            </button>

                            <div className="relative aspect-video overflow-hidden">
                                <div 
                                    className="absolute inset-0 flex items-center justify-center cursor-move"
                                    style={{ 
                                        transform: `scale(${scale}) translate(${position.x}px, ${position.y}px)`,
                                        transition: isDragging ? 'none' : 'transform 0.2s'
                                    }}
                                    onMouseDown={(e) => {
                                        setIsDragging(true);
                                        setDragStart({
                                            x: e.clientX - position.x,
                                            y: e.clientY - position.y
                                        });
                                    }}
                                    onMouseMove={(e) => {
                                        if (isDragging) {
                                            setPosition({
                                                x: (e.clientX - dragStart.x) / scale,
                                                y: (e.clientY - dragStart.y) / scale
                                            });
                                        }
                                    }}
                                    onMouseUp={() => setIsDragging(false)}
                                    onMouseLeave={() => setIsDragging(false)}
                                    onTouchStart={(e) => {
                                        setIsDragging(true);
                                        setDragStart({
                                            x: e.touches[0].clientX - position.x,
                                            y: e.touches[0].clientY - position.y
                                        });
                                    }}
                                    onTouchMove={(e) => {
                                        if (isDragging) {
                                            setPosition({
                                                x: (e.touches[0].clientX - dragStart.x) / scale,
                                                y: (e.touches[0].clientY - dragStart.y) / scale
                                            });
                                        }
                                    }}
                                    onTouchEnd={() => setIsDragging(false)}
                                >
                                    <Image
                                        src={modalImage}
                                        alt={productData?.data.name || "Product image"}
                                        layout="fill"
                                        objectFit="contain"
                                        quality={100}
                                        draggable={false}
                                    />
                                </div>
                            </div>

                            <div className="p-4 border-t flex justify-center space-x-4">
                                <button
                                    onClick={handleZoomOut}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md"
                                    disabled={scale === 1}
                                >
                                    Zoom Out
                                </button>
                                <button
                                    onClick={() => {
                                        handleZoomReset();
                                        setPosition({ x: 0, y: 0 });
                                    }}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md"
                                >
                                    Reset
                                </button>
                                <button
                                    onClick={handleZoomIn}
                                    className="px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md"
                                    disabled={scale === 3}
                                >
                                    Zoom In
                                </button>
                            </div>
                        </Dialog.Panel>
                    </div>
                </div>
            </Dialog>
        </div>
    )
}

