import { useState, useRef } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
  storageFolderTreeOptions, storageFolderDetailOptions, storageFolderMutations, storageFolderKeys,
  storageFileListOptions, storageFileMutations, storageFileKeys,
} from '@/api/storage'
import { usePagination } from '@/hooks/use-pagination'
import { FolderTree } from '@/components/storage/folder-tree'
import { FileIcon, formatFileSize } from '@/components/storage/file-icons'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { FolderPlus, Upload, Folder, ChevronRight, MoreVertical, Trash2, Download, Shield } from 'lucide-react'
import { toast } from 'sonner'
import { useAuthStore } from '@/stores/auth.store'
import { FolderPermissionsDialog } from '@/components/storage/folder-permissions-dialog'
import type { StorageFile } from '@/types/storage'

export const Route = createFileRoute('/_authenticated/files/')({
  validateSearch: (search: Record<string, unknown>) => ({
    page: Number(search.page) || 1,
    limit: Number(search.limit) || 50,
    q: (search.q as string) || undefined,
    sort: (search.sort as string) || undefined,
    order: (search.order as 'asc' | 'desc') || 'asc',
  }),
  component: FileManagerPage,
})

function FileManagerPage() {
  const queryClient = useQueryClient()
  const token = useAuthStore((s) => s.token)
  const [selectedFolderId, setSelectedFolderId] = useState<string | null>(null)
  const [newFolderOpen, setNewFolderOpen] = useState(false)
  const [newFolderName, setNewFolderName] = useState('')
  const [permissionsOpen, setPermissionsOpen] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const { params } = usePagination()

  const { data: treeData, isLoading: treeLoading } = useQuery(storageFolderTreeOptions())
  const { data: folderDetail } = useQuery(storageFolderDetailOptions(selectedFolderId ?? ''))
  const { data: filesData, isLoading: filesLoading } = useQuery(
    storageFileListOptions(selectedFolderId ?? '', { ...params, limit: 50 }),
  )
  const { data: subFoldersData } = useQuery({
    queryKey: storageFolderKeys.children(selectedFolderId),
    queryFn: () => {
      const allFolders = treeData?.data ?? []
      return { data: allFolders.filter((f) => f.parentId === selectedFolderId) }
    },
    enabled: !!treeData,
  })

  const createFolderMutation = useMutation({
    mutationFn: storageFolderMutations.create,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: storageFolderKeys.all })
      toast.success('Folder created')
      setNewFolderOpen(false)
      setNewFolderName('')
    },
    onError: (err) => toast.error(err.message),
  })

  const deleteFileMutation = useMutation({
    mutationFn: storageFileMutations.delete,
    onSuccess: () => {
      if (selectedFolderId) queryClient.invalidateQueries({ queryKey: storageFileKeys.all(selectedFolderId) })
      toast.success('File deleted')
    },
    onError: (err) => toast.error(err.message),
  })

  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    if (!selectedFolderId || !e.target.files?.length) return
    const files = Array.from(e.target.files)

    for (const file of files) {
      const formData = new FormData()
      formData.append('file', file)
      try {
        const res = await fetch(`/v1/storage/folders/${selectedFolderId}/files`, {
          method: 'POST',
          headers: { Authorization: `Bearer ${token}` },
          body: formData,
        })
        if (!res.ok) {
          const err = await res.json().catch(() => ({}))
          toast.error(`Upload failed: ${(err as any).error?.message ?? file.name}`)
        }
      } catch {
        toast.error(`Upload failed: ${file.name}`)
      }
    }

    queryClient.invalidateQueries({ queryKey: storageFileKeys.all(selectedFolderId) })
    toast.success(`${files.length} file(s) uploaded`)
    e.target.value = ''
  }

  async function handleDownload(file: StorageFile) {
    try {
      const { url } = await storageFileMutations.getSignedUrl(file.id)
      window.open(url, '_blank')
    } catch {
      toast.error('Download failed')
    }
  }

  function handleCreateFolder(e: React.FormEvent) {
    e.preventDefault()
    if (!newFolderName.trim()) return
    createFolderMutation.mutate({ name: newFolderName.trim(), parentId: selectedFolderId ?? undefined })
  }

  const folders = treeData?.data ?? []
  const files = filesData?.data ?? []
  const subFolders = subFoldersData?.data ?? []
  const breadcrumbs = folderDetail?.breadcrumbs ?? []

  return (
    <div className="flex gap-0 h-[calc(100vh-6rem)]">
      {/* Left Panel — Folder Tree */}
      <div className="w-60 shrink-0 border-r overflow-y-auto p-3">
        <div className="flex items-center justify-between mb-3">
          <h2 className="text-sm font-semibold">Folders</h2>
          <Dialog open={newFolderOpen} onOpenChange={setNewFolderOpen}>
            <DialogTrigger asChild>
              <Button variant="ghost" size="sm" className="h-7 w-7 p-0">
                <FolderPlus className="h-4 w-4" />
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>New Folder</DialogTitle></DialogHeader>
              <form onSubmit={handleCreateFolder} className="space-y-4">
                <div className="space-y-2">
                  <Label>Folder Name</Label>
                  <Input value={newFolderName} onChange={(e) => setNewFolderName(e.target.value)} placeholder="e.g. HR Documents" autoFocus />
                </div>
                {selectedFolderId && (
                  <p className="text-xs text-muted-foreground">
                    Creating inside: {breadcrumbs.map((b) => b.name).join(' / ') || 'Root'}
                  </p>
                )}
                <Button type="submit" disabled={createFolderMutation.isPending || !newFolderName.trim()}>
                  {createFolderMutation.isPending ? 'Creating...' : 'Create Folder'}
                </Button>
              </form>
            </DialogContent>
          </Dialog>
        </div>

        {treeLoading ? (
          <div className="space-y-2">{Array.from({ length: 5 }).map((_, i) => <Skeleton key={i} className="h-7 w-full" />)}</div>
        ) : (
          <FolderTree folders={folders} selectedFolderId={selectedFolderId} onSelect={setSelectedFolderId} />
        )}
      </div>

      {/* Right Panel — Files */}
      <div className="flex-1 overflow-y-auto">
        {/* Toolbar */}
        <div className="flex items-center gap-2 p-3 border-b">
          {/* Breadcrumbs */}
          <div className="flex items-center gap-1 text-sm flex-1 min-w-0">
            <button type="button" onClick={() => setSelectedFolderId(null)} className="text-muted-foreground hover:text-foreground">
              Files
            </button>
            {breadcrumbs.map((crumb) => (
              <span key={crumb.id} className="flex items-center gap-1">
                <ChevronRight className="h-3 w-3 text-muted-foreground" />
                <button type="button" onClick={() => setSelectedFolderId(crumb.id)} className="text-muted-foreground hover:text-foreground truncate max-w-[120px]">
                  {crumb.name}
                </button>
              </span>
            ))}
          </div>

          {selectedFolderId && (
            <>
              {folderDetail?.accessLevel === 'admin' && (
                <Button variant="outline" size="sm" onClick={() => setPermissionsOpen(true)}>
                  <Shield className="mr-2 h-4 w-4" />Permissions
                </Button>
              )}
              <Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
                <Upload className="mr-2 h-4 w-4" />Upload
              </Button>
              <input ref={fileInputRef} type="file" multiple className="hidden" onChange={handleFileUpload} />
            </>
          )}
        </div>

        {/* Content */}
        <div className="p-4">
          {!selectedFolderId ? (
            <div className="text-center py-12 text-muted-foreground">
              <Folder className="h-12 w-12 mx-auto mb-3 opacity-30" />
              <p>Select a folder to view files</p>
              <p className="text-xs mt-1">Or create a new folder to get started</p>
            </div>
          ) : filesLoading ? (
            <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
              {Array.from({ length: 8 }).map((_, i) => <Skeleton key={i} className="h-28 w-full rounded-lg" />)}
            </div>
          ) : (
            <>
              {/* Sub-folders */}
              {subFolders.length > 0 && (
                <div className="mb-4">
                  <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Folders</p>
                  <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                    {subFolders.map((folder) => (
                      <button
                        key={folder.id}
                        type="button"
                        onClick={() => setSelectedFolderId(folder.id)}
                        className="flex flex-col items-center gap-1.5 p-3 rounded-lg border hover:bg-accent transition-colors group"
                      >
                        <Folder className="h-8 w-8 text-amber-500" />
                        <span className="text-xs font-medium text-center truncate w-full">{folder.name}</span>
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Files */}
              {files.length > 0 && (
                <div>
                  {subFolders.length > 0 && <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Files</p>}
                  <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3">
                    {files.map((file) => (
                      <div
                        key={file.id}
                        className="flex flex-col items-center gap-1.5 p-3 rounded-lg border hover:bg-accent transition-colors group relative"
                      >
                        <button type="button" onClick={() => handleDownload(file)} className="flex flex-col items-center gap-1.5 w-full">
                          <FileIcon contentType={file.contentType} />
                          <span className="text-xs font-medium text-center truncate w-full">{file.filename}</span>
                          <span className="text-[10px] text-muted-foreground">{formatFileSize(file.sizeBytes)}</span>
                        </button>

                        <DropdownMenu>
                          <DropdownMenuTrigger asChild>
                            <button className="absolute top-1 right-1 h-6 w-6 rounded-md flex items-center justify-center opacity-0 group-hover:opacity-100 hover:bg-muted transition-opacity">
                              <MoreVertical className="h-3 w-3" />
                            </button>
                          </DropdownMenuTrigger>
                          <DropdownMenuContent align="end">
                            <DropdownMenuItem onClick={() => handleDownload(file)}>
                              <Download className="mr-2 h-4 w-4" />Download
                            </DropdownMenuItem>
                            <DropdownMenuItem className="text-destructive" onClick={() => deleteFileMutation.mutate(file.id)}>
                              <Trash2 className="mr-2 h-4 w-4" />Delete
                            </DropdownMenuItem>
                          </DropdownMenuContent>
                        </DropdownMenu>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {files.length === 0 && subFolders.length === 0 && (
                <div className="text-center py-12 text-muted-foreground">
                  <Upload className="h-10 w-10 mx-auto mb-3 opacity-30" />
                  <p>This folder is empty</p>
                  <p className="text-xs mt-1">Upload files or create sub-folders</p>
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {selectedFolderId && folderDetail && (
        <FolderPermissionsDialog
          folderId={selectedFolderId}
          folderName={folderDetail.name ?? ''}
          isPublic={folderDetail.isPublic ?? true}
          open={permissionsOpen}
          onOpenChange={setPermissionsOpen}
        />
      )}
    </div>
  )
}
