"use client";

import Link from "next/link";
import type { Route } from "next";
import { trpc } from "~/lib/trpc/client.js";
import type { WidgetProps } from "~/components/dashboard/widget-registry.js";
import { TaskCard } from "~/components/notifications/TaskCard.js";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function TaskWidget(_props: Partial<WidgetProps> = {}) {
  const utils = trpc.useUtils();

  const { data: tasks, isLoading: loadingTasks } = trpc.notification.listTasks.useQuery(
    { status: "OPEN", limit: 5 },
    { staleTime: 30_000, placeholderData: (prev) => prev },
  );

  const { data: taskCounts, isLoading: loadingCounts } = trpc.notification.taskCounts.useQuery(undefined, {
    staleTime: 30_000,
    placeholderData: (prev) => prev,
  });

  const updateTaskStatus = trpc.notification.updateTaskStatus.useMutation({
    onSuccess: () => {
      void utils.notification.taskCounts.invalidate();
      void utils.notification.listTasks.invalidate();
      void utils.notification.list.invalidate();
      void utils.notification.unreadCount.invalidate();
    },
  });

  function handleStatusChange(id: string, status: string) {
    updateTaskStatus.mutate({ id, status: status as "OPEN" | "IN_PROGRESS" | "DONE" | "DISMISSED" });
  }

  const openCount = (taskCounts?.open ?? 0) + (taskCounts?.inProgress ?? 0);
  const isLoading = loadingTasks || loadingCounts;

  if (isLoading) {
    return (
      <div className="flex h-full flex-col">
        <div className="flex items-center justify-between px-1 pb-3">
          <div className="h-5 w-32 shimmer-skeleton rounded" />
        </div>
        <div className="flex-1 space-y-2">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="rounded-xl border border-gray-200 dark:border-gray-700 p-3">
              <div className="h-4 w-3/4 shimmer-skeleton rounded" />
              <div className="mt-2 h-3 w-1/2 bg-gray-100 dark:bg-gray-800 rounded" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="flex h-full flex-col">
      {/* Header */}
      <div className="flex items-center justify-between px-1 pb-3">
        <h3 className="text-sm font-semibold text-gray-900 dark:text-gray-50">
          Open Tasks
          {openCount > 0 && (
            <span className="ml-2 inline-flex items-center justify-center min-w-[18px] h-5 px-1.5 text-[10px] font-bold text-white bg-orange-500 rounded-full">
              {openCount}
            </span>
          )}
        </h3>
        {taskCounts?.overdue !== undefined && taskCounts.overdue > 0 && (
          <span className="text-xs font-semibold text-red-600 dark:text-red-400">
            {taskCounts.overdue} overdue
          </span>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 space-y-2 overflow-y-auto">
        {!tasks || tasks.length === 0 ? (
          <div className="flex h-full items-center justify-center rounded-xl border border-dashed border-gray-300 dark:border-gray-600 py-8 text-sm text-gray-400 dark:text-gray-500">
            No open tasks
          </div>
        ) : (
          tasks.map((t) => (
            <TaskCard
              key={t.id}
              task={{
                id: t.id,
                title: t.title,
                body: t.body,
                priority: t.priority ?? "NORMAL",
                taskStatus: t.taskStatus,
                taskAction: t.taskAction,
                dueDate: t.dueDate,
                entityType: t.entityType,
                link: t.link,
                createdAt: t.createdAt,
                completedBy: t.completedBy,
              }}
              onStatusChange={handleStatusChange}
              compact
            />
          ))
        )}
      </div>

      {/* Footer */}
      <div className="pt-2 border-t border-gray-100 dark:border-gray-800 mt-2">
        <Link
          href={"/notifications?tab=tasks" as Route}
          className="block text-center text-xs font-medium text-brand-600 dark:text-brand-400 hover:underline"
        >
          View all &rarr;
        </Link>
      </div>
    </div>
  );
}
