"use client";

/**
 * Task History Dropdown — shows in the header next to the notification bell.
 * Badge shows running task count. Dropdown shows running, completed, failed tasks.
 *
 * Cross-brand handoff: clicking "View" on a completed task switches the
 * active brand (if needed) BEFORE navigating to the result URL. Tasks
 * persist in a global store keyed by brandId so a user can start an
 * audit on Modern Heart, switch to Life Imaging mid-flight, and click
 * the completion notification to land back on the correct brand's
 * audit results.
 */

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Layers, Loader2, CheckCircle2, XCircle, ArrowRight, Trash2 } from "lucide-react";
import { useBackgroundTasks } from "@/lib/stores/task-store";
import { useBrand } from "@/context/brand-context";

function timeAgo(date: Date): string {
  const s = Math.floor((Date.now() - date.getTime()) / 1000);
  if (s < 60) return "Just now";
  if (s < 3600) return `${Math.floor(s / 60)}m ago`;
  if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
  return `${Math.floor(s / 86400)}d ago`;
}

export function TaskHistoryDropdown() {
  const { runningTasks, recentTasks, dismissTask, clearHistory } = useBackgroundTasks();
  const { brand: currentBrand, brands, setBrand } = useBrand();
  const [open, setOpen] = useState(false);
  const router = useRouter();
  const totalRunning = runningTasks.length;
  const hasItems = totalRunning > 0 || recentTasks.length > 0;

  // Map a task's brandId to a Brand object so the row can render the
  // brand name and the click handler can call setBrand() with a real
  // Brand record rather than just an id.
  const brandById = new Map(brands.map((b) => [b.id, b]));

  function viewTask(taskBrandId: string, resultUrl: string) {
    if (taskBrandId !== currentBrand?.id) {
      const target = brandById.get(taskBrandId);
      if (target) {
        // setBrand updates context + persists to localStorage. The
        // brand-context provider re-fetches the site/integrations
        // for the new brand asynchronously — we don't need to await
        // because the destination page will read brand context on
        // mount and re-render once it resolves.
        setBrand(target);
      }
    }
    router.push(resultUrl);
    setOpen(false);
  }

  return (
    <div className="relative">
      <button
        onClick={() => setOpen(!open)}
        className="relative p-2 rounded-lg hover:bg-slate-100 transition-colors"
      >
        <Layers className="w-5 h-5 text-slate-500" />
        {totalRunning > 0 && (
          <span className="absolute top-1 right-1 w-4 h-4 rounded-full bg-brand-500 text-white text-[9px] font-bold flex items-center justify-center">
            {totalRunning}
          </span>
        )}
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
          <div className="absolute top-full right-0 mt-1.5 bg-white border border-slate-200 rounded-xl shadow-lg z-50 w-80 overflow-hidden">
            <div className="flex items-center justify-between px-4 py-3 border-b border-slate-100">
              <h3 className="text-sm font-bold text-slate-900">Background Tasks</h3>
              {recentTasks.length > 0 && (
                <button onClick={clearHistory} className="text-[10px] text-slate-400 hover:text-slate-600 flex items-center gap-1">
                  <Trash2 className="w-3 h-3" /> Clear
                </button>
              )}
            </div>

            <div className="max-h-80 overflow-y-auto">
              {!hasItems ? (
                <div className="px-4 py-8 text-center">
                  <Layers className="w-8 h-8 text-slate-200 mx-auto mb-2" />
                  <p className="text-xs text-slate-400">No background tasks</p>
                </div>
              ) : (
                <div className="py-1">
                  {/* Running tasks */}
                  {runningTasks.map((t) => {
                    const taskBrand = brandById.get(t.brandId);
                    return (
                      <div key={t.id} className="px-4 py-2.5 hover:bg-slate-50 flex items-start gap-2.5">
                        <Loader2 className="w-4 h-4 animate-spin text-brand-500 mt-0.5 shrink-0" />
                        <div className="flex-1 min-w-0">
                          <p className="text-xs font-semibold text-slate-800 truncate">{t.label}</p>
                          <p className="text-[10px] text-slate-400">
                            {taskBrand ? <span className="font-medium text-slate-500">{taskBrand.name}</span> : null}
                            {taskBrand && " · "}
                            {timeAgo(t.startedAt)}
                          </p>
                        </div>
                      </div>
                    );
                  })}

                  {/* Recent completed/failed */}
                  {recentTasks.map((t) => {
                    const taskBrand = brandById.get(t.brandId);
                    const isOtherBrand = taskBrand && taskBrand.id !== currentBrand?.id;
                    return (
                    <div key={t.id} className="px-4 py-2.5 hover:bg-slate-50 flex items-start gap-2.5 group">
                      {t.status === "completed"
                        ? <CheckCircle2 className="w-4 h-4 text-green-500 mt-0.5 shrink-0" />
                        : <XCircle className="w-4 h-4 text-red-400 mt-0.5 shrink-0" />
                      }
                      <div className="flex-1 min-w-0">
                        <p className="text-xs font-semibold text-slate-800 truncate">
                          {t.label.replace(/^Running\s+/i, "").replace(/\.{2,}$/, "")}
                        </p>
                        {taskBrand && (
                          <p className="text-[10px] text-slate-500">
                            {taskBrand.name}
                            {isOtherBrand && <span className="ml-1 text-[9px] font-semibold text-amber-600 bg-amber-50 border border-amber-200 rounded px-1 py-0.5">switch</span>}
                          </p>
                        )}
                        <p className="text-[10px] text-slate-500 truncate">
                          {t.status === "completed" ? t.resultSummary : t.error}
                        </p>
                        <div className="flex items-center gap-2 mt-1">
                          {t.resultUrl && t.status === "completed" && (
                            <button
                              onClick={() => viewTask(t.brandId, t.resultUrl!)}
                              className="text-[10px] font-semibold text-brand-600 hover:text-brand-700 flex items-center gap-0.5"
                              title={isOtherBrand ? `Switch to ${taskBrand?.name} and view results` : "View results"}
                            >
                              View <ArrowRight className="w-2.5 h-2.5" />
                            </button>
                          )}
                          <button
                            onClick={() => dismissTask(t.id)}
                            className="text-[10px] text-slate-400 hover:text-slate-600 opacity-0 group-hover:opacity-100"
                          >
                            Dismiss
                          </button>
                        </div>
                      </div>
                      <span className="text-[10px] text-slate-300 shrink-0">{timeAgo(t.completedAt || t.startedAt)}</span>
                    </div>
                    );
                  })}
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
