"use client"

import { Button } from "@/components/ui/button"
import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerTrigger } from "@/components/ui/drawer"
import { Spinner } from "@/components/ui/spinner"
import { useTaskManager, useTasks, useTaskPanelOpen } from "@/contexts/task-context"
import { RiCheckLine } from "@remixicon/react"
import * as React from "react"
import { useTranslation } from "react-i18next"
import { TaskPanel } from "./panel"

export function TaskStatsButton() {
  const { t } = useTranslation()
  const tasks = useTasks()
  const taskManager = useTaskManager()
  const { isTaskPanelOpen, setTaskPanelOpen } = useTaskPanelOpen()

  const pending = tasks.filter((task) => task.status === "pending")
  const processing = tasks.filter((task) => task.status === "running")
  const completed = tasks.filter((task) => task.status === "completed")
  const failed = tasks.filter((task) => task.status === "failed")
  const active = pending.length + processing.length
  const total = tasks.length

  if (total === 0) return null

  return (
    <Drawer open={isTaskPanelOpen} onOpenChange={setTaskPanelOpen} swipeDirection="right">
      <DrawerTrigger render={<Button variant="outline" />}>
        {active > 0 ? (
          <div className="flex items-center gap-2">
            <Spinner className="size-3 text-muted-foreground" />
            <span>
              {t("In Progress", {
                total,
                processing: processing.length,
                completed: completed.length,
              })}
            </span>
          </div>
        ) : (
          <div className="flex items-center gap-2">
            <RiCheckLine className="size-4 text-primary" aria-hidden />
            <span>{t("Task Completed", { completed: completed.length, failed: failed.length })}</span>
          </div>
        )}
      </DrawerTrigger>
      <DrawerContent className="sm:max-w-sm">
        <DrawerHeader>
          <DrawerTitle>{t("Task Management")}</DrawerTitle>
        </DrawerHeader>
        <div className="overflow-auto p-4">
          <TaskPanel tasks={tasks} onClearFinishedTasks={() => taskManager.clearFinishedTasks()} />
        </div>
      </DrawerContent>
    </Drawer>
  )
}
