/**
 * Features Configuration Page
 *
 * Allows enabling/disabling and reordering menu items.
 * Requires private gallery authentication.
 */

import { useState, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  ChevronRight,
  ChevronDown,
  Check,
  Loader2,
  Save,
  RotateCcw,
  Shield,
  FolderDown,
  GalleryHorizontalEnd,
  ClipboardList,
  Clapperboard,
  Star,
  ListVideo,
  Video,
  FolderInput,
  ScanFace,
  CalendarClock,
  User,
  Compass,
  Trash2,
  BarChart3,
  HeartPulse,
  Gauge,
  BellRing,
  LayoutDashboard,
  ScrollText,
  Users,
  Plus,
  ListOrdered,
  Bell,
  Settings,
  Layers,
  Bot,
  FileText,
  Lock,
  GripVertical,
  MessageCircle,
} from 'lucide-react'
import { useBreadcrumb } from '../../hooks/useBreadcrumb'
import { usePrivateGalleryContext } from '../../components/private-gallery/PrivateGalleryProvider'
import { api } from '../../lib/api'

// Feature tree structure matching the navigation menu
interface FeatureItem {
  path: string
  label: string
  icon: React.ComponentType<{ className?: string }>
  disabled?: boolean // Some features can't be disabled
}

interface FeatureGroup {
  id: string
  label: string
  icon: React.ComponentType<{ className?: string }>
  items: FeatureItem[]
}

const FEATURE_GROUPS: FeatureGroup[] = [
  {
    id: 'media',
    label: 'Media',
    icon: GalleryHorizontalEnd,
    items: [
      { path: '/downloads', label: 'Downloads', icon: FolderDown },
      { path: '/gallery', label: 'Gallery', icon: GalleryHorizontalEnd },
      { path: '/review', label: 'Review', icon: ClipboardList },
    ],
  },
  {
    id: 'video',
    label: 'Video',
    icon: Clapperboard,
    items: [
      { path: '/videos', label: 'Video Downloader', icon: Clapperboard },
      { path: '/celebrities', label: 'Internet Discovery', icon: Star },
      { path: '/queue', label: 'Download Queue', icon: ListVideo },
      { path: '/video/channel-monitors', label: 'Channel Monitors', icon: Video },
    ],
  },
  {
    id: 'tools',
    label: 'Tools',
    icon: FolderInput,
    items: [
      { path: '/import', label: 'Manual Import', icon: FolderInput },
      { path: '/faces', label: 'Face Recognition', icon: ScanFace },
      { path: '/scheduler', label: 'Scheduler', icon: CalendarClock },
      { path: '/appearances', label: 'Appearances', icon: User },
      { path: '/discovery', label: 'Discovery', icon: Compass },
      { path: '/recycle-bin', label: 'Recycle Bin', icon: Trash2 },
    ],
  },
  {
    id: 'analytics',
    label: 'Analytics',
    icon: BarChart3,
    items: [
      { path: '/analytics', label: 'Analytics', icon: BarChart3 },
      { path: '/health', label: 'System Health', icon: HeartPulse },
      { path: '/monitoring', label: 'Monitoring', icon: Gauge },
      { path: '/notifications', label: 'Notifications', icon: BellRing },
    ],
  },
  {
    id: 'paid-content',
    label: 'Paid Content',
    icon: ScrollText,
    items: [
      { path: '/paid-content', label: 'Dashboard', icon: LayoutDashboard },
      { path: '/paid-content/feed', label: 'Feed', icon: ScrollText },
      { path: '/paid-content/gallery', label: 'Gallery', icon: GalleryHorizontalEnd },
      { path: '/paid-content/messages', label: 'Messages', icon: MessageCircle },
      { path: '/paid-content/creators', label: 'Creators', icon: Users },
      { path: '/paid-content/add', label: 'Add Content', icon: Plus },
      { path: '/paid-content/queue', label: 'Download Queue', icon: ListOrdered },
      { path: '/paid-content/notifications', label: 'Notifications', icon: Bell },
      { path: '/paid-content/settings', label: 'Configuration', icon: Settings },
    ],
  },
  {
    id: 'system',
    label: 'System',
    icon: Settings,
    items: [
      { path: '/config', label: 'Configuration', icon: Settings, disabled: true },
      { path: '/platforms', label: 'Platforms', icon: Layers },
      { path: '/scrapers', label: 'Scrapers', icon: Bot },
      { path: '/logs', label: 'Logs', icon: ScrollText },
      { path: '/changelog', label: 'Change Log', icon: FileText },
    ],
  },
]

