"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import type { Route } from "next";
import { Eraser, History } from "lucide-react";

import { EmptyState } from "@/components/shared/empty-state";
import { SimpleToastStack } from "@/components/shared/simple-toast-stack";
import { Button } from "@/components/ui/button";
import { useSimpleToast } from "@/hooks/use-simple-toast";
import {
  DASHBOARD_RECENT_UPDATED_EVENT,
  clearRecentTools,
  readRecentTools
} from "@/lib/client/dashboard-storage";

interface RecentToolsProps {
  items: {
    slug: string;
    title: string;
    usedAtLabel: string;
  }[];
}

export function RecentTools({ items }: RecentToolsProps) {
  const [recentItems, setRecentItems] = useState(() => readRecentTools(items, 6));
  const { toasts, pushToast, dismissToast } = useSimpleToast();

  const hasLocalHistory = useMemo(() => recentItems.length > 0, [recentItems.length]);

  useEffect(() => {
    const refreshRecentTools = () => {
      setRecentItems(readRecentTools(items, 6));
    };

    refreshRecentTools();
    window.addEventListener("storage", refreshRecentTools);
    window.addEventListener(DASHBOARD_RECENT_UPDATED_EVENT, refreshRecentTools);

    return () => {
      window.removeEventListener("storage", refreshRecentTools);
      window.removeEventListener(DASHBOARD_RECENT_UPDATED_EVENT, refreshRecentTools);
    };
  }, [items]);

  return (
    <section className="space-y-4">
      <div className="flex flex-wrap items-end justify-between gap-2">
        <div>
        <h2 className="font-[var(--font-space-grotesk)] text-xl font-semibold text-white sm:text-2xl">
          Recent Tools
        </h2>
          <p className="text-sm text-slate-400">Recently opened tools are stored locally for quick jump-back.</p>
        </div>
        <Button
          variant="ghost"
          size="sm"
          className="text-slate-300 hover:text-white"
          disabled={!hasLocalHistory}
          onClick={() => {
            clearRecentTools();
            setRecentItems(readRecentTools(items, 6));
            pushToast({
              title: "Recent tools cleared",
              description: "Dashboard history reset for this browser.",
              variant: "info"
            });
          }}
        >
          <Eraser data-icon="inline-start" />
          Clear History
        </Button>
      </div>
      {recentItems.length === 0 ? (
        <EmptyState
          title="No Recent Tools Yet"
          description="Launch a tool from the suite and it will appear here."
          icon={History}
        />
      ) : (
        <div className="glass-panel rounded-2xl border border-white/10">
          <ul className="divide-y divide-white/10">
            {recentItems.map((item) => (
              <li key={`${item.slug}-${item.usedAtLabel}`} className="flex flex-wrap items-center justify-between gap-3 p-4">
                <div className="flex items-center gap-3">
                  <span className="inline-flex size-8 items-center justify-center rounded-lg bg-white/5 text-slate-300">
                    <History className="size-4" />
                  </span>
                  <div>
                    <p className="text-sm font-medium text-slate-100">{item.title}</p>
                    <p className="text-xs text-slate-400">{item.usedAtLabel}</p>
                  </div>
                </div>
                <Button
                  size="sm"
                  variant="ghost"
                  className="text-sky-200 hover:text-white focus-visible:ring-sky-300/60"
                  render={<Link href={`/tools/${item.slug}` as Route}>Re-open</Link>}
                />
              </li>
            ))}
          </ul>
        </div>
      )}
      <SimpleToastStack toasts={toasts} onDismiss={dismissToast} />
    </section>
  );
}
