"use client";

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";

type ResourceSection = {
  title: string;
  level: number;
};

type ResourceLink = {
  id: string;
  title: string;
  url: string;
  category: string;
  status: string;
  createdAt: string;
};

interface ResourceLinkCaptureProps {
  date: string;
}

export function ResourceLinkCapture({ date }: ResourceLinkCaptureProps) {
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState("");
  const [url, setUrl] = useState("");
  const [category, setCategory] = useState("Interesting things to read up:");
  const qc = useQueryClient();

  const { data } = useQuery({
    queryKey: ["resource-links", "capture"],
    queryFn: async () => {
      const res = await fetch("/api/resource-links?status=inbox&includeSections=1");
      if (!res.ok) throw new Error("Failed to load resource links");
      return res.json() as Promise<{ links: ResourceLink[]; sections: ResourceSection[] }>;
    },
    enabled: open,
    staleTime: 60_000,
  });

  const sections = data?.sections?.length
    ? data.sections
    : [{ title: "Interesting things to read up:", level: 1 }];

  const save = useMutation({
    mutationFn: async () => {
      const res = await fetch("/api/resource-links", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ date, title, url, category }),
      });
      if (!res.ok) {
        const data = await res.json().catch(() => ({}));
        throw new Error(data.error ?? "Failed to save link");
      }
      return res.json();
    },
    onSuccess: () => {
      setTitle("");
      setUrl("");
      qc.invalidateQueries({ queryKey: ["resource-links"] });
    },
  });

  if (!open) {
    return (
      <button type="button" className="retro-btn text-xs w-full" onClick={() => setOpen(true)}>
        Capture resource link
      </button>
    );
  }

  return (
    <div className="retro-window border border-[var(--warm-grey)]/30">
      <div className="retro-titlebar text-sm">Resource Inbox</div>
      <div className="p-3 space-y-2 text-sm">
        <input
          className="retro-input w-full text-xs"
          placeholder="Title"
          value={title}
          onChange={(event) => setTitle(event.target.value)}
        />
        <input
          className="retro-input w-full text-xs"
          placeholder="https://..."
          value={url}
          onChange={(event) => setUrl(event.target.value)}
        />
        <select
          className="retro-window-inset w-full p-1 text-xs"
          value={category}
          onChange={(event) => setCategory(event.target.value)}
        >
          {sections.map((section) => (
            <option key={section.title} value={section.title}>
              {section.title}
            </option>
          ))}
        </select>
        {save.error && (
          <p className="text-xs text-[var(--muted-rose)]">{save.error.message}</p>
        )}
        <div className="flex gap-2">
          <button
            type="button"
            className="retro-btn retro-btn-primary text-xs flex-1"
            disabled={save.isPending || !title.trim() || !url.trim()}
            onClick={() => save.mutate()}
          >
            {save.isPending ? "Saving..." : "Save link"}
          </button>
          <button type="button" className="retro-btn text-xs" onClick={() => setOpen(false)}>
            Close
          </button>
        </div>
        {data?.links?.length ? (
          <div className="pt-2 border-t border-[var(--warm-grey)]/25">
            <p className="text-xs font-bold text-[var(--warm-grey)] mb-1">Inbox</p>
            <ul className="space-y-1">
              {data.links.slice(0, 4).map((link) => (
                <li key={link.id} className="text-xs truncate">
                  {link.title}
                </li>
              ))}
            </ul>
          </div>
        ) : null}
      </div>
    </div>
  );
}
