import { useState } from 'react'
import { RotateCcw, Trash2 } from 'lucide-react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { usePhotoStore } from '../../store/photoStore'
import { useFilterStore } from '../../store/filterStore'
import { usePhotosQuery, stripPhotosFromCache } from '../../hooks/usePhotosQuery'
import { discard as discardApi, photos as photosApi } from '../../services/api'
import { toast } from '../ToastContainer'
import { ConfirmDialog } from '../dialogs/ConfirmDialog'
import { Button } from '@/components/ui/button'
import { formatApiError } from '../../lib/apiError'
import { registerUndoable } from '../../store/undoStore'
import { LIBRARY_STATS_QUERY_KEY } from '../../hooks/useLibraryStatsQuery'

/**
 * Top-of-timeline bar visible only when the discarded filter is active.
 * Shows a count, lets the user restore the current selection, and lets them
 * permanently empty the discard pile (with confirmation).
 */
export function DiscardActionBar() {
  const flag = useFilterStore((s) => s.flag)
  const selectedPhotos = usePhotoStore((s) => s.selectedPhotos)
  const clearSelection = usePhotoStore((s) => s.clearSelection)
  const queryClient = useQueryClient()
  const { data: photos = [] } = usePhotosQuery()

  const [confirmOpen, setConfirmOpen] = useState(false)
  const [deleteSelectedOpen, setDeleteSelectedOpen] = useState(false)

  const restoreMutation = useMutation({
    mutationFn: (ids: string[]) => discardApi.restore(ids),
    // Pull the restored ids out of the discard view immediately. The
    // user is sitting on flag=discarded so they should disappear from
    // sight the moment the click lands; the onSuccess invalidate still
    // reconciles with server truth shortly after.
    onMutate: (ids) => {
      usePhotoStore.getState().removePhotosFromTimeline(ids)
      stripPhotosFromCache(queryClient, ids)
    },
    onSuccess: (_, ids) => {
      registerUndoable(
        `Restored ${ids.length} photo${ids.length === 1 ? '' : 's'}`,
        async () => {
          await photosApi.bulkDiscard(ids)
          queryClient.invalidateQueries({ queryKey: ['photos'] })
      queryClient.invalidateQueries({ queryKey: LIBRARY_STATS_QUERY_KEY })
        }
      )
      clearSelection()
      queryClient.invalidateQueries({ queryKey: ['photos'] })
      queryClient.invalidateQueries({ queryKey: LIBRARY_STATS_QUERY_KEY })
    },
    onError: (e: any) => toast.error('Restore failed', formatApiError(e)),
  })

  const deleteSelectedMutation = useMutation({
    mutationFn: (ids: string[]) => discardApi.deletePermanent(ids),
    onMutate: (ids) => {
      usePhotoStore.getState().removePhotosFromTimeline(ids)
      stripPhotosFromCache(queryClient, ids)
    },
    onSuccess: (data: any) => {
      const count = data?.deleted ?? 0
      const errors = data?.file_errors ?? 0
      if (errors > 0) {
        toast.error(
          `Deleted with ${errors} error${errors > 1 ? 's' : ''}`,
          `${count} record${count === 1 ? '' : 's'} deleted; some files could not be removed`
        )
      } else {
        toast.success(
          'Permanently deleted',
          `${count} photo${count === 1 ? '' : 's'} removed from disk`
        )
      }
      clearSelection()
      queryClient.invalidateQueries({ queryKey: ['photos'] })
      queryClient.invalidateQueries({ queryKey: LIBRARY_STATS_QUERY_KEY })
      setDeleteSelectedOpen(false)
    },
    onError: (e: any) =>
      toast.error('Delete failed', formatApiError(e)),
  })

  const emptyMutation = useMutation({
    mutationFn: () => discardApi.empty(),
    onSuccess: (data: any) => {
      const count = data?.deleted ?? 0
      const errors = data?.file_errors ?? 0
      if (errors > 0) {
        toast.error(
          `Emptied with ${errors} error${errors > 1 ? 's' : ''}`,
          `${count} record${count > 1 ? 's' : ''} deleted; some files could not be removed`
        )
      } else {
        toast.success('Discard pile emptied', `${count} photo${count > 1 ? 's' : ''} permanently deleted`)
      }
      clearSelection()
      queryClient.invalidateQueries({ queryKey: ['photos'] })
      queryClient.invalidateQueries({ queryKey: LIBRARY_STATS_QUERY_KEY })
      setConfirmOpen(false)
    },
    onError: (e: any) => toast.error('Empty failed', formatApiError(e)),
  })

  if (flag !== 'discarded') return null

  const total = photos.length
  const selected = selectedPhotos.length

  return (
    <>
      <div className="flex items-center justify-between gap-3 border-b border-border bg-reject/10 px-4 py-2 text-sm">
        <div className="flex items-center gap-2 text-text">
          <Trash2 className="h-4 w-4 text-reject" />
          <span className="font-medium">Discarded</span>
          <span className="text-text-muted">
            {total} photo{total === 1 ? '' : 's'}
          </span>
        </div>

        <div className="flex items-center gap-2">
          {selected > 0 && (
            <>
              <Button
                variant="secondary"
                size="sm"
                onClick={() => restoreMutation.mutate(selectedPhotos)}
                disabled={restoreMutation.isPending}
                title="Restore selected (U)"
              >
                <RotateCcw className="mr-1.5 h-3.5 w-3.5" />
                Restore {selected}
              </Button>
              <Button
                size="sm"
                onClick={() => setDeleteSelectedOpen(true)}
                disabled={deleteSelectedMutation.isPending}
                className="bg-reject/20 text-reject hover:bg-reject/30"
                title="Permanently delete selected"
              >
                <Trash2 className="mr-1.5 h-3.5 w-3.5" />
                Delete {selected}
              </Button>
            </>
          )}
          <Button
            size="sm"
            onClick={() => setConfirmOpen(true)}
            disabled={total === 0 || emptyMutation.isPending}
            className="bg-reject/20 text-reject hover:bg-reject/30"
            title="Permanently delete all discarded photos and files"
          >
            <Trash2 className="mr-1.5 h-3.5 w-3.5" />
            Empty discard pile
          </Button>
        </div>
      </div>

      <ConfirmDialog
        isOpen={deleteSelectedOpen}
        title={`Delete ${selected} photo${selected === 1 ? '' : 's'}?`}
        message={
          <>
            This will <strong className="text-text">permanently delete</strong>{' '}
            {selected} photo{selected === 1 ? '' : 's'} and remove the file
            {selected === 1 ? '' : 's'} from disk. This cannot be undone.
          </>
        }
        confirmLabel="Delete"
        destructive
        onConfirm={() => deleteSelectedMutation.mutate(selectedPhotos)}
        onClose={() => setDeleteSelectedOpen(false)}
      />

      <ConfirmDialog
        isOpen={confirmOpen}
        title="Empty discard pile?"
        message={
          <>
            This will <strong className="text-text">permanently delete</strong>{' '}
            {total} photo{total === 1 ? '' : 's'} and remove the file
            {total === 1 ? '' : 's'} from disk. This cannot be undone.
          </>
        }
        confirmLabel="Empty pile"
        destructive
        onConfirm={() => emptyMutation.mutate()}
        onClose={() => setConfirmOpen(false)}
      />
    </>
  )
}
