'use client'

import { useState, useEffect } from 'react'
import { X, Download, ChevronLeft, ChevronRight, FileText, Package, Settings } from 'lucide-react'
import { Model3D, ModelFile } from '@/types'
import { ImagePlaceholder } from './ImagePlaceholder'
import Image from 'next/image'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'


interface ModelModalProps {
  model: Model3D
  onClose: () => void
}

export function ModelModal({ model, onClose }: ModelModalProps) {
  const [currentImageIndex, setCurrentImageIndex] = useState(0)

  useEffect(() => {
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleEscape)
    document.body.style.overflow = 'hidden'
    
    return () => {
      document.removeEventListener('keydown', handleEscape)
      document.body.style.overflow = 'unset'
    }
  }, [onClose])

  const nextImage = () => {
    setCurrentImageIndex((prev) => (prev + 1) % model.images.length)
  }

  const prevImage = () => {
    setCurrentImageIndex((prev) => (prev - 1 + model.images.length) % model.images.length)
  }

  const getFileIcon = (type: ModelFile['type']) => {
    switch (type) {
      case 'Object': return <Package className="w-5 h-5" />
      case 'CAD': return <Settings className="w-5 h-5" />
      case 'Profile': return <FileText className="w-5 h-5" />
      case 'Guide': return <FileText className="w-5 h-5" />
      default: return <FileText className="w-5 h-5" />
    }
  }

  const getFileTypeColor = (type: ModelFile['type']) => {
    switch (type) {
      case 'Object': return 'bg-blue-500/20 text-blue-400'
      case 'CAD': return 'bg-purple-500/20 text-purple-400'
      case 'Profile': return 'bg-green-500/20 text-green-400'
      case 'Guide': return 'bg-orange-500/20 text-orange-400'
      default: return 'bg-gray-500/20 text-gray-400'
    }
  }

  const downloadAllFiles = async () => {
    const zip = new JSZip()

      for (const file of model.files) {
        try {
          const response = await fetch(file.url)
          if (!response.ok) throw new Error(`Failed to fetch ${file.name}`)
          const blob = await response.blob()

          zip.file(file.name, blob)
        } catch (err) {
            console.error(`Error adding ${file.name} to zip:`, err)
        }
      }

      zip.generateAsync({ type: 'blob' }).then((content) => {
        saveAs(content, `${model.title.replace(/\s+/g, '_')}_files.zip`)
      })
  }


  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div 
        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
        onClick={onClose}
      />
      
      {/* Modal */}
      <div className="relative bg-background border border-border rounded-xl max-w-6xl max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="sticky top-0 bg-background border-b border-border p-6 flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold text-foreground">{model.title}</h2>
            <div className="flex items-center gap-3 mt-2">
              <span className="px-3 py-1 bg-primary/20 text-primary rounded-full text-sm font-medium">
                {model.category}
              </span>
              <span className="text-sm text-muted-foreground">
                {model.files.length} files available
              </span>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-secondary rounded-lg transition-colors"
          >
            <X size={24} />
          </button>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 p-6">
          {/* Image Gallery */}
          <div>
            <div className="relative mb-4">
              <Image 
                fill
                src={model.images[currentImageIndex]}
                alt={model.title}
                className="object-cover group-hover:scale-105 transition-transform duration-300"
              />
              
              {/* Navigation Arrows */}
              {model.images.length > 1 && (
                <>
                  <button
                    onClick={prevImage}
                    className="absolute left-4 top-1/2 transform -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-3 rounded-full transition-all"
                  >
                    <ChevronLeft size={20} />
                  </button>
                  <button
                    onClick={nextImage}
                    className="absolute right-4 top-1/2 transform -translate-y-1/2 bg-black/50 hover:bg-black/70 text-white p-3 rounded-full transition-all"
                  >
                    <ChevronRight size={20} />
                  </button>
                </>
              )}
            </div>

            {/* Thumbnail Gallery */}
            {model.images.length > 1 && (
              <div className="grid grid-cols-4 gap-2">
                {model.images.map((image, index) => (
                  <button
                    key={index}
                    onClick={() => setCurrentImageIndex(index)}
                    className={`relative ${
                      index === currentImageIndex ? 'ring-2 ring-primary' : 'opacity-70 hover:opacity-100'
                    } transition-all rounded-lg overflow-hidden`}
                  >
                    <Image
                      src={image}
                      alt={`${model.title} thumbnail ${index + 1}`}
                      width={80}
                      height={80}
                      className="object-cover"
                    />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Content */}
          <div className="space-y-6">
            {/* Description */}
            <div>
              <h3 className="text-lg font-semibold mb-3 text-foreground">Description</h3>
              <p className="text-muted-foreground leading-relaxed mb-4">
                {model.description}
              </p>
              <p className="text-muted-foreground leading-relaxed">
                {model.detailedDescription}
              </p>
            </div>

            {/* Files */}
            <div>
              <h3 className="text-lg font-semibold mb-4 text-foreground">Available Files</h3>
              <div className="space-y-3">
                {model.files.map((file, index) => (
                  <div
                    key={index}
                    className="flex items-center justify-between p-4 bg-secondary/20 rounded-lg border border-border hover:bg-secondary/30 transition-colors"
                  >
                    <div className="flex items-center gap-3">
                      {getFileIcon(file.type)}
                      <div>
                        <p className="font-medium text-foreground">{file.name}</p>
                        <div className="flex items-center gap-2 mt-1">
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${getFileTypeColor(file.type)}`}>
                            {file.type}
                          </span>
                          <span className="text-sm text-muted-foreground">{file.size}</span>
                        </div>
                      </div>
                    </div>
                    <a
                      href={file.url}
                      download
                      className="flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors text-sm font-medium"
                    >
                      <Download size={16} />
                      Download
                    </a>
                  </div>
                ))}
              </div>
            </div>

            {/* Download All Button */}
            <button
              onClick={downloadAllFiles}
              className="w-full flex items-center justify-center gap-2 px-6 py-4 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors font-semibold text-lg"
            >
              <Download size={20} />
              Download All Files
            </button>

          </div>
        </div>
      </div>
    </div>
  )
}