import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useState, useMemo } from 'react'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { breadcrumbConfig } from '../../config/breadcrumbConfig'
import {
  Trash2,
  RotateCcw,
  Info,
  CheckSquare,
  Square,
  Clock,
  File,
  Image as ImageIcon,
  Video,
  User,
  X,
} from 'lucide-react'
import { FilterBar, FilterSection, ActiveFilter } from '../../components/FilterPopover'
import { api, getErrorMessage, PaidContentRecycleBinItem, PaidContentCreator } from '../../lib/api'
import { formatBytes, formatRelativeTime } from '../../lib/utils'
import { notificationManager } from '../../lib/notificationManager'

// Display names for platforms
const PLATFORM_DISPLAY_NAMES: Record<string, string> = {
  onlyfans: 'OnlyFans',
  fansly: 'Fansly',
  patreon: 'Patreon',
  fanbox: 'Fanbox',
  gumroad: 'Gumroad',
  youtube: 'YouTube',
}

function getPlatformDisplayName(platform: string): string {
  return PLATFORM_DISPLAY_NAMES[platform] || platform.charAt(0).toUpperCase() + platform.slice(1)
}

// Helper to extract name/details from original_data
function getItemDetails(item: PaidContentRecycleBinItem) {
  const data = item.original_data as Record<string, unknown>
  return {
    name: (data.name as string) || (data.username as string) || (data.title as string) || `Item ${item.original_id}`,
    file_type: data.file_type as string | undefined,
    file_size: data.file_size as number | undefined,
    creator_username: data.creator_username as string | undefined,
    platform: data.platform as string | undefined,
  }
}

function ItemTypeIcon({ type, fileType }: { type: string; fileType?: string }) {
  if (type === 'creator') {
    return <User className="w-5 h-5" />
  }
  if (type === 'post') {
    return <File className="w-5 h-5" />
  }
  if (fileType === 'image') {
    return <ImageIcon className="w-5 h-5" />
  }
  if (fileType === 'video') {
    return <Video className="w-5 h-5" />
  }
  return <File className="w-5 h-5" />
}

function RecycleItemCard({
  item,
  isSelected,
  onSelect,
  onRestore,
  onDelete,
}: {
  item: PaidContentRecycleBinItem
  isSelected: boolean
  onSelect: () => void
  onRestore: () => void
  onDelete: () => void
}) {
  const details = getItemDetails(item)

  return (
    <div
      className={`p-4 border-b border-border last:border-b-0 flex items-center space-x-4 ${
        isSelected ? 'bg-primary/10' : 'hover:bg-secondary/50'
      } transition-colors`}
    >
      <button onClick={onSelect} className="flex-shrink-0">
        {isSelected ? (
          <CheckSquare className="w-5 h-5 text-primary" />
        ) : (
          <Square className="w-5 h-5 text-muted-foreground" />
        )}
      </button>

      <div className="p-2 rounded-lg bg-secondary flex-shrink-0">
        <ItemTypeIcon type={item.item_type} fileType={details.file_type} />
      </div>

      <div className="flex-1 min-w-0">
        <p className="font-medium text-foreground truncate">{details.name}</p>
        <div className="flex items-center space-x-3 text-xs text-muted-foreground mt-1">
          <span className="capitalize">{item.item_type}</span>
          {details.creator_username && (
            <span>@{details.creator_username}</span>
          )}
          {details.platform && (
            <span className="capitalize">{details.platform}</span>
          )}
          {details.file_size && (
            <span>{formatBytes(details.file_size)}</span>
          )}
        </div>
      </div>

      <div className="flex items-center space-x-2 text-xs text-muted-foreground flex-shrink-0">
        <Clock className="w-3 h-3" />
        <span>{formatRelativeTime(item.deleted_at)}</span>
      </div>

      <div className="flex items-center space-x-2 flex-shrink-0">
        <button
          onClick={onRestore}
          className="p-2 rounded-lg hover:bg-secondary text-emerald-600 dark:text-emerald-400 transition-colors"
          title="Restore"
        >
          <RotateCcw className="w-4 h-4" />
        </button>
        <button
          onClick={onDelete}
          className="p-2 rounded-lg hover:bg-red-100 dark:hover:bg-red-900/30 text-red-600 dark:text-red-400 transition-colors"
          title="Delete permanently"
        >
          <Trash2 className="w-4 h-4" />
        </button>
      </div>
    </div>
  )
}

