'use client';

import { useState, useEffect } from 'react';
import { ChevronLeft, ChevronRight, X } from 'lucide-react';
import { Button } from '@/components/ui/button';

interface CompanyImage {
  id: string;
  title: string;
  description?: string;
  image: string;
  category: string;
  isActive: boolean;
  order: number;
  createdAt: string;
  updatedAt: string;
}

interface CompanyGallerySliderProps {
  images?: CompanyImage[];
  autoPlay?: boolean;
  autoPlayDelay?: number;
  className?: string;
}

export default function CompanyGallerySlider({ 
  images = [], 
  autoPlay = true, 
  autoPlayDelay = 4000,
  className = ""
}: CompanyGallerySliderProps) {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isLightboxOpen, setIsLightboxOpen] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState(0);

  // Filter active images and sort by order
  const activeImages = images
    .filter(img => img.isActive)
    .sort((a, b) => a.order - b.order);

  useEffect(() => {
    if (!autoPlay || activeImages.length <= 1) return;

    const interval = setInterval(() => {
      setCurrentIndex(prev => 
        prev === activeImages.length - 1 ? 0 : prev + 1
      );
    }, autoPlayDelay);

    return () => clearInterval(interval);
  }, [autoPlay, autoPlayDelay, activeImages.length]);

  const goToNext = () => {
    setCurrentIndex(prev => 
      prev === activeImages.length - 1 ? 0 : prev + 1
    );
  };

  const goToPrevious = () => {
    setCurrentIndex(prev => 
      prev === 0 ? activeImages.length - 1 : prev - 1
    );
  };

  const openLightbox = (index: number) => {
    setLightboxIndex(index);
    setIsLightboxOpen(true);
  };

  const closeLightbox = () => {
    setIsLightboxOpen(false);
  };

  const nextLightboxImage = () => {
    setLightboxIndex(prev => 
      prev === activeImages.length - 1 ? 0 : prev + 1
    );
  };

  const previousLightboxImage = () => {
    setLightboxIndex(prev => 
      prev === 0 ? activeImages.length - 1 : prev - 1
    );
  };

  if (activeImages.length === 0) {
    return (
      <div className={`bg-gray-100 rounded-lg p-12 text-center ${className}`}>
        <div className="max-w-md mx-auto">
          <div className="text-gray-400 mb-4">
            <svg className="w-16 h-16 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          </div>
          <h3 className="text-xl font-semibold text-gray-600 mb-2">No Gallery Images</h3>
          <p className="text-gray-500">Company gallery images will appear here once added.</p>
        </div>
      </div>
    );
  }

  return (
    <>
      <div className={`relative bg-white rounded-lg overflow-hidden shadow-lg ${className}`}>
        {/* Main Image Display */}
        <div className="relative aspect-video bg-gray-100">
          <img
            src={activeImages[currentIndex]?.image}
            alt={activeImages[currentIndex]?.title}
            className="w-full h-full object-cover cursor-pointer transition-transform duration-300 hover:scale-105"
            onClick={() => openLightbox(currentIndex)}
          />
          
          {/* Image Overlay Info */}
          <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-6">
            <h3 className="text-white text-xl font-semibold mb-2">
              {activeImages[currentIndex]?.title}
            </h3>
            {activeImages[currentIndex]?.description && (
              <p className="text-white/90 text-sm">
                {activeImages[currentIndex].description}
              </p>
            )}
            <div className="text-white/70 text-xs mt-2">
              {activeImages[currentIndex]?.category}
            </div>
          </div>

          {/* Navigation Arrows */}
          {activeImages.length > 1 && (
            <>
              <button
                onClick={goToPrevious}
                className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-white/20 backdrop-blur-sm hover:bg-white/30 text-white p-2 rounded-full transition-all duration-200"
                aria-label="Previous image"
              >
                <ChevronLeft className="h-6 w-6" />
              </button>
              
              <button
                onClick={goToNext}
                className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-white/20 backdrop-blur-sm hover:bg-white/30 text-white p-2 rounded-full transition-all duration-200"
                aria-label="Next image"
              >
                <ChevronRight className="h-6 w-6" />
              </button>
            </>
          )}

          {/* Image Counter */}
          <div className="absolute top-4 right-4 bg-black/50 text-white px-3 py-1 rounded-full text-sm">
            {currentIndex + 1} / {activeImages.length}
          </div>
        </div>

        {/* Thumbnail Strip */}
        {activeImages.length > 1 && (
          <div className="p-4 bg-gray-50">
            <div className="flex gap-2 overflow-x-auto pb-2">
              {activeImages.map((image, index) => (
                <button
                  key={image.id}
                  onClick={() => setCurrentIndex(index)}
                  className={`flex-shrink-0 relative rounded-lg overflow-hidden transition-all duration-200 ${
                    index === currentIndex
                      ? 'ring-2 ring-blue-500 ring-offset-2'
                      : 'hover:ring-2 hover:ring-gray-300 hover:ring-offset-1'
                  }`}
                >
                  <img
                    src={image.image}
                    alt={image.title}
                    className="w-20 h-16 object-cover"
                  />
                  {index === currentIndex && (
                    <div className="absolute inset-0 bg-blue-500/20"></div>
                  )}
                </button>
              ))}
            </div>
          </div>
        )}

        {/* Dots Indicator */}
        {activeImages.length > 1 && (
          <div className="absolute bottom-20 left-1/2 transform -translate-x-1/2">
            <div className="flex space-x-2">
              {activeImages.map((_, index) => (
                <button
                  key={index}
                  onClick={() => setCurrentIndex(index)}
                  className={`w-3 h-3 rounded-full transition-all duration-200 ${
                    index === currentIndex
                      ? 'bg-white scale-110'
                      : 'bg-white/60 hover:bg-white/80'
                  }`}
                  aria-label={`Go to image ${index + 1}`}
                />
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Lightbox Modal */}
      {isLightboxOpen && (
        <div className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4">
          <div className="relative max-w-5xl max-h-full">
            {/* Close Button */}
            <button
              onClick={closeLightbox}
              className="absolute -top-12 right-0 text-white hover:text-gray-300 transition-colors"
              aria-label="Close lightbox"
            >
              <X className="h-8 w-8" />
            </button>

            {/* Lightbox Image */}
            <div className="relative">
              <img
                src={activeImages[lightboxIndex]?.image}
                alt={activeImages[lightboxIndex]?.title}
                className="max-w-full max-h-[80vh] object-contain"
              />

              {/* Lightbox Navigation */}
              {activeImages.length > 1 && (
                <>
                  <button
                    onClick={previousLightboxImage}
                    className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-white/20 backdrop-blur-sm hover:bg-white/30 text-white p-3 rounded-full transition-all duration-200"
                    aria-label="Previous image"
                  >
                    <ChevronLeft className="h-8 w-8" />
                  </button>
                  
                  <button
                    onClick={nextLightboxImage}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-white/20 backdrop-blur-sm hover:bg-white/30 text-white p-3 rounded-full transition-all duration-200"
                    aria-label="Next image"
                  >
                    <ChevronRight className="h-8 w-8" />
                  </button>
                </>
              )}

              {/* Lightbox Counter */}
              <div className="absolute top-4 right-4 bg-black/50 text-white px-4 py-2 rounded-full">
                {lightboxIndex + 1} / {activeImages.length}
              </div>
            </div>

            {/* Lightbox Image Info */}
            <div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 to-transparent text-white p-6">
              <h3 className="text-2xl font-semibold mb-2">
                {activeImages[lightboxIndex]?.title}
              </h3>
              {activeImages[lightboxIndex]?.description && (
                <p className="text-white/90 mb-1">
                  {activeImages[lightboxIndex].description}
                </p>
              )}
              <div className="text-white/70 text-sm">
                {activeImages[lightboxIndex]?.category}
              </div>
            </div>
          </div>

          {/* Click outside to close */}
          <div 
            className="absolute inset-0 -z-10"
            onClick={closeLightbox}
          ></div>
        </div>
      )}
    </>
  );
}