'use client'

import { useState, useEffect, useMemo } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import {
  Loader2,
  HardDrive,
  Search,
  AlertTriangle,
  Check,
  ChevronDown,
  ChevronRight,
} from 'lucide-react'
import { useNetcupImageFlavours, useNetcupReinstall, type ImageFlavour } from '@/hooks/use-netcup'
import { SliderConfirmDialog } from '@/components/ui/slider-confirm-dialog'

interface ReinstallDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  serverId: string
  serverName?: string
  onReinstallStarted?: (taskId: string) => void
}

export function ReinstallDialog({
  open,
  onOpenChange,
  serverId,
  serverName,
  onReinstallStarted,
}: ReinstallDialogProps) {
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedFlavour, setSelectedFlavour] = useState<ImageFlavour | null>(null)
  const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false)

  const { data: flavoursData, isLoading, error, refetch } = useNetcupImageFlavours(serverId)
  const reinstallMutation = useNetcupReinstall()

  // Reset state when dialog opens
  useEffect(() => {
    if (open) {
      setSearchQuery('')
      setSelectedFlavour(null)
      setExpandedCategories(new Set())
      refetch()
    }
  }, [open, refetch])

  // Group flavours by category
  const groupedFlavours = useMemo(() => {
    if (!flavoursData?.flavours) return {}

    const filtered = flavoursData.flavours.filter((f) => {
      const query = searchQuery.toLowerCase()
      return (
        f.name.toLowerCase().includes(query) ||
        f.category.toLowerCase().includes(query) ||
        f.description?.toLowerCase().includes(query)
      )
    })

    return filtered.reduce(
      (acc, flavour) => {
        const category = flavour.category || 'Other'
        if (!acc[category]) acc[category] = []
        acc[category].push(flavour)
        return acc
      },
      {} as Record<string, ImageFlavour[]>
    )
  }, [flavoursData?.flavours, searchQuery])

  // Sort categories alphabetically, but put common ones first
  const sortedCategories = useMemo(() => {
    const categories = Object.keys(groupedFlavours)
    const priority = ['Debian', 'Ubuntu', 'CentOS', 'Rocky', 'AlmaLinux', 'Windows']

    return categories.sort((a, b) => {
      const aIndex = priority.findIndex((p) => a.toLowerCase().includes(p.toLowerCase()))
      const bIndex = priority.findIndex((p) => b.toLowerCase().includes(p.toLowerCase()))

      if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex
      if (aIndex !== -1) return -1
      if (bIndex !== -1) return 1
      return a.localeCompare(b)
    })
  }, [groupedFlavours])

  const toggleCategory = (category: string) => {
    const newExpanded = new Set(expandedCategories)
    if (newExpanded.has(category)) {
      newExpanded.delete(category)
    } else {
      newExpanded.add(category)
    }
    setExpandedCategories(newExpanded)
  }

  const handleReinstall = async () => {
    if (!selectedFlavour) return

    try {
      const result = await reinstallMutation.mutateAsync({
        serverId,
        imageFlavour: selectedFlavour.id,
      })
      setConfirmDialogOpen(false)
      onOpenChange(false)

      // Notify parent about the reinstall task so it can poll for status
      if (result?.taskId && onReinstallStarted) {
        onReinstallStarted(result.taskId)
      }
    } catch (err) {
      // Error handled by mutation
    }
  }

  const totalFlavours = flavoursData?.flavours?.length || 0
  const filteredCount = Object.values(groupedFlavours).reduce((sum, arr) => sum + arr.length, 0)

  return (
    <>
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <HardDrive className="h-5 w-5 text-muted-foreground" />
              Reinstall Operating System
            </DialogTitle>
            <DialogDescription>
              Select an operating system to install on {serverName || `server ${serverId}`}. This
              will <span className="text-destructive font-medium">erase all data</span> on the
              server.
            </DialogDescription>
          </DialogHeader>

          <div className="flex-1 min-h-0 space-y-4 mt-4">
            {/* Search */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search operating systems..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-9"
              />
            </div>

            {/* Image List */}
            {isLoading ? (
              <div className="flex flex-col items-center justify-center py-12 gap-3">
                <Loader2 className="h-8 w-8 animate-spin text-primary" />
                <p className="text-sm text-muted-foreground">Loading available images...</p>
              </div>
            ) : error ? (
              <div className="rounded-lg border border-destructive/20 bg-destructive/5 p-4 text-center">
                <p className="text-sm text-destructive">Failed to load available images</p>
                <Button variant="outline" size="sm" className="mt-2" onClick={() => refetch()}>
                  Retry
                </Button>
              </div>
            ) : totalFlavours === 0 ? (
              <div className="rounded-lg border border-dashed p-8 text-center">
                <HardDrive className="h-8 w-8 mx-auto text-muted-foreground/50 mb-2" />
                <p className="text-sm text-muted-foreground">No images available for this server</p>
              </div>
            ) : (
              <>
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>
                    {filteredCount === totalFlavours
                      ? `${totalFlavours} images available`
                      : `${filteredCount} of ${totalFlavours} images`}
                  </span>
                  {selectedFlavour && (
                    <Badge variant="secondary" className="gap-1">
                      <Check className="h-3 w-3" />
                      Selected: {selectedFlavour.name}
                    </Badge>
                  )}
                </div>

                <div className="h-[300px] rounded-lg border overflow-y-auto">
                  <div className="p-2 space-y-1">
                    {sortedCategories.map((category) => (
                      <div key={category}>
                        {/* Category Header */}
                        <button
                          onClick={() => toggleCategory(category)}
                          className="w-full flex items-center gap-2 px-3 py-2 rounded-md hover:bg-muted/50 transition-colors text-left"
                        >
                          {expandedCategories.has(category) ? (
                            <ChevronDown className="h-4 w-4 text-muted-foreground" />
                          ) : (
                            <ChevronRight className="h-4 w-4 text-muted-foreground" />
                          )}
                          <span className="font-medium">{category}</span>
                          <Badge variant="outline" className="ml-auto text-xs">
                            {groupedFlavours[category].length}
                          </Badge>
                        </button>

                        {/* Category Items */}
                        {expandedCategories.has(category) && (
                          <div className="ml-6 space-y-1 mt-1 mb-2">
                            {groupedFlavours[category].map((flavour) => (
                              <button
                                key={flavour.id}
                                onClick={() => setSelectedFlavour(flavour)}
                                className={`w-full flex items-start gap-3 p-3 rounded-md text-left transition-colors ${
                                  selectedFlavour?.id === flavour.id
                                    ? 'bg-primary/10 border border-primary/30'
                                    : 'hover:bg-muted/50 border border-transparent'
                                }`}
                              >
                                <div
                                  className={`mt-0.5 h-4 w-4 rounded-full border-2 flex items-center justify-center ${
                                    selectedFlavour?.id === flavour.id
                                      ? 'border-primary bg-primary'
                                      : 'border-muted-foreground/30'
                                  }`}
                                >
                                  {selectedFlavour?.id === flavour.id && (
                                    <Check className="h-2.5 w-2.5 text-primary-foreground" />
                                  )}
                                </div>
                                <div className="flex-1 min-w-0">
                                  <p className="font-medium text-sm">{flavour.name}</p>
                                  {flavour.description && (
                                    <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
                                      {flavour.description}
                                    </p>
                                  )}
                                </div>
                              </button>
                            ))}
                          </div>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              </>
            )}
          </div>

          <DialogFooter className="gap-2 sm:gap-0 mt-6">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={reinstallMutation.isPending}
            >
              Cancel
            </Button>
            <Button
              type="button"
              variant="destructive"
              disabled={!selectedFlavour || reinstallMutation.isPending}
              onClick={() => setConfirmDialogOpen(true)}
            >
              <HardDrive className="mr-2 h-4 w-4" />
              Reinstall Server
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Confirmation Dialog */}
      <SliderConfirmDialog
        open={confirmDialogOpen}
        onOpenChange={setConfirmDialogOpen}
        title="Confirm Server Reinstall"
        description={
          <>
            <div className="flex items-start gap-3 p-3 rounded-lg bg-destructive/10 border border-destructive/20 mb-4">
              <AlertTriangle className="h-5 w-5 text-destructive mt-0.5" />
              <div className="text-sm">
                <p className="font-medium text-destructive">This action cannot be undone!</p>
                <p className="text-muted-foreground mt-1">
                  All data on the server will be permanently erased and the operating system will be
                  reinstalled.
                </p>
              </div>
            </div>
            <div className="space-y-2 text-sm">
              <p>
                <span className="text-muted-foreground">Server:</span>{' '}
                <span className="font-medium">{serverName || serverId}</span>
              </p>
              <p>
                <span className="text-muted-foreground">New OS:</span>{' '}
                <span className="font-medium">{selectedFlavour?.name}</span>
              </p>
            </div>
          </>
        }
        confirmText="Reinstall"
        variant="destructive"
        onConfirm={handleReinstall}
        isLoading={reinstallMutation.isPending}
      />
    </>
  )
}