// Get default order for a group
function getDefaultOrder(group: FeatureGroup): string[] {
  return group.items.map(item => item.path)
}

export default function FeaturesConfig() {
  const { isUnlocked } = usePrivateGalleryContext()
  const queryClient = useQueryClient()

  useBreadcrumb([
    { label: 'Private Gallery', path: '/private-gallery' },
    { label: 'Features' },
  ])

  // Fetch current features
  const { data, isLoading } = useQuery({
    queryKey: ['private-gallery-features'],
    queryFn: () => api.privateGallery.getFeatures(),
    enabled: isUnlocked,
  })

  // Local state
  const [enabledFeatures, setEnabledFeatures] = useState<Set<string>>(new Set())
  const [featureOrder, setFeatureOrder] = useState<Record<string, string[]>>({})
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set(FEATURE_GROUPS.map(g => g.id)))
  const [hasChanges, setHasChanges] = useState(false)

  // Drag state
  const [draggedItem, setDraggedItem] = useState<{ groupId: string; path: string } | null>(null)
  const [dragOverItem, setDragOverItem] = useState<{ groupId: string; path: string } | null>(null)

  // Initialize local state when data loads
  useEffect(() => {
    if (data) {
      setEnabledFeatures(new Set(data.enabled_features || []))
      setFeatureOrder(data.feature_order || {})
      setHasChanges(false)
    }
  }, [data])

  // Save mutation
  const saveMutation = useMutation({
    mutationFn: ({ enabled, order }: { enabled: string[]; order: Record<string, string[]> }) =>
      api.privateGallery.updateFeatures({ enabled_features: enabled, feature_order: order }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['private-gallery-features'] })
      queryClient.invalidateQueries({ queryKey: ['enabled-features'] })
      setHasChanges(false)
    },
  })

  const toggleGroup = (groupId: string) => {
    setExpandedGroups(prev => {
      const next = new Set(prev)
      if (next.has(groupId)) {
        next.delete(groupId)
      } else {
        next.add(groupId)
      }
      return next
    })
  }

  const toggleFeature = (path: string) => {
    setEnabledFeatures(prev => {
      const next = new Set(prev)
      if (next.has(path)) {
        next.delete(path)
      } else {
        next.add(path)
      }
      return next
    })
    setHasChanges(true)
  }

  const toggleGroupFeatures = (group: FeatureGroup) => {
    const enabledInGroup = group.items.filter(item => !item.disabled && enabledFeatures.has(item.path))
    const allEnabled = enabledInGroup.length === group.items.filter(i => !i.disabled).length

    setEnabledFeatures(prev => {
      const next = new Set(prev)
      group.items.forEach(item => {
        if (item.disabled) return
        if (allEnabled) {
          next.delete(item.path)
        } else {
          next.add(item.path)
        }
      })
      return next
    })
    setHasChanges(true)
  }

  // Get ordered items for a group
  const getOrderedItems = (group: FeatureGroup): FeatureItem[] => {
    const order = featureOrder[group.id]
    if (!order || order.length === 0) return group.items

    // Sort items based on their position in the order array
    return [...group.items].sort((a, b) => {
      const aIndex = order.indexOf(a.path)
      const bIndex = order.indexOf(b.path)
      // Items not in order array maintain their default position
      const aPos = aIndex === -1 ? group.items.findIndex(i => i.path === a.path) : aIndex
      const bPos = bIndex === -1 ? group.items.findIndex(i => i.path === b.path) : bIndex
      return aPos - bPos
    })
  }

  // Drag handlers
  const handleDragStart = (e: React.DragEvent, groupId: string, path: string) => {
    setDraggedItem({ groupId, path })
    e.dataTransfer.effectAllowed = 'move'
    e.dataTransfer.setData('text/plain', path)
  }

  const handleDragOver = (e: React.DragEvent, groupId: string, path: string) => {
    e.preventDefault()
    if (!draggedItem || draggedItem.groupId !== groupId || draggedItem.path === path) return
    setDragOverItem({ groupId, path })
  }

  const handleDragLeave = () => {
    setDragOverItem(null)
  }

  const handleDrop = (e: React.DragEvent, groupId: string, targetPath: string) => {
    e.preventDefault()
    if (!draggedItem || draggedItem.groupId !== groupId) return

    const group = FEATURE_GROUPS.find(g => g.id === groupId)
    if (!group) return

    // Get current order or default
    const currentOrder = featureOrder[groupId] || getDefaultOrder(group)

    // Find indices
    const fromIndex = currentOrder.indexOf(draggedItem.path)
    const toIndex = currentOrder.indexOf(targetPath)

    if (fromIndex === -1 || toIndex === -1) return

    // Reorder
    const newOrder = [...currentOrder]
    newOrder.splice(fromIndex, 1)
    newOrder.splice(toIndex, 0, draggedItem.path)

    setFeatureOrder(prev => ({
      ...prev,
      [groupId]: newOrder,
    }))
    setHasChanges(true)
    setDraggedItem(null)
    setDragOverItem(null)
  }

  const handleDragEnd = () => {
    setDraggedItem(null)
    setDragOverItem(null)
  }

  const handleSave = () => {
    saveMutation.mutate({
      enabled: Array.from(enabledFeatures),
      order: featureOrder,
    })
  }

  const handleReset = () => {
    if (data) {
      setEnabledFeatures(new Set(data.enabled_features || []))
      setFeatureOrder(data.feature_order || {})
      setHasChanges(false)
    }
  }

  const handleEnableAll = () => {
    const allPaths = FEATURE_GROUPS.flatMap(g => g.items.map(i => i.path))
    setEnabledFeatures(new Set(allPaths))
    setHasChanges(true)
  }

  const handleDisableAll = () => {
    // Keep only disabled items (like /config that can't be disabled)
    const disabledPaths = FEATURE_GROUPS.flatMap(g =>
      g.items.filter(i => i.disabled).map(i => i.path)
    )
    setEnabledFeatures(new Set(disabledPaths))
    setHasChanges(true)
  }

  const handleResetOrder = () => {
    setFeatureOrder({})
    setHasChanges(true)
  }

  if (!isUnlocked) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="text-center">
          <Lock className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
          <p className="text-muted-foreground">Private Gallery is locked</p>
        </div>
      </div>
    )
  }

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-6 max-w-3xl">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Shield className="w-6 h-6 text-primary" />
          <div>
            <h1 className="text-2xl font-bold">Features</h1>
            <p className="text-sm text-muted-foreground">Enable, disable, and reorder menu items</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {hasChanges && (
            <button
              onClick={handleReset}
              className="px-3 py-2 text-sm rounded-lg border border-border hover:bg-secondary flex items-center gap-2"
            >
              <RotateCcw className="w-4 h-4" />
              Reset
            </button>
          )}
          <button
            onClick={handleSave}
            disabled={!hasChanges || saveMutation.isPending}
            className="px-4 py-2 text-sm rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 flex items-center gap-2"
          >
            {saveMutation.isPending ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            Save Changes
          </button>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="flex gap-2 mb-4 flex-wrap">
        <button
          onClick={handleEnableAll}
          className="text-xs px-3 py-1.5 rounded border border-border hover:bg-secondary"
        >
          Enable All
        </button>
        <button
          onClick={handleDisableAll}
          className="text-xs px-3 py-1.5 rounded border border-border hover:bg-secondary"
        >
          Disable All
        </button>
        <button
          onClick={handleResetOrder}
          className="text-xs px-3 py-1.5 rounded border border-border hover:bg-secondary"
        >
          Reset Order
        </button>
      </div>

      {/* Feature Tree */}
      <div className="bg-card border border-border rounded-xl overflow-hidden">
        {FEATURE_GROUPS.map((group, groupIndex) => {
          const isExpanded = expandedGroups.has(group.id)
          const orderedItems = getOrderedItems(group)
          const enableableItems = group.items.filter(i => !i.disabled)
          const enabledCount = enableableItems.filter(i => enabledFeatures.has(i.path)).length
          const allEnabled = enabledCount === enableableItems.length
          const someEnabled = enabledCount > 0 && enabledCount < enableableItems.length
          const GroupIcon = group.icon

          return (
            <div
              key={group.id}
              className={groupIndex > 0 ? 'border-t border-border' : ''}
            >
              {/* Group Header */}
              <div
                className="flex items-center gap-3 px-4 py-3 hover:bg-secondary/50 cursor-pointer"
                onClick={() => toggleGroup(group.id)}
              >
                {isExpanded ? (
                  <ChevronDown className="w-4 h-4 text-muted-foreground" />
                ) : (
                  <ChevronRight className="w-4 h-4 text-muted-foreground" />
                )}

                {/* Group checkbox */}
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    toggleGroupFeatures(group)
                  }}
                  className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ${
                    allEnabled
                      ? 'bg-primary border-primary text-primary-foreground'
                      : someEnabled
                      ? 'bg-primary/30 border-primary'
                      : 'border-muted-foreground/30 hover:border-primary'
                  }`}
                >
                  {allEnabled && <Check className="w-3 h-3" />}
                  {someEnabled && !allEnabled && <div className="w-2 h-2 bg-primary rounded-sm" />}
                </button>

                <GroupIcon className="w-5 h-5 text-muted-foreground" />
                <span className="font-medium flex-1">{group.label}</span>
                <span className="text-xs text-muted-foreground">
                  {enabledCount}/{enableableItems.length}
                </span>
              </div>

              {/* Group Items */}
              {isExpanded && (
                <div className="bg-secondary/20">
                  {orderedItems.map((item) => {
                    const isEnabled = enabledFeatures.has(item.path)
                    const ItemIcon = item.icon
                    const isDragging = draggedItem?.path === item.path && draggedItem?.groupId === group.id
                    const isDragOver = dragOverItem?.path === item.path && dragOverItem?.groupId === group.id

                    return (
                      <div
                        key={item.path}
                        draggable={!item.disabled}
                        onDragStart={(e) => handleDragStart(e, group.id, item.path)}
                        onDragOver={(e) => handleDragOver(e, group.id, item.path)}
                        onDragLeave={handleDragLeave}
                        onDrop={(e) => handleDrop(e, group.id, item.path)}
                        onDragEnd={handleDragEnd}
                        className={`flex items-center gap-2 px-4 py-2.5 pl-8 transition-all ${
                          item.disabled ? 'opacity-50' : 'cursor-grab active:cursor-grabbing'
                        } ${isDragging ? 'opacity-50 bg-secondary' : 'hover:bg-secondary/50'} ${
                          isDragOver ? 'border-t-2 border-primary' : ''
                        }`}
                      >
                        {/* Drag handle */}
                        {!item.disabled && (
                          <GripVertical className="w-4 h-4 text-muted-foreground/50 flex-shrink-0" />
                        )}
                        {item.disabled && <div className="w-4" />}

                        {/* Item checkbox */}
                        <button
                          disabled={item.disabled}
                          onClick={(e) => {
                            e.stopPropagation()
                            if (!item.disabled) toggleFeature(item.path)
                          }}
                          className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-colors flex-shrink-0 ${
                            isEnabled
                              ? 'bg-primary border-primary text-primary-foreground'
                              : 'border-muted-foreground/30 hover:border-primary'
                          } ${item.disabled ? 'cursor-not-allowed' : ''}`}
                        >
                          {isEnabled && <Check className="w-3 h-3" />}
                        </button>

                        <ItemIcon className="w-4 h-4 text-muted-foreground flex-shrink-0" />
                        <span className="flex-1 text-sm">{item.label}</span>
                        {item.disabled && (
                          <span className="text-xs text-muted-foreground bg-secondary px-2 py-0.5 rounded">
                            Required
                          </span>
                        )}
                      </div>
                    )
                  })}
                </div>
              )}
            </div>
          )
        })}
      </div>

      {/* Info */}
      <p className="text-xs text-muted-foreground mt-4 text-center">
        Drag items to reorder. Disabled features will be hidden from the navigation menu.
      </p>
    </div>
  )
}
