"use client";

import { Globe } from "lucide-react";
import { useRouter } from "next/navigation";
import { useTransition } from "react";
import { setActiveSite } from "@/components/shell/actions";

export interface WebsiteOption { id: string; name: string; organization?: { name: string } }

/**
 * Website field of the New Page / Add Panel editor (super admin).
 * - Creating: choosing another website reloads the editor for that website (`hrefTemplate` with `{id}`, or the open-website setting).
 */
export function WebsiteSelect({ sites, activeSiteId, hrefTemplate }: { sites: WebsiteOption[]; activeSiteId: string | null; hrefTemplate?: string}) {
  const router = useRouter();
  const [pending, start] = useTransition();
  const change = (id: string) => {
    if (hrefTemplate) { router.push(hrefTemplate.replace("{id}", encodeURIComponent(id))); return; }
    const fd = new FormData();
    fd.set("siteId", id);
    start(() => setActiveSite(fd));
  };
  return (
    <div className="flex flex-wrap items-center gap-2">
      <Globe className="h-4 w-4 text-[var(--ed-soft,theme(colors.gray.500))]" aria-hidden="true" />
      <label htmlFor="website-select" className="text-sm font-bold">Website</label>
      <select
        id="website-select"
        value={activeSiteId ?? ""}
        disabled={pending}
        onChange={(e) => change(e.target.value)}
        className="h-10 min-w-56 max-w-full rounded-full border border-border bg-white px-4 text-sm font-medium disabled:opacity-100"
      >
        {activeSiteId ? null : <option value="">Select a website…</option>}
        {sites.map((s) => <option key={s.id} value={s.id}>{s.name}{s.organization ? ` · ${s.organization.name}` : ""}</option>)}
      </select>
    </div>
  );
}
