import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useCallback } from 'react'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../../config/breadcrumbConfig'
import { Clock, Play, Trash2, GripVertical, X, Video, Image as ImageIcon, Music } from 'lucide-react'
import { api, PaidContentPost, PaidContentAttachment } from '../../lib/api'
import { formatBytes } from '../../lib/utils'
import BundleLightbox from '../../components/paid-content/BundleLightbox'

function formatDuration(seconds: number | null): string {
  if (!seconds) return ''
  const m = Math.floor(seconds / 60)
  const s = Math.floor(seconds % 60)
  return `${m}:${s.toString().padStart(2, '0')}`
}

function formatResolution(_w: number | null, h: number | null): string {
  if (!h) return ''
  if (h >= 2160) return '4K'
  if (h >= 1440) return '1440p'
  if (h >= 1080) return '1080p'
  if (h >= 720) return '720p'
  return `${h}p`
}

export default function PaidContentWatchLater() {
  useBreadcrumb(breadcrumbConfig['/paid-content/watch-later'])
  const queryClient = useQueryClient()

  const [lightboxActive, setLightboxActive] = useState(false)
  const [lightboxIndex, setLightboxIndex] = useState(0)
  const [dragIndex, setDragIndex] = useState<number | null>(null)
  const [dragOverIndex, setDragOverIndex] = useState<number | null>(null)

  const { data: items = [], isLoading } = useQuery({
    queryKey: ['paid-content-watch-later'],
    queryFn: () => api.paidContent.getWatchLater(),
  })

  const removeMutation = useMutation({
    mutationFn: (attachmentId: number) => api.paidContent.removeFromWatchLater(attachmentId),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['paid-content-watch-later'] }),
  })

  const clearMutation = useMutation({
    mutationFn: () => api.paidContent.clearWatchLater(),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['paid-content-watch-later'] }),
  })

  const reorderMutation = useMutation({
    mutationFn: (orderedIds: number[]) => api.paidContent.reorderWatchLater(orderedIds),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['paid-content-watch-later'] }),
  })

  // Build BundleLightbox-compatible data from watch later items
  const buildLightboxData = useCallback(() => {
    const attachments: PaidContentAttachment[] = items.map(item => ({
      id: item.attachment_id,
      post_id: item.post_id,
      attachment_index: 0,
      name: item.filename,
      file_type: item.file_type,
      extension: item.extension,
      server_path: null,
      download_url: null,
      file_size: item.file_size,
      width: item.width,
      height: item.height,
      duration: item.duration,
      status: item.status,
      local_path: item.local_path,
      local_filename: item.local_filename,
      file_hash: null,
      error_message: null,
      download_attempts: 0,
      downloaded_at: null,
      created_at: null,
    }))

    // Build a synthetic post for context
    const post: PaidContentPost = items.length > 0 ? {
      id: items[0].post_id,
      creator_id: items[0].creator_id,
      post_id: items[0].external_post_id,
      title: items[0].post_title,
      content: null,
      published_at: null,
      added_at: null,
      has_attachments: 1,
      attachment_count: attachments.length,
      downloaded: 1,
      download_date: null,
      is_favorited: 0,
      is_viewed: 0,
      is_pinned: 0,
      pinned_at: null,
      username: items[0].username,
      platform: items[0].platform,
      service_id: '',
      display_name: items[0].display_name,
      profile_image_url: items[0].profile_image_url,
      identity_id: null,
      attachments: attachments,
    } : null as any

    return { attachments, post }
  }, [items])

  // Create a post map for navigating between items from different creators
  const postMapForIndex = useCallback((idx: number) => {
    if (idx < 0 || idx >= items.length) return null
    const item = items[idx]
    return {
      id: item.post_id,
      creator_id: item.creator_id,
      post_id: item.external_post_id,
      title: item.post_title,
      content: null,
      published_at: null,
      added_at: null,
      has_attachments: 1,
      attachment_count: 1,
      downloaded: 1,
      download_date: null,
      is_favorited: 0,
      is_viewed: 0,
      is_pinned: 0,
      pinned_at: null,
      username: item.username,
      platform: item.platform,
      service_id: '',
      display_name: item.display_name,
      profile_image_url: item.profile_image_url,
      identity_id: null,
      attachments: [],
    } as PaidContentPost
  }, [items])

  const handlePlayAll = () => {
    if (items.length === 0) return
    setLightboxIndex(0)
    setLightboxActive(true)
  }

  const handlePlayFrom = (index: number) => {
    setLightboxIndex(index)
    setLightboxActive(true)
  }

  // Drag and drop handlers
  const handleDragStart = (index: number) => {
    setDragIndex(index)
  }

  const handleDragOver = (e: React.DragEvent, index: number) => {
    e.preventDefault()
    setDragOverIndex(index)
  }

  const handleDrop = (e: React.DragEvent, dropIndex: number) => {
    e.preventDefault()
    if (dragIndex === null || dragIndex === dropIndex) {
      setDragIndex(null)
      setDragOverIndex(null)
      return
    }

    const reordered = [...items]
    const [moved] = reordered.splice(dragIndex, 1)
    reordered.splice(dropIndex, 0, moved)
    reorderMutation.mutate(reordered.map(i => i.id))
    setDragIndex(null)
    setDragOverIndex(null)
  }

  const handleDragEnd = () => {
    setDragIndex(null)
    setDragOverIndex(null)
  }

  const fileTypeIcon = (type: string | null) => {
    if (type === 'video') return <Video className="w-4 h-4 text-blue-500" />
    if (type === 'image') return <ImageIcon className="w-4 h-4 text-green-500" />
    if (type === 'audio') return <Music className="w-4 h-4 text-purple-500" />
    return null
  }

  const { attachments, post } = buildLightboxData()
  const [currentPost, setCurrentPost] = useState<PaidContentPost | null>(null)

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between flex-wrap gap-4">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold flex items-center gap-2 sm:gap-3">
            <Clock className="w-8 h-8 text-violet-500" />
            Watch Later
          </h1>
          <p className="text-muted-foreground mt-1">
            {items.length} {items.length === 1 ? 'item' : 'items'} in queue
          </p>
        </div>
        <div className="flex gap-2">
          {items.length > 0 && (
            <>
              <button onClick={handlePlayAll} className="btn btn-primary text-sm">
                <Play className="w-4 h-4 mr-1" /> Play All
              </button>
              <button
                onClick={() => { if (confirm('Clear all watch later items?')) clearMutation.mutate() }}
                className="btn btn-secondary text-sm text-red-500 hover:text-red-600"
              >
                <Trash2 className="w-4 h-4 mr-1" /> Clear All
              </button>
            </>
          )}
        </div>
      </div>

      {/* Content */}
      {isLoading ? (
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent" />
        </div>
      ) : items.length === 0 ? (
        <div className="text-center py-16 text-muted-foreground">
          <Clock className="w-12 h-12 mx-auto mb-3 opacity-30" />
          <p className="text-lg mb-1">No items in Watch Later</p>
          <p className="text-sm">Add items from the Feed or media viewer</p>
        </div>
      ) : (
        <div className="space-y-1">
          {items.map((item, index) => (
            <div
              key={item.id}
              draggable
              onDragStart={() => handleDragStart(index)}
              onDragOver={(e) => handleDragOver(e, index)}
              onDrop={(e) => handleDrop(e, index)}
              onDragEnd={handleDragEnd}
              className={`bg-card rounded-lg border transition-colors flex items-center gap-3 p-3 group cursor-grab active:cursor-grabbing ${
                dragOverIndex === index ? 'border-violet-500 bg-violet-500/5' :
                dragIndex === index ? 'opacity-50 border-border' : 'border-border hover:border-border/80'
              }`}
            >
              {/* Drag Handle */}
              <div className="flex-shrink-0 text-muted-foreground/50 group-hover:text-muted-foreground">
                <GripVertical className="w-5 h-5" />
              </div>

              {/* Position Number */}
              <div className="flex-shrink-0 w-6 text-center text-sm text-muted-foreground font-mono">
                {index + 1}
              </div>

              {/* Thumbnail / Play */}
              <button
                onClick={() => handlePlayFrom(index)}
                className="flex-shrink-0 w-16 h-12 bg-secondary rounded overflow-hidden relative group/thumb"
              >
                {item.attachment_id && (
                  <img
                    src={`/api/paid-content/files/thumbnail/${item.attachment_id}`}
                    className="w-full h-full object-cover"
                    alt=""
                    onError={(e) => { (e.target as HTMLImageElement).style.display = 'none' }}
                  />
                )}
                <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover/thumb:opacity-100 transition-opacity">
                  <Play className="w-5 h-5 text-white" />
                </div>
              </button>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  {fileTypeIcon(item.file_type)}
                  <span className="text-sm font-medium truncate">
                    {item.post_title || item.filename}
                  </span>
                </div>
                <div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
                  <span>{item.display_name || item.username}</span>
                  <span className="capitalize">{item.platform}</span>
                  {item.duration && <span>{formatDuration(item.duration)}</span>}
                  {item.width && item.height && <span>{formatResolution(item.width, item.height)}</span>}
                  {item.file_size && <span>{formatBytes(item.file_size)}</span>}
                </div>
              </div>

              {/* Remove */}
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  removeMutation.mutate(item.attachment_id)
                }}
                className="flex-shrink-0 p-1.5 rounded-lg text-muted-foreground hover:text-red-500 hover:bg-secondary opacity-0 group-hover:opacity-100 transition-opacity"
              >
                <X className="w-4 h-4" />
              </button>
            </div>
          ))}
        </div>
      )}

      {/* BundleLightbox */}
      {lightboxActive && post && attachments.length > 0 && (
        <BundleLightbox
          post={currentPost || post}
          attachments={attachments}
          currentIndex={lightboxIndex}
          onClose={() => {
            setLightboxActive(false)
            setLightboxIndex(0)
            setCurrentPost(null)
          }}
          onNavigate={(idx) => {
            setLightboxIndex(idx)
            const p = postMapForIndex(idx)
            if (p) setCurrentPost(p)
          }}
          initialSlideshow={true}
          autoPlayVideo={true}
        />
      )}
    </div>
  )
}
