"use client";

import Link from "next/link";
import { useId, useState } from "react";
import { useRouter } from "next/navigation";
import { deletePanelLocationAction, updatePanelLocationAction } from "@/lib/actions/platform";
import { LOCATION_PLACEMENTS, PLACEMENT_LABELS, type LocationPlacement } from "@/lib/public/panel-positions";
import { cn } from "@/lib/utils";
import { StatusLine, useRun } from "@/components/features/accounts/use-run";
import { EdField, EdTabs, Modal, Pill, YesNo, edInput, pillClass } from "@/components/features/page-editor/ed-ui";
import type { LocationRow, SiteOption } from "./locations-manager";

type Tab = "content" | "settings";

/** ShowOff-style "position editor": Label, Position Type, then Content / Settings tabs and a sticky Save bar. */
export function PositionEditor({ location, sites }: { location: LocationRow; sites: SiteOption[] }) {
  const router = useRouter();
  const { pending, msg, errors, run } = useRun();
  const ids = useId();
  const [name, setName] = useState(location.name);
  const [placement, setPlacement] = useState<LocationPlacement>(location.placement);
  const [description, setDescription] = useState(location.description);
  const [active, setActive] = useState(location.active);
  const [all, setAll] = useState(location.siteIds === null);
  const [siteIds, setSiteIds] = useState<string[]>(location.siteIds ?? []);
  const [tab, setTab] = useState<Tab>("content");
  const [dirty, setDirty] = useState(false);
  const [confirmDelete, setConfirmDelete] = useState(false);
  const touch = () => setDirty(true);
  const invalid = name.trim().length < 2 || (!all && siteIds.length === 0);

  const save = () => run(() => updatePanelLocationAction(location.id, { name, description, placement, siteIds: all ? null : siteIds, active }), () => setDirty(false));

  return (
    <div className="ed -m-1 space-y-5 rounded-3xl bg-[var(--ed-bg)] p-4 sm:p-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <h1 className="text-4xl font-bold tracking-tight text-[var(--ed-ink)]">{location.name}</h1>
        <Link href="/dashboard/panel-locations" className={pillClass("outline", "px-5 py-3")}>Return to Panel Positions</Link>
      </div>

      <EdField id={`${ids}-label`} label="Label:" error={errors.name}>
        <input id={`${ids}-label`} value={name} maxLength={80} aria-invalid={errors.name ? true : undefined} onChange={(e) => { setName(e.target.value); touch(); }} className={cn(edInput, "rounded-xl bg-white py-3")} />
      </EdField>

      <EdField id={`${ids}-type`} label="Position Type" hint={`Key: ${location.key} (set when the position was created)`}>
        <select id={`${ids}-type`} value={placement} onChange={(e) => { setPlacement(e.target.value as LocationPlacement); touch(); }} className={cn(edInput, "rounded-xl bg-white py-3")}>
          {LOCATION_PLACEMENTS.map((p) => <option key={p} value={p}>{PLACEMENT_LABELS[p]}</option>)}
        </select>
      </EdField>

      <EdTabs<Tab> label="Position options" tabs={[{ id: "content", label: "Content" }, { id: "settings", label: "Settings" }]} value={tab} onChange={setTab}>
        {tab === "content" ? (
          <div className="space-y-4">
            <EdField id={`${ids}-help`} label="Help text for admins" hint="Shown under the Location field when an admin adds a panel here.">
              <input id={`${ids}-help`} value={description} maxLength={255} onChange={(e) => { setDescription(e.target.value); touch(); }} className={cn(edInput, "rounded-xl py-3")} />
            </EdField>
            <p className="text-xs text-[var(--ed-soft)]">{location.panels} panel{location.panels === 1 ? "" : "s"} use this position across all websites.</p>
          </div>
        ) : (
          <fieldset className="space-y-3">
            <legend className="mb-1 text-xs font-bold text-[var(--ed-ink)]">Websites that can use this position</legend>
            <label className="flex items-center gap-2 text-sm"><input type="radio" name={`${ids}-scope`} checked={all} onChange={() => { setAll(true); touch(); }} />All websites (including ones added later)</label>
            <label className="flex items-center gap-2 text-sm"><input type="radio" name={`${ids}-scope`} checked={!all} onChange={() => { setAll(false); touch(); }} />Only the websites I choose</label>
            {!all ? (
              <div role="group" aria-label="Websites" className="max-h-64 overflow-auto rounded-lg border border-[var(--ed-line)] p-2">
                {sites.map((s) => (
                  <label key={s.id} className="flex items-center gap-2 py-0.5 text-sm">
                    <input type="checkbox" checked={siteIds.includes(s.id)} onChange={(e) => { setSiteIds(e.target.checked ? [...siteIds, s.id] : siteIds.filter((x) => x !== s.id)); touch(); }} />
                    {s.name} <span className="text-xs text-[var(--ed-soft)]">· {s.organization}</span>
                  </label>
                ))}
              </div>
            ) : null}
          </fieldset>
        )}
      </EdTabs>

      <StatusLine msg={msg} />

      <div role="region" aria-label="Position actions" className="sticky bottom-0 z-30 mt-6 flex flex-wrap items-center justify-end gap-3 rounded-3xl bg-[var(--ed-dark)] px-4 py-3 text-white shadow-xl">
        <div className="min-w-0 basis-full text-xs sm:basis-0 sm:flex-1" aria-live="polite">
          {msg ? <span className={cn("font-bold", msg.ok ? "text-[#9be7c9]" : "text-[#ffb4c8]")}>{msg.text}</span> : dirty ? <span className="font-bold text-[#ffe08a]">Unsaved changes</span> : null}
        </div>
        <div className="flex items-center gap-2 text-xs font-bold">
          <span>Available:</span>
          <YesNo label="Position is available to admins" value={active} disabled={pending} onChange={(v) => { setActive(v); touch(); }} />
        </div>
        <Pill variant="pink" disabled={pending} onClick={() => setConfirmDelete(true)}>Delete</Pill>
        <Pill variant="green" disabled={pending || invalid || !dirty} onClick={save}>{pending ? "Saving…" : "Save"}</Pill>
      </div>

      {confirmDelete ? (
        <Modal title="Delete this position?" onClose={() => setConfirmDelete(false)}>
          <div className="space-y-4 px-8 pb-8 text-center text-sm text-[var(--ed-ink)]">
            <p>A position that still has panels cannot be deleted. Turn it off instead, or move those panels first.</p>
            <div className="flex justify-center gap-2">
              <Pill variant="grey" onClick={() => setConfirmDelete(false)}>Cancel</Pill>
              <Pill variant="pink" disabled={pending} onClick={() => run(() => deletePanelLocationAction(location.id), () => router.push("/dashboard/panel-locations"))}>Delete position</Pill>
            </div>
          </div>
        </Modal>
      ) : null}
    </div>
  );
}
