"use client";

import { useId, useRef, type ReactNode } from "react";
import Link from "next/link";
import { ChevronRight } from "lucide-react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/cn";

type DomainApp = { id: string; projectCode: string; projectName: string };

/**
 * Wraps a domain name or its app codes in a button that lists every app on the
 * domain — the table cell only has room for the first few.
 */
export function DomainAppsButton({
  domain,
  apps,
  className,
  children,
}: {
  domain: string;
  apps: DomainApp[];
  className?: string;
  children: ReactNode;
}) {
  const dialogRef = useRef<HTMLDialogElement>(null);
  const titleId = useId();

  return (
    <>
      <button
        type="button"
        onClick={() => dialogRef.current?.showModal()}
        aria-haspopup="dialog"
        aria-label={`Show the ${apps.length} ${apps.length === 1 ? "app" : "apps"} on ${domain}`}
        className={cn("cursor-pointer text-left underline-offset-2 hover:underline", className)}
      >
        {children}
      </button>

      <dialog
        ref={dialogRef}
        aria-labelledby={titleId}
        // A click on the backdrop lands on the <dialog> itself: close, like Esc.
        onClick={(event) => event.target === dialogRef.current && dialogRef.current.close()}
        className="m-auto w-[calc(100%-2rem)] max-w-lg rounded-lg border border-slate-200 bg-white p-0 text-left whitespace-normal shadow-xl backdrop:bg-slate-950/40"
      >
        <div className="border-b border-slate-200 px-5 py-4">
          <h2 id={titleId} className="text-sm font-semibold text-slate-900">
            {domain}
          </h2>
          <p className="mt-0.5 text-xs text-slate-500">
            {`Used by ${apps.length} monitored ${apps.length === 1 ? "app" : "apps"}`}
          </p>
        </div>

        <ul className="max-h-[60vh] divide-y divide-slate-100 overflow-y-auto">
          {apps.map((app) => (
            <li key={app.id}>
              <Link
                href={`/apps/${app.id}`}
                className="flex items-center gap-3 px-5 py-2.5 text-sm hover:bg-slate-50"
              >
                <span className="w-24 shrink-0 truncate font-mono text-xs font-medium text-slate-900" title={app.projectCode}>
                  {app.projectCode}
                </span>
                <span className="min-w-0 flex-1 truncate text-slate-700" title={app.projectName}>
                  {app.projectName}
                </span>
                <ChevronRight className="size-4 shrink-0 text-slate-400" aria-hidden />
              </Link>
            </li>
          ))}
        </ul>

        <div className="flex justify-end border-t border-slate-200 bg-slate-50 px-5 py-3">
          <Button variant="secondary" onClick={() => dialogRef.current?.close()}>
            Close
          </Button>
        </div>
      </dialog>
    </>
  );
}