export default function PaidContentRecycleBin() {
  useBreadcrumb(breadcrumbConfig['/paid-content/recycle'])

  const queryClient = useQueryClient()
  const [filterType, setFilterType] = useState('')
  const [filterPlatform, setFilterPlatform] = useState('')
  const [filterCreator, setFilterCreator] = useState('')
  const [filterContentType, setFilterContentType] = useState('')
  const [search, setSearch] = useState('')
  const [selectedIds, setSelectedIds] = useState<number[]>([])

  // Fetch creators for the creator filter dropdown
  const { data: creators = [] } = useQuery<PaidContentCreator[]>({
    queryKey: ['paid-content-creators-all'],
    queryFn: () => api.paidContent.getCreators({}),
    staleTime: 30000,
  })

  // Derive unique platforms from creators
  const availablePlatforms = [...new Set(creators.map(c => c.platform))].sort()

  // Get unique creator usernames
  const availableCreators = [...new Set(creators.map(c => c.username))].sort()

  // Build filter sections for FilterBar
  const filterSections: FilterSection[] = useMemo(() => [
    {
      id: 'itemType',
      label: 'Item Type',
      type: 'select',
      options: [
        { value: '', label: 'All Item Types' },
        { value: 'attachment', label: 'Attachments' },
        { value: 'post', label: 'Posts' },
        { value: 'creator', label: 'Creators' },
      ],
      value: filterType,
      onChange: (v) => setFilterType(v as string),
    },
    {
      id: 'platform',
      label: 'Platform',
      type: 'select',
      options: [
        { value: '', label: 'All Platforms' },
        ...availablePlatforms.map(p => ({ value: p, label: getPlatformDisplayName(p) })),
      ],
      value: filterPlatform,
      onChange: (v) => setFilterPlatform(v as string),
    },
    {
      id: 'creator',
      label: 'Creator',
      type: 'select',
      options: [
        { value: '', label: 'All Creators' },
        ...availableCreators.map(u => ({ value: u, label: u })),
      ],
      value: filterCreator,
      onChange: (v) => setFilterCreator(v as string),
    },
    {
      id: 'contentType',
      label: 'Content Type',
      type: 'select',
      options: [
        { value: '', label: 'All Content' },
        { value: 'image', label: 'Images' },
        { value: 'video', label: 'Videos' },
      ],
      value: filterContentType,
      onChange: (v) => setFilterContentType(v as string),
    },
  ], [filterType, filterPlatform, filterCreator, filterContentType, availablePlatforms, availableCreators])

  // Build active filters for FilterBar
  const activeFilters: ActiveFilter[] = useMemo(() => {
    const filters: ActiveFilter[] = []
    if (search) {
      filters.push({
        id: 'search',
        label: 'Search',
        value: search,
        displayValue: `"${search}"`,
        onRemove: () => setSearch(''),
      })
    }
    if (filterType) {
      filters.push({
        id: 'itemType',
        label: 'Type',
        value: filterType,
        displayValue: filterType.charAt(0).toUpperCase() + filterType.slice(1) + 's',
        onRemove: () => setFilterType(''),
      })
    }
    if (filterPlatform) {
      filters.push({
        id: 'platform',
        label: 'Platform',
        value: filterPlatform,
        displayValue: getPlatformDisplayName(filterPlatform),
        onRemove: () => setFilterPlatform(''),
      })
    }
    if (filterCreator) {
      filters.push({
        id: 'creator',
        label: 'Creator',
        value: filterCreator,
        displayValue: filterCreator,
        onRemove: () => setFilterCreator(''),
      })
    }
    if (filterContentType) {
      filters.push({
        id: 'contentType',
        label: 'Content',
        value: filterContentType,
        displayValue: filterContentType.charAt(0).toUpperCase() + filterContentType.slice(1) + 's',
        onRemove: () => setFilterContentType(''),
      })
    }
    return filters
  }, [search, filterType, filterPlatform, filterCreator, filterContentType])

  const { data: items, isLoading } = useQuery({
    queryKey: ['paid-content-recycle-bin', filterType, filterPlatform, filterCreator, filterContentType, search],
    queryFn: () =>
      api.paidContent.getRecycleBin({
        item_type: filterType || undefined,
        platform: filterPlatform || undefined,
        creator: filterCreator || undefined,
        content_type: filterContentType || undefined,
        search: search || undefined,
      }),
  })

  const clearFilters = () => {
    setFilterType('')
    setFilterPlatform('')
    setFilterCreator('')
    setFilterContentType('')
    setSearch('')
  }

  const restoreMutation = useMutation({
    mutationFn: (ids: number[]) => api.paidContent.restoreFromRecycleBin(ids),
    onSuccess: (_, ids) => {
      notificationManager.success('Restored', `${ids.length} item(s) restored successfully`)
      queryClient.invalidateQueries({ queryKey: ['paid-content-recycle-bin'] })
      setSelectedIds([])
    },
    onError: (error: unknown) => {
      notificationManager.error('Restore Failed', getErrorMessage(error))
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (ids: number[]) => api.paidContent.permanentlyDelete(ids),
    onSuccess: (_, ids) => {
      notificationManager.success('Deleted', `${ids.length} item(s) permanently deleted`)
      queryClient.invalidateQueries({ queryKey: ['paid-content-recycle-bin'] })
      setSelectedIds([])
    },
    onError: (error: unknown) => {
      notificationManager.error('Delete Failed', getErrorMessage(error))
    },
  })

  const emptyBinMutation = useMutation({
    mutationFn: () => api.paidContent.emptyRecycleBin(),
    onSuccess: () => {
      notificationManager.success('Emptied', 'Recycle bin has been emptied')
      queryClient.invalidateQueries({ queryKey: ['paid-content-recycle-bin'] })
      setSelectedIds([])
    },
    onError: (error: unknown) => {
      notificationManager.error('Failed', getErrorMessage(error))
    },
  })

  const handleSelectAll = () => {
    if (selectedIds.length === items?.length) {
      setSelectedIds([])
    } else {
      setSelectedIds(items?.map((i) => i.id) || [])
    }
  }

  const handleSelect = (id: number) => {
    setSelectedIds((prev) =>
      prev.includes(id) ? prev.filter((i) => i !== id) : [...prev, id]
    )
  }

  const handleRestoreSelected = () => {
    if (selectedIds.length === 0) return
    restoreMutation.mutate(selectedIds)
  }

  const handleDeleteSelected = () => {
    if (selectedIds.length === 0) return
    if (
      window.confirm(
        `Are you sure you want to permanently delete ${selectedIds.length} item(s)? This cannot be undone.`
      )
    ) {
      deleteMutation.mutate(selectedIds)
    }
  }

  const handleEmptyBin = () => {
    if (
      window.confirm(
        'Are you sure you want to empty the recycle bin? All items will be permanently deleted. This cannot be undone.'
      )
    ) {
      emptyBinMutation.mutate()
    }
  }

  const handleRestoreSingle = (id: number) => {
    restoreMutation.mutate([id])
  }

  const handleDeleteSingle = (id: number) => {
    if (window.confirm('Are you sure you want to permanently delete this item? This cannot be undone.')) {
      deleteMutation.mutate([id])
    }
  }

  const allSelected = items && items.length > 0 && selectedIds.length === items.length

  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">
            <Trash2 className="w-8 h-8 text-red-500" />
            Recycle Bin
          </h1>
          <p className="text-slate-600 dark:text-slate-400 mt-1">
            {items?.length || 0} items in recycle bin
          </p>
        </div>
        {items && items.length > 0 && (
          <button
            onClick={handleEmptyBin}
            disabled={emptyBinMutation.isPending}
            className="btn btn-danger"
          >
            <Trash2 className="w-4 h-4 mr-2" />
            Empty Bin
          </button>
        )}
      </div>

      {/* Filters */}
      <div className="card-glass-hover rounded-xl p-4 relative z-30">
        <FilterBar
          searchValue={search}
          onSearchChange={setSearch}
          searchPlaceholder="Search items..."
          filterSections={filterSections}
          activeFilters={activeFilters}
          onClearAll={clearFilters}
          totalCount={items?.length}
          countLabel="items in recycle bin"
        />
      </div>

      {/* Selection Actions */}
      {selectedIds.length > 0 && (
        <div className="bg-primary/10 rounded-xl border border-primary/20 p-4 flex items-center justify-between">
          <span className="text-sm font-medium text-foreground">
            {selectedIds.length} item(s) selected
          </span>
          <div className="flex items-center space-x-2">
            <button onClick={handleRestoreSelected} className="btn btn-sm btn-secondary">
              <RotateCcw className="w-4 h-4 mr-1" />
              Restore
            </button>
            <button onClick={handleDeleteSelected} className="btn btn-sm btn-danger">
              <Trash2 className="w-4 h-4 mr-1" />
              Delete
            </button>
            <button
              onClick={() => setSelectedIds([])}
              className="p-2 rounded-lg hover:bg-secondary"
            >
              <X className="w-4 h-4 text-muted-foreground" />
            </button>
          </div>
        </div>
      )}

      {/* Items List */}
      <div className="bg-card rounded-xl border border-border overflow-hidden">
        {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>
          </div>
        ) : !items || items.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
            <Trash2 className="w-12 h-12 mb-4 opacity-50" />
            <h3 className="text-lg font-semibold text-foreground">Recycle bin is empty</h3>
            <p className="mt-1">Deleted items will appear here</p>
          </div>
        ) : (
          <>
            {/* Select All Header */}
            <div className="p-4 border-b border-border bg-secondary/30 flex items-center space-x-4">
              <button onClick={handleSelectAll}>
                {allSelected ? (
                  <CheckSquare className="w-5 h-5 text-primary" />
                ) : (
                  <Square className="w-5 h-5 text-muted-foreground" />
                )}
              </button>
              <span className="text-sm font-medium text-foreground">
                {allSelected ? 'Deselect all' : 'Select all'}
              </span>
            </div>

            {/* Items */}
            <div className="max-h-[calc(100vh-400px)] overflow-y-auto">
              {items.map((item) => (
                <RecycleItemCard
                  key={item.id}
                  item={item}
                  isSelected={selectedIds.includes(item.id)}
                  onSelect={() => handleSelect(item.id)}
                  onRestore={() => handleRestoreSingle(item.id)}
                  onDelete={() => handleDeleteSingle(item.id)}
                />
              ))}
            </div>
          </>
        )}
      </div>

      {/* Warning */}
      <div className="bg-blue-100 dark:bg-blue-900/20 rounded-xl p-4 flex items-start space-x-3">
        <Info className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
        <div>
          <h3 className="font-medium text-blue-800 dark:text-blue-200">
            Items are kept indefinitely
          </h3>
          <p className="text-sm text-blue-700 dark:text-blue-300 mt-1">
            Restore items to return them to your library, or empty the bin to permanently delete them.
          </p>
        </div>
      </div>
    </div>
  )
}
