"use client";

import { useActionState, useState } from "react";
import { updateNavItem, deleteNavItem } from "@/lib/actions/nav";
import type { NavItemWithChildren } from "@/components/layout/NavLink";

type TopLevelOption = { id: string; label: string };

const VISIBILITY_LABELS: Record<string, string> = {
  always: "Always",
  logged_in: "Logged in only",
  logged_out: "Logged out only",
};

export function NavItemRow({
  item,
  topLevelOptions,
}: {
  item: NavItemWithChildren;
  topLevelOptions: TopLevelOption[];
}) {
  const [editing, setEditing] = useState(false);
  const [state, formAction] = useActionState(updateNavItem, undefined);

  const parentOptions = topLevelOptions.filter((opt) => opt.id !== item.id);

  return (
    <li className="rounded-lg border border-charcoal/10 bg-warm-white p-4">
      {editing ? (
        <form
          action={async (formData) => {
            await formAction(formData);
            setEditing(false);
          }}
          className="flex flex-wrap items-center gap-2"
        >
          <input type="hidden" name="navItemId" value={item.id} />
          <input
            type="text"
            name="label"
            defaultValue={item.label}
            placeholder="Menu title"
            className="rounded border border-charcoal/20 bg-cream px-2 py-1 text-sm text-charcoal"
          />
          <input
            type="text"
            name="url"
            defaultValue={item.url}
            placeholder="/path or https://..."
            className="flex-1 rounded border border-charcoal/20 bg-cream px-2 py-1 text-sm text-charcoal"
          />
          <input
            type="number"
            name="order"
            defaultValue={item.order}
            className="w-16 rounded border border-charcoal/20 bg-cream px-2 py-1 text-sm text-charcoal"
          />
          <select
            name="parentId"
            defaultValue={item.parentId ?? ""}
            className="rounded border border-charcoal/20 bg-cream px-2 py-1 text-sm text-charcoal"
          >
            <option value="">Top level</option>
            {parentOptions.map((opt) => (
              <option key={opt.id} value={opt.id}>
                {opt.label}
              </option>
            ))}
          </select>
          <select
            name="visibility"
            defaultValue={item.visibility}
            className="rounded border border-charcoal/20 bg-cream px-2 py-1 text-sm text-charcoal"
          >
            <option value="always">Always</option>
            <option value="logged_in">Logged in only</option>
            <option value="logged_out">Logged out only</option>
          </select>
          <label className="flex items-center gap-1 text-sm text-charcoal">
            <input type="checkbox" name="isButtonStyle" defaultChecked={item.isButtonStyle} />
            Button style
          </label>
          <button type="submit" className="text-sm font-medium text-terracotta hover:underline">
            Save
          </button>
          <button
            type="button"
            onClick={() => setEditing(false)}
            className="text-sm text-charcoal/60 hover:underline"
          >
            Cancel
          </button>
        </form>
      ) : (
        <div className="flex items-center justify-between gap-4">
          <span className="text-charcoal">
            <strong>{item.label}</strong>{" "}
            <code className="text-xs text-charcoal/60">{item.url}</code>
            {item.visibility !== "always" && (
              <span className="ml-2 rounded-full bg-cream px-2 py-0.5 text-xs text-charcoal/60">
                {VISIBILITY_LABELS[item.visibility]}
              </span>
            )}
            {item.isButtonStyle && (
              <span className="ml-2 rounded-full bg-terracotta/10 px-2 py-0.5 text-xs text-terracotta">
                Button
              </span>
            )}
          </span>
          <div className="flex items-center gap-3">
            <button
              type="button"
              onClick={() => setEditing(true)}
              className="text-sm text-terracotta hover:underline"
            >
              Edit
            </button>
            <button
              type="button"
              onClick={() => deleteNavItem(item.id)}
              className="text-sm text-terracotta hover:underline"
            >
              Delete
            </button>
          </div>
        </div>
      )}
      {state?.error && <p className="mt-1 text-sm text-terracotta">{state.error}</p>}

      {item.children.length > 0 && (
        <ul className="mt-3 flex flex-col gap-2 border-l border-charcoal/10 pl-4">
          {item.children.map((child) => (
            <NavItemRow
              key={child.id}
              item={{ ...child, children: [] }}
              topLevelOptions={topLevelOptions}
            />
          ))}
        </ul>
      )}
    </li>
  );
}
