"use client"

import React, { useState, useEffect } from "react"
import { Search, Folder, Move } from "lucide-react"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { toast } from "@/hooks/use-toast"
import { DriveLsEntry } from "@/lib/drive_types"

interface DriveMoveDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  selectedCount: number
  onMove: (destinationPath: string) => void
}

export function DriveMoveDialog({ open, onOpenChange, selectedCount, onMove }: DriveMoveDialogProps) {
  const [directories, setDirectories] = useState<DriveLsEntry[]>([])
  const [filteredDirectories, setFilteredDirectories] = useState<DriveLsEntry[]>([])
  const [searchQuery, setSearchQuery] = useState("")
  const [selectedDirectory, setSelectedDirectory] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  // Load all directories when dialog opens
  useEffect(() => {
    if (open) {
      loadDirectories()
    }
  }, [open])

  // Filter directories based on search query
  useEffect(() => {
    if (!searchQuery.trim()) {
      setFilteredDirectories(directories)
    } else {
      const query = searchQuery.toLowerCase()
      const filtered = directories.filter(dir => 
        dir.path.toLowerCase().includes(query)
      )
      setFilteredDirectories(filtered)
    }
  }, [searchQuery, directories])

  const loadDirectories = async () => {
    setLoading(true)
    try {
      const response = await fetch('/api/directories')
      if (!response.ok) {
        throw new Error(`Failed to fetch directories: ${response.statusText}`)
      }
      const dirs = await response.json()
      setDirectories(dirs)
      setFilteredDirectories(dirs)
    } catch (error) {
      console.error('Error loading directories:', error)
      toast({
        title: "Failed to load directories",
        description: error instanceof Error ? error.message : 'Unknown error occurred',
        variant: "destructive"
      })
    } finally {
      setLoading(false)
    }
  }

  const handleMove = () => {
    if (selectedDirectory) {
      onMove(selectedDirectory)
      // Reset dialog state
      setSelectedDirectory(null)
      setSearchQuery("")
    }
  }

  const handleClose = () => {
    onOpenChange(false)
    // Reset dialog state
    setSelectedDirectory(null)
    setSearchQuery("")
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="max-w-md max-h-[80vh]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Move className="h-5 w-5" />
            Move {selectedCount} item{selectedCount !== 1 ? "s" : ""}
          </DialogTitle>
        </DialogHeader>

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

          {/* Directory List */}
          <ScrollArea className="h-[300px] border rounded-md">
            <div className="p-2">
              {loading ? (
                <div className="flex items-center justify-center py-8">
                  <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
                </div>
              ) : filteredDirectories.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  {searchQuery ? 'No directories found matching your search' : 'No directories available'}
                </div>
              ) : (
                <div className="space-y-1">
                  {filteredDirectories.map((directory) => (
                    <div
                      key={directory.path}
                      className={`flex items-center gap-2 p-2 rounded cursor-pointer transition-colors ${
                        selectedDirectory === directory.path
                          ? 'bg-blue-50 border border-blue-200'
                          : 'hover:bg-muted/50'
                      }`}
                      onClick={() => setSelectedDirectory(directory.path)}
                    >
                      <Folder className="h-4 w-4 text-blue-500 flex-shrink-0" />
                      <span className="text-sm font-mono break-all">
                        {directory.path}
                      </span>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </ScrollArea>

          {/* Selected Directory Display */}
          {selectedDirectory && (
            <div className="bg-blue-50 border border-blue-200 rounded-lg p-3">
              <div className="text-sm font-medium text-blue-900 mb-1">
                Moving to:
              </div>
              <div className="text-sm font-mono text-blue-700">
                {selectedDirectory}
              </div>
            </div>
          )}

          {/* Action Buttons */}
          <div className="flex justify-end gap-2">
            <Button variant="outline" onClick={handleClose}>
              Cancel
            </Button>
            <Button 
              onClick={handleMove} 
              disabled={!selectedDirectory || loading}
            >
              <Move className="mr-2 h-4 w-4" />
              Move Here
            </Button>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}