"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { FetchError, apiGet, type PublicTemplate } from "@/lib/client-api";

export function FavoritesPanel({
  favoriteIds,
  onRemove,
  onClose,
}: {
  favoriteIds: string[];
  onRemove: (templateId: string) => void;
  onClose: () => void;
}) {
  const [templates, setTemplates] = useState<PublicTemplate[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setLoading(true);
    apiGet<{ items: PublicTemplate[] }>("/api/templates")
      .then((res) => {
        if (!active) return;
        const set = new Set(favoriteIds);
        setTemplates((res.items ?? []).filter((t) => set.has(t.id)));
      })
      .catch((err) => {
        if (err instanceof FetchError) {
          console.warn(err.message);
        }
      })
      .finally(() => {
        if (active) setLoading(false);
      });
    return () => {
      active = false;
    };
  }, [favoriteIds]);

  return (
    <div className="p-4">
      <div className="mb-3 flex items-center justify-between">
        <h3 className="text-sm font-semibold text-foreground">
          Your favorites
          <span className="ml-1.5 rounded-full bg-rose-100 px-2 py-0.5 text-[10px] font-semibold text-rose-700">
            {favoriteIds.length}
          </span>
        </h3>
        <button
          type="button"
          onClick={onClose}
          aria-label="Close favorites"
          className="rounded p-1 text-muted hover:bg-rose-50 hover:text-rose-700"
        >
          ✕
        </button>
      </div>
      {loading ? (
        <p className="text-sm text-muted">Loading favorites…</p>
      ) : templates.length === 0 ? (
        <div className="rounded-xl border border-dashed border-rose-200 bg-rose-50/40 p-4 text-center">
          <p className="text-sm font-medium text-foreground">No favorites yet</p>
          <p className="mt-1 text-xs text-muted">
            Tap the heart on a template to save it for quick access.
          </p>
          <Link
            href="/templates"
            className="mt-3 inline-flex items-center gap-1 rounded-full bg-rose-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-rose-600"
          >
            Browse templates →
          </Link>
        </div>
      ) : (
        <ul className="max-h-80 space-y-2 overflow-y-auto pr-1">
          {templates.map((t) => (
            <li
              key={t.id}
              className="flex items-start gap-3 rounded-xl border border-rose-100 bg-white p-2.5"
            >
              <div className="grid h-10 w-10 shrink-0 place-items-center rounded-lg bg-gradient-to-br from-rose-100 to-pink-100 text-sm font-semibold text-rose-700">
                {t.icon?.[0]?.toUpperCase() ?? t.name.charAt(0)}
              </div>
              <div className="min-w-0 flex-1">
                <p className="truncate text-sm font-semibold text-foreground">
                  {t.name}
                </p>
                <p className="truncate text-xs text-muted">{t.category}</p>
                <Link
                  href="/templates"
                  className="mt-1 inline-block text-[11px] font-medium text-rose-600 hover:text-rose-700"
                >
                  Use template →
                </Link>
              </div>
              <button
                type="button"
                onClick={() => onRemove(t.id)}
                aria-label={`Remove ${t.name} from favorites`}
                className="grid h-7 w-7 place-items-center rounded-full text-rose-400 hover:bg-rose-50 hover:text-rose-600"
              >
                ✕
              </button>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
