"use client"

import { useState, useEffect } from "react"
import { Dialog, DialogContent } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { X, ChevronLeft, ChevronRight, Download, Play, Pause, ExternalLink } from "lucide-react"
import type { MediaItem, DocumentItem, AudioItem, LinkItem } from "@/lib/types"

type FileItem = MediaItem | DocumentItem | AudioItem | LinkItem

interface FileViewerModalProps {
  isOpen: boolean
  onClose: () => void
  item: FileItem | null
  allItems?: FileItem[]
  type: "media" | "document" | "audio" | "link"
}

export function FileViewerModal({ isOpen, onClose, item, allItems = [], type }: FileViewerModalProps) {
  const [currentIndex, setCurrentIndex] = useState(0)
  const [isPlaying, setIsPlaying] = useState(false)

  useEffect(() => {
    if (item && allItems.length > 0) {
      const itemIndex = allItems.findIndex((i) => i.id === item.id)
      if (itemIndex !== -1) {
        setCurrentIndex(itemIndex)
      }
    }
  }, [item, allItems])

  if (!item) return null

  const canNavigate = type === "media" && allItems.length > 1
  const currentItem = allItems[currentIndex] || item

  const handlePrevious = () => {
    if (currentIndex > 0) {
      setCurrentIndex(currentIndex - 1)
    }
  }

  const handleNext = () => {
    if (currentIndex < allItems.length - 1) {
      setCurrentIndex(currentIndex + 1)
    }
  }

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl w-full p-0 gap-0 bg-black/95">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-white/10">
          <div className="flex-1 min-w-0">
            <h3 className="text-white font-medium truncate">{currentItem.name}</h3>
            <p className="text-white/60 text-sm">{currentItem.timestamp}</p>
          </div>
          <div className="flex items-center gap-2 ml-4">
            {type === "media" && (currentItem as MediaItem).url && (
              <Button
                size="icon"
                variant="ghost"
                className="text-white hover:bg-white/10"
                onClick={() => {
                  const link = document.createElement("a")
                  link.href = (currentItem as MediaItem).url || ""
                  link.download = currentItem.name
                  link.click()
                }}
              >
                <Download className="h-5 w-5" />
              </Button>
            )}
            <Button size="icon" variant="ghost" className="text-white hover:bg-white/10" onClick={onClose}>
              <X className="h-5 w-5" />
            </Button>
          </div>
        </div>

        {/* Content */}
        <div className="relative flex items-center justify-center min-h-[400px] max-h-[70vh]">
          {type === "media" && <MediaViewer item={currentItem as MediaItem} />}
          {type === "document" && <DocumentViewer item={currentItem as DocumentItem} />}
          {type === "audio" && (
            <AudioViewer item={currentItem as AudioItem} isPlaying={isPlaying} setIsPlaying={setIsPlaying} />
          )}
          {type === "link" && <LinkViewer item={currentItem as LinkItem} />}

          {/* Carousel Navigation for Media */}
          {canNavigate && (
            <>
              <Button
                size="icon"
                variant="ghost"
                className="absolute left-4 top-1/2 -translate-y-1/2 h-10 w-10 rounded-full bg-black/50 text-white hover:bg-black/70 disabled:opacity-30"
                onClick={handlePrevious}
                disabled={currentIndex === 0}
              >
                <ChevronLeft className="h-6 w-6" />
              </Button>
              <Button
                size="icon"
                variant="ghost"
                className="absolute right-4 top-1/2 -translate-y-1/2 h-10 w-10 rounded-full bg-black/50 text-white hover:bg-black/70 disabled:opacity-30"
                onClick={handleNext}
                disabled={currentIndex === allItems.length - 1}
              >
                <ChevronRight className="h-6 w-6" />
              </Button>

              {/* Counter */}
              <div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/70 text-white px-3 py-1 rounded-full text-sm">
                {currentIndex + 1} / {allItems.length}
              </div>
            </>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}

function MediaViewer({ item }: { item: MediaItem }) {
  if (item.type === "video") {
    return (
      <video src={item.url} controls className="max-w-full max-h-[70vh] w-auto h-auto" autoPlay>
        Your browser does not support the video tag.
      </video>
    )
  }

  return (
    <img
      src={item.url || "/placeholder.svg"}
      alt={item.name}
      className="max-w-full max-h-[70vh] w-auto h-auto object-contain"
    />
  )
}

function DocumentViewer({ item }: { item: DocumentItem }) {
  return (
    <div className="flex flex-col items-center justify-center p-8 text-center">
      <div className="h-24 w-24 rounded-2xl bg-blue-500/20 flex items-center justify-center mb-6">
        <svg className="h-12 w-12 text-blue-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
          />
        </svg>
      </div>
      <h3 className="text-white text-lg font-medium mb-2">{item.name}</h3>
      <p className="text-white/60 text-sm mb-6">{item.size}</p>
      <Button
        className="bg-blue-600 hover:bg-blue-700 text-white"
        onClick={() => {
          // Simulate download
          console.log("Downloading:", item.name)
        }}
      >
        <Download className="h-4 w-4 mr-2" />
        Download Document
      </Button>
    </div>
  )
}

function AudioViewer({
  item,
  isPlaying,
  setIsPlaying,
}: { item: AudioItem; isPlaying: boolean; setIsPlaying: (playing: boolean) => void }) {
  return (
    <div className="flex flex-col items-center justify-center p-8 text-center w-full max-w-md">
      <div className="h-32 w-32 rounded-full bg-purple-500/20 flex items-center justify-center mb-6">
        <svg className="h-16 w-16 text-purple-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"
          />
        </svg>
      </div>
      <h3 className="text-white text-lg font-medium mb-2">{item.name}</h3>
      <p className="text-white/60 text-sm mb-6">{item.duration}</p>

      {/* Audio Player */}
      <div className="w-full space-y-4">
        <div className="flex items-center gap-4">
          <Button
            size="icon"
            className="h-12 w-12 rounded-full bg-purple-600 hover:bg-purple-700 text-white"
            onClick={() => setIsPlaying(!isPlaying)}
          >
            {isPlaying ? (
              <Pause className="h-6 w-6" fill="currentColor" />
            ) : (
              <Play className="h-6 w-6 ml-0.5" fill="currentColor" />
            )}
          </Button>
          <div className="flex-1">
            <div className="h-1 bg-white/20 rounded-full overflow-hidden">
              <div className="h-full bg-purple-500 w-1/3 rounded-full" />
            </div>
          </div>
        </div>
        <div className="flex justify-between text-xs text-white/60">
          <span>1:23</span>
          <span>{item.duration}</span>
        </div>
      </div>
    </div>
  )
}

function LinkViewer({ item }: { item: LinkItem }) {
  return (
    <div className="flex flex-col items-center justify-center p-8 text-center w-full max-w-md">
      <div className="h-24 w-24 rounded-2xl bg-green-500/20 flex items-center justify-center mb-6">
        <svg className="h-12 w-12 text-green-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"
          />
        </svg>
      </div>
      <h3 className="text-white text-lg font-medium mb-2">{item.title}</h3>
      {item.description && <p className="text-white/60 text-sm mb-6">{item.description}</p>}
      <p className="text-white/40 text-xs mb-6 break-all">{item.url}</p>
      <Button
        className="bg-green-600 hover:bg-green-700 text-white"
        onClick={() => {
          window.open(item.url, "_blank")
        }}
      >
        <ExternalLink className="h-4 w-4 mr-2" />
        Open Link
      </Button>
    </div>
  )
}
