"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { createSitePositionAction, deleteSitePositionAction, resetSitePositionLabelsAction, saveSitePositionLabelsAction, updateSitePositionAction } from "@/lib/actions/panels";
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, Modal, Pill, YesNo, edInput, pillClass } from "@/components/features/page-editor/ed-ui";

export interface PositionRow { key: string; name: string; description: string; builtIn: boolean; type: string; panels: number; ownId: string | null; active: boolean; placement: LocationPlacement | null; defaultName: string; overridden: boolean }

const BASE = "/dashboard/panels/positions";

/** ShowOff-style "Panel Positions" table for one website: Position, Panel Count, Type and an Edit Position button. */
export function SitePositions({ siteId, positions }: { siteId: string; positions: PositionRow[] }) {
  const { pending, msg, errors, run } = useRun();
  const [adding, setAdding] = useState(false);
  const [name, setName] = useState("");
  const [placement, setPlacement] = useState<LocationPlacement>("below-content");
  const [description, setDescription] = useState("");
  return (
    <div className="space-y-5">
      <div className="flex flex-wrap items-center gap-3">
        <h1 className="mr-auto text-4xl font-bold tracking-tight text-[var(--ed-ink)]">Panel Positions</h1>
        <Link href="/dashboard/panels" className={pillClass("outline", "py-2.5")}>Back to Panels</Link>
        <Pill variant="outline" className="py-2.5" onClick={() => setAdding(true)}>Add Panel Position</Pill>
      </div>
      <StatusLine msg={msg} />
      <div className="overflow-x-auto rounded-3xl bg-white" tabIndex={0} role="region" aria-label="Panel positions table">
        <table className="w-full text-left text-sm text-[var(--ed-ink)]">
          <caption className="sr-only">Panel positions of this website</caption>
          <thead><tr className="border-b border-[var(--ed-line)]"><th scope="col" className="px-6 py-4 font-bold">Position</th><th scope="col" className="px-6 py-4 font-bold">Panel Count</th><th scope="col" className="px-6 py-4 font-bold">Type</th><th scope="col" className="px-6 py-4"><span className="sr-only">Actions</span></th></tr></thead>
          <tbody className="divide-y divide-[var(--ed-line)]">
            {positions.map((p) => (
              <tr key={p.key}>
                <th scope="row" className="px-6 py-4 font-medium">{p.name}{!p.active ? <span className="ml-2 rounded-full border-2 border-[var(--ed-dark)] px-2 py-0.5 text-[10px] font-bold">Off</span> : null}</th>
                <td className="px-6 py-4">{p.panels}</td>
                <td className="px-6 py-4">{p.type}</td>
                <td className="px-6 py-4 text-right"><Link href={`${BASE}/${p.key}`} aria-label={`Edit position ${p.name}`} className={pillClass("grey")}>Edit Position</Link></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <p className="text-xs text-[var(--ed-soft)]">Header, Hero, Footer and Popup are built in. You can rename any position for this website. Positions you add here belong to this website only, so you can also change their type and delete them.</p>
      {adding ? (
        <Modal title="Add Panel Position" onClose={() => setAdding(false)}>
          <form className="space-y-4 px-8 pb-8" onSubmit={(e) => { e.preventDefault(); run(() => createSitePositionAction(siteId, { name, description, placement, active: true }), () => { setAdding(false); setName(""); setDescription(""); }); }}>
            <EdField id="np-name" label="Label:" error={errors.name}><input id="np-name" value={name} maxLength={80} onChange={(e) => setName(e.target.value)} className={cn(edInput, "py-3")} aria-invalid={errors.name ? true : undefined} /></EdField>
            <EdField id="np-type" label="Position Type"><select id="np-type" value={placement} onChange={(e) => setPlacement(e.target.value as LocationPlacement)} className={cn(edInput, "py-3")}>{LOCATION_PLACEMENTS.map((p) => <option key={p} value={p}>{PLACEMENT_LABELS[p]}</option>)}</select></EdField>
            <EdField id="np-help" label="Help text (optional)"><input id="np-help" value={description} maxLength={255} onChange={(e) => setDescription(e.target.value)} className={cn(edInput, "py-3")} /></EdField>
            {msg && !msg.ok && !errors.name ? <p role="alert" className="text-xs font-medium text-[#b91c1c]">{msg.text}</p> : null}
            <div className="flex justify-end gap-2"><Pill variant="grey" onClick={() => setAdding(false)}>Cancel</Pill><Pill type="submit" variant="green" disabled={pending || name.trim().length < 2}>{pending ? "Adding…" : "Add position"}</Pill></div>
          </form>
        </Modal>
      ) : null}
    </div>
  );
}

/** Edit one position. Positions made for this website only are editable; built-in and shared ones are read-only. */
export function SitePositionEditor({ siteId, position }: { siteId: string; position: PositionRow }) {
  const router = useRouter();
  const { pending, msg, errors, run } = useRun();
  const editable = position.ownId !== null;
  const [name, setName] = useState(position.name);
  const [description, setDescription] = useState(position.description);
  const [placement, setPlacement] = useState<LocationPlacement>(position.placement ?? "below-content");
  const [active, setActive] = useState(position.active);
  const [dirty, setDirty] = useState(false);
  const [confirm, setConfirm] = useState(false);
  const touch = () => setDirty(true);
  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)]">{position.name}</h1>
        <Link href="/dashboard/panels/positions" className={pillClass("outline", "px-5 py-3")}>Return to Panel Positions</Link>
      </div>
      {!editable ? <p className="rounded-2xl bg-white px-5 py-3 text-sm text-[var(--ed-ink)]">{position.builtIn ? "This is a built-in position. You can rename it for this website; where it appears on the page stays the same." : "This position is shared with other websites. You can rename it for this website; where it appears on the page is set by your platform administrator."}</p> : null}
      <div className="space-y-4 rounded-3xl bg-white p-6">
        <EdField id="pe-name" label="Label:" error={errors.name}><input id="pe-name" value={name} maxLength={80} onChange={(e) => { setName(e.target.value); touch(); }} className={cn(edInput, "py-3")} aria-invalid={errors.name ? true : undefined} /></EdField>
        <EdField id="pe-type" label="Position Type" hint={`Key: ${position.key}`}>
          {position.builtIn ? <input id="pe-type" value={position.type} disabled className={cn(edInput, "py-3")} /> : (
            <select id="pe-type" value={placement} disabled={!editable} onChange={(e) => { setPlacement(e.target.value as LocationPlacement); touch(); }} className={cn(edInput, "py-3")}>{LOCATION_PLACEMENTS.map((p) => <option key={p} value={p}>{PLACEMENT_LABELS[p]}</option>)}</select>
          )}
        </EdField>
        <EdField id="pe-help" label="Help text"><input id="pe-help" value={description} maxLength={255} onChange={(e) => { setDescription(e.target.value); touch(); }} className={cn(edInput, "py-3")} /></EdField>
        <p className="text-xs text-[var(--ed-soft)]">{position.panels} panel{position.panels === 1 ? "" : "s"} on this website use this position.</p>
      </div>
      <div role="region" aria-label="Position actions" className="sticky bottom-0 z-30 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>
        {editable ? <div className="flex items-center gap-2 text-xs font-bold"><span>Available:</span><YesNo label="Position is available" value={active} disabled={pending} onChange={(v) => { setActive(v); touch(); }} /></div> : null}
        {editable ? <Pill variant="pink" disabled={pending} onClick={() => setConfirm(true)}>Delete</Pill> : null}
        {!editable && position.overridden ? <Pill variant="grey" disabled={pending} onClick={() => run(() => resetSitePositionLabelsAction(siteId, position.key), () => router.push("/dashboard/panels/positions"))}>Reset to default</Pill> : null}
        <Pill variant="green" disabled={pending || !dirty || name.trim().length < 2} onClick={() => run(() => (editable ? updateSitePositionAction(siteId, position.key, { name, description, placement, active }) : saveSitePositionLabelsAction(siteId, position.key, { name, description })), () => setDirty(false))}>{pending ? "Saving…" : "Save"}</Pill>
      </div>
      {confirm ? (
        <Modal title="Delete this position?" onClose={() => setConfirm(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. Move or delete those panels first.</p>
            <div className="flex justify-center gap-2"><Pill variant="grey" onClick={() => setConfirm(false)}>Cancel</Pill><Pill variant="pink" disabled={pending} onClick={() => { setConfirm(false); run(() => deleteSitePositionAction(siteId, position.key), () => router.push("/dashboard/panels/positions")); }}>Delete position</Pill></div>
          </div>
        </Modal>
      ) : null}
    </div>
  );
}
