"use client"

import { toastApiError } from "@/lib/toast-api-error";
import * as React from "react"
import { Eye, Loader2, Plus, RefreshCw, SearchCheck, Trash2, Upload } from "lucide-react"
import Link from "next/link"
import { toast } from "sonner"

import { FormPageHeader } from "@/app/dashboard/_components/form"
import {
  deleteDeepdexUploadQueueItem,
  fetchDeepdexUploadQueue,
  getDeepdexUploadQueueReviewUrl,
  getDeepdexUploadQueueViewUrl,
  publishDeepdexUploadQueueItem,
} from "@/components/deepdex/api/deepdex.api"
import { DeepdexUploadForm } from "@/components/deepdex/create/deepdex-upload-form"
import { getDeepdexDocTypeLabel } from "@/components/deepdex/data/deepdex-doc-types"
import type { DeepdexUploadQueueItem } from "@/components/deepdex/types"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
  SheetTrigger,
} from "@/components/ui/sheet"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"

function statusBadgeVariant(status: string): "default" | "secondary" | "destructive" | "outline" {
  if (status === "failed") return "destructive"
  if (status === "pending_review") return "default"
  if (status === "completed") return "secondary"
  return "outline"
}

export function DeepdexUploadQueuePage() {
  const [items, setItems] = React.useState<DeepdexUploadQueueItem[]>([])
  const [module, setModule] = React.useState<"deepdex" | "structure" | "accumulator">("deepdex")
  const [isLoading, setIsLoading] = React.useState(true)
  const [isRefreshing, setIsRefreshing] = React.useState(false)
  const [busyId, setBusyId] = React.useState<string | null>(null)
  const [isUploadOpen, setIsUploadOpen] = React.useState(false)

  const load = React.useCallback(async (activeModule: "deepdex" | "structure" | "accumulator") => {
    try {
      const data = await fetchDeepdexUploadQueue({
        page: 1,
        pageSize: 50,
        filters: { module: activeModule },
      })
      setItems(data.items)
    } catch (error) {
      const message = error instanceof Error ? error.message : "Failed to load upload queue"
      toast.error(message)
    }
  }, [])

  React.useEffect(() => {
    void (async () => {
      setIsLoading(true)
      await load(module)
      setIsLoading(false)
    })()
  }, [load, module])

  const refresh = React.useCallback(async () => {
    setIsRefreshing(true)
    await load(module)
    setIsRefreshing(false)
  }, [load, module])

  const handleDelete = async (id: string) => {
    setBusyId(id)
    try {
      await deleteDeepdexUploadQueueItem(id)
      toast.success("Queue item deleted")
      await load(module)
    } catch (error) {
      toastApiError(error, "Delete failed")
    } finally {
      setBusyId(null)
    }
  }

  const handlePublish = async (id: string) => {
    setBusyId(id)
    try {
      const message = await publishDeepdexUploadQueueItem(id)
      toast.success(message)
      await load(module)
    } catch (error) {
      toastApiError(error, "Publish failed")
    } finally {
      setBusyId(null)
    }
  }

  return (
    <div className="flex flex-col">
      <FormPageHeader
        backHref="/dashboard/deepdex/view-all"
        parentLabel="Deepdex"
        currentLabel="Upload queue"
        titleIcon={<Upload className="size-4 text-primary" />}
        title="Upload queue"
        description="Upload files, review queue status, then publish processed items to Deepdex."
      />
      <Card className="mt-6">
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle>Queue items</CardTitle>
          <div className="flex items-center gap-2">
            <Sheet open={isUploadOpen} onOpenChange={setIsUploadOpen}>
              <SheetTrigger asChild>
                <Button size="sm">
                  <Plus className="size-4" />
                  Add files
                </Button>
              </SheetTrigger>
              <SheetContent
                side="right"
                className="h-screen w-1/2 overflow-y-auto max-w-none border-0 data-[side=right]:w-1/2 data-[side=right]:sm:max-w-none"
              >
                <SheetHeader>
                  <SheetTitle>Upload files</SheetTitle>
                  <SheetDescription>Add files to the processing queue.</SheetDescription>
                </SheetHeader>
                <div className="p-4">
                  <DeepdexUploadForm
                    module={module}
                    onUploaded={() => {
                      setIsUploadOpen(false)
                      void refresh()
                    }}
                  />
                </div>
              </SheetContent>
            </Sheet>
            <Button variant="outline" size="sm" onClick={() => void refresh()} disabled={isRefreshing}>
              {isRefreshing ? <Loader2 className="size-4 animate-spin" /> : <RefreshCw className="size-4" />}
              Refresh
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-4 p-0">
          <div className="px-4 pt-4">
            <Tabs value={module} onValueChange={(value) => setModule(value as typeof module)}>
              <TabsList>
                <TabsTrigger value="deepdex">Deepdex</TabsTrigger>
                <TabsTrigger value="structure">Structure</TabsTrigger>
                <TabsTrigger value="accumulator">Accumulator</TabsTrigger>
              </TabsList>
            </Tabs>
          </div>
          {isLoading ? (
            <div className="p-4 text-sm text-muted-foreground">Loading queue…</div>
          ) : items.length === 0 ? (
            <div className="p-4 text-sm text-muted-foreground">Queue is empty.</div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>ID</TableHead>
                  <TableHead>File name</TableHead>
                  <TableHead>Module</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Doc type</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((item) => (
                  <TableRow key={item.id}>
                    <TableCell>{item.id}</TableCell>
                    <TableCell className="max-w-[18rem] truncate" title={item.originalName}>
                      {item.originalName}
                      {item.errorMessage ? (
                        <p className="mt-1 text-xs text-destructive">{item.errorMessage}</p>
                      ) : null}
                    </TableCell>
                    <TableCell className="capitalize">{item.moduleType}</TableCell>
                    <TableCell>
                      <Badge variant={statusBadgeVariant(item.status)}>{item.status}</Badge>
                    </TableCell>
                    <TableCell>{getDeepdexDocTypeLabel(item.docType)}</TableCell>
                    <TableCell>{item.createdAt || "—"}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button variant="outline" size="sm" asChild>
                          <Link href={getDeepdexUploadQueueViewUrl(item.viewToken)} target="_blank">
                            <Eye className="size-4" />
                          </Link>
                        </Button>
                        {(module === "structure" || module === "accumulator") ? (
                          <Button variant="outline" size="sm" asChild>
                            <Link
                              href={getDeepdexUploadQueueReviewUrl(module, item.id)}
                              target="_blank"
                            >
                              <SearchCheck className="size-4" />
                            </Link>
                          </Button>
                        ) : null}
                        <Button
                          variant="default"
                          size="sm"
                          onClick={() => void handlePublish(item.id)}
                          disabled={module !== "deepdex" || !item.canPublish || busyId === item.id}
                        >
                          {busyId === item.id ? <Loader2 className="size-4 animate-spin" /> : null}
                          Publish
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => void handleDelete(item.id)}
                          disabled={!item.canDelete || busyId === item.id}
                        >
                          <Trash2 className="size-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
