import { useState, useEffect, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useDropzone } from 'react-dropzone'
import { useFlight } from '../../components/FlightContext'
import { api } from '../../api/client'
import { useDebounce } from '../../hooks/useDebounce'
import ConfirmDialog from '../../components/ConfirmDialog'
import { MediaType } from '../../types'
import type { Media, PaginatedResponse, AnnotationListItem } from '../../types'

interface Props {
  selectedMedia: Media | null
  onSelect: (m: Media) => void
  onAnnotationsLoaded: (anns: AnnotationListItem[]) => void
}

export default function MediaList({ selectedMedia, onSelect, onAnnotationsLoaded }: Props) {
  const { t } = useTranslation()
  const { selectedFlight } = useFlight()
  const [media, setMedia] = useState<Media[]>([])
  const [filter, setFilter] = useState('')
  const debouncedFilter = useDebounce(filter, 300)
  const [deleteId, setDeleteId] = useState<string | null>(null)
  const folderInputRef = useRef<HTMLInputElement>(null)

  const fetchMedia = useCallback(async () => {
    const params = new URLSearchParams({ pageSize: '1000' })
    if (selectedFlight) params.set('flightId', selectedFlight.id)
    if (debouncedFilter) params.set('name', debouncedFilter)
    try {
      const res = await api.get<PaginatedResponse<Media>>(`/api/annotations/media?${params}`)
      setMedia(prev => {
        // Keep local-only (blob URL) entries, merge with backend entries
        const local = prev.filter(m => m.path.startsWith('blob:'))
        return [...local, ...res.items]
      })
    } catch {
      // backend unavailable — keep local-only entries
    }
  }, [selectedFlight, debouncedFilter])

  useEffect(() => { fetchMedia() }, [fetchMedia])

  useEffect(() => {
    return () => {
      for (const m of media) if (m.path.startsWith('blob:')) URL.revokeObjectURL(m.path)
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const handleSelect = async (m: Media) => {
    onSelect(m)
    if (m.path.startsWith('blob:')) {
      onAnnotationsLoaded([])
      return
    }
    try {
      const res = await api.get<PaginatedResponse<AnnotationListItem>>(
        `/api/annotations/annotations?mediaId=${m.id}&pageSize=1000`
      )
      onAnnotationsLoaded(res.items)
    } catch {
      onAnnotationsLoaded([])
    }
  }

  const handleDelete = async () => {
    if (!deleteId) return
    const target = media.find(m => m.id === deleteId)
    if (target?.path.startsWith('blob:')) {
      URL.revokeObjectURL(target.path)
      setMedia(prev => prev.filter(m => m.id !== deleteId))
      setDeleteId(null)
      return
    }
    try { await api.delete(`/api/annotations/media/${deleteId}`) } catch {}
    setDeleteId(null)
    fetchMedia()
  }

  const uploadFiles = useCallback(async (files: File[] | FileList) => {
    if (!files.length) return
    const arr = Array.from(files)

    // Try backend first
    if (selectedFlight) {
      try {
        const form = new FormData()
        form.append('waypointId', '')
        for (const file of arr) form.append('files', file)
        await api.upload('/api/annotations/media/batch', form)
        fetchMedia()
        return
      } catch {
        // fall through to local mode
      }
    }

    // Local mode: add blob URL entries to state
    const videoExts = /\.(mp4|mov|webm|mkv|avi|m4v|ogg|ogv)$/i
    const imageExts = /\.(jpe?g|png|webp|gif|bmp|tiff?)$/i
    const accepted: File[] = []
    const rejected: string[] = []
    for (const file of arr) {
      const isVideo = file.type.startsWith('video/') || videoExts.test(file.name)
      const isImage = file.type.startsWith('image/') || imageExts.test(file.name)
      if (isVideo || isImage) accepted.push(file)
      else rejected.push(file.name)
    }
    if (rejected.length) {
      alert(`Unsupported file type (video/image only):\n${rejected.join('\n')}`)
    }

    const localItems: Media[] = accepted.map(file => {
      const isVideo = file.type.startsWith('video/') || videoExts.test(file.name)
      return {
        id: `local-${crypto.randomUUID()}`,
        name: file.name,
        path: URL.createObjectURL(file),
        mediaType: isVideo ? MediaType.Video : MediaType.Image,
        mediaStatus: 0,
        duration: null,
        annotationCount: 0,
        waypointId: null,
        userId: 'local',
      }
    })
    setMedia(prev => [...localItems, ...prev])
  }, [selectedFlight, fetchMedia])

  const { getRootProps, getInputProps, isDragActive } = useDropzone({
    onDrop: uploadFiles,
    multiple: true,
    noClick: true,
    noKeyboard: true,
  })

  const handleFolderInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) uploadFiles(e.target.files)
    e.target.value = ''
  }

  return (
    <div
      {...getRootProps({
        className: `flex-1 flex flex-col overflow-hidden ${isDragActive ? 'ring-2 ring-az-orange ring-inset' : ''}`,
      })}
    >
      <input {...getInputProps()} />
      <div className="p-2 border-b border-az-border flex gap-1">
        <input
          value={filter}
          onChange={e => setFilter(e.target.value)}
          placeholder={t('annotations.mediaList')}
          className="flex-1 bg-az-bg border border-az-border rounded px-2 py-1 text-xs text-az-text outline-none"
        />
      </div>
      <div className="px-2 pt-2 pb-2 flex gap-1">
        <label className="flex-1 bg-az-orange text-white text-[10px] py-1 rounded text-center cursor-pointer hover:brightness-110">
          Open File
          <input
            type="file"
            multiple
            className="hidden"
            onChange={e => {
              if (e.target.files?.length) uploadFiles(e.target.files)
              e.target.value = ''
            }}
          />
        </label>
        <button
          type="button"
          onClick={() => folderInputRef.current?.click()}
          className="flex-1 bg-az-orange text-white text-[10px] py-1 rounded hover:brightness-110"
        >
          Open Folder
        </button>
        <input
          ref={folderInputRef}
          type="file"
          multiple
          className="hidden"
          // @ts-expect-error webkitdirectory is non-standard but widely supported
          webkitdirectory=""
          directory=""
          onChange={handleFolderInput}
        />
      </div>
      <div className="flex-1 overflow-y-auto">
        {media.filter(m => m.name.toLowerCase().includes(filter.toLowerCase())).map(m => (
          <div
            key={m.id}
            onClick={() => handleSelect(m)}
            onContextMenu={e => { e.preventDefault(); setDeleteId(m.id) }}
            className={`px-2 py-1 cursor-pointer border-b border-az-border text-xs flex items-center gap-1.5 ${
              selectedMedia?.id === m.id ? 'bg-az-bg text-white' : ''
            } ${m.annotationCount > 0 ? 'bg-az-bg/50' : ''} text-az-text hover:bg-az-bg`}
          >
            <span className={`font-mono text-[10px] px-1 rounded ${m.mediaType === MediaType.Video ? 'bg-az-blue/20 text-az-blue' : 'bg-az-green/20 text-az-green'}`}>
              {m.mediaType === MediaType.Video ? 'V' : 'P'}
            </span>
            <span className="truncate flex-1">{m.name}</span>
            {m.duration && <span className="text-az-muted">{m.duration}</span>}
          </div>
        ))}
      </div>
      <ConfirmDialog
        open={!!deleteId}
        title={t('annotations.deleteMedia')}
        onConfirm={handleDelete}
        onCancel={() => setDeleteId(null)}
      />
    </div>
  )
}
