"use client";

/**
 * Task Toast — slides in from the right when a background task completes
 * or fails. Auto-dismisses after 10s. Stacks vertically (max 3).
 */

import { useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { CheckCircle2, XCircle, X, ArrowRight, RefreshCw } from "lucide-react";
import { useBackgroundTasks, type BackgroundTask } from "@/lib/stores/task-store";
import { useBrand } from "@/context/brand-context";

function formatLabel(label: string): string {
  return label.replace(/^Running\s+/i, "").replace(/\.{2,}$/, "").trim();
}

function Toast({ task, onDismiss }: { task: BackgroundTask; onDismiss: () => void }) {
  const router = useRouter();
  const { brand: currentBrand, brands, setBrand } = useBrand();
  const timerRef = useRef<ReturnType<typeof setTimeout>>();

  useEffect(() => {
    timerRef.current = setTimeout(onDismiss, 10000);
    return () => clearTimeout(timerRef.current);
  }, [onDismiss]);

  const isSuccess = task.status === "completed";
  const taskBrand = brands.find((b) => b.id === task.brandId);
  const isOtherBrand = taskBrand && taskBrand.id !== currentBrand?.id;

  function viewResults() {
    if (taskBrand && isOtherBrand) {
      // Switch to the brand the task was started for, then navigate.
      // Brand context updates synchronously via setBrand; the
      // destination page reads brand context on mount.
      setBrand(taskBrand);
    }
    if (task.resultUrl) router.push(task.resultUrl);
    onDismiss();
  }

  return (
    <div className="animate-[slideInRight_0.3s_ease-out] bg-white rounded-xl shadow-elevated border border-slate-200 p-4 max-w-sm w-full">
      <div className="flex items-start gap-3">
        {isSuccess
          ? <CheckCircle2 className="h-5 w-5 text-green-500 mt-0.5 shrink-0" />
          : <XCircle className="h-5 w-5 text-red-500 mt-0.5 shrink-0" />
        }
        <div className="flex-1 min-w-0">
          <p className="font-semibold text-sm text-slate-900">
            {formatLabel(task.label)} {isSuccess ? "Complete" : "Failed"}
          </p>
          <p className="text-xs text-slate-500 mt-0.5 line-clamp-2">
            {isSuccess ? task.resultSummary : task.error}
          </p>
          {taskBrand && (
            <p className="text-[10px] text-slate-500 mt-0.5">
              {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>
          )}
          {isSuccess && task.resultUrl ? (
            <button
              onClick={viewResults}
              className="mt-2 flex items-center gap-1 text-xs font-semibold text-brand-600 hover:text-brand-700"
              title={isOtherBrand ? `Switch to ${taskBrand?.name} and view results` : "View results"}
            >
              View Results <ArrowRight className="w-3 h-3" />
            </button>
          ) : task.status === "failed" ? (
            <button
              onClick={onDismiss}
              className="mt-2 flex items-center gap-1 text-xs font-semibold text-red-600 hover:text-red-700"
            >
              <RefreshCw className="w-3 h-3" /> Dismiss
            </button>
          ) : null}
        </div>
        <button onClick={onDismiss} className="text-slate-400 hover:text-slate-600 shrink-0">
          <X className="h-4 w-4" />
        </button>
      </div>
    </div>
  );
}

export default function TaskToastContainer() {
  const { completedTasks, failedTasks, dismissTask } = useBackgroundTasks();

  // Show at most 3 toasts (newest first)
  const visible = [...completedTasks, ...failedTasks]
    .sort((a, b) => (b.completedAt?.getTime() || 0) - (a.completedAt?.getTime() || 0))
    .slice(0, 3);

  if (visible.length === 0) return null;

  return (
    <div className="fixed top-4 right-4 z-50 flex flex-col gap-2.5">
      {visible.map((task) => (
        <Toast key={task.id} task={task} onDismiss={() => dismissTask(task.id)} />
      ))}
    </div>
  );
}
