"use client";

import { ListChecks } from "lucide-react";
import { useOptimistic, useTransition } from "react";
import type { ListShareData, ListShareItem } from "../server/share-queries";
import { toggleShareListItem } from "../server/share-actions";
import { ShareEyebrow } from "@/components/share/share-eyebrow";

export function ListSharedView({
  data,
  canWrite,
  token,
}: {
  data: ListShareData;
  canWrite: boolean;
  token: string;
}) {
  const [optimisticItems, setOptimisticItems] = useOptimistic(
    data.items,
    (current: ListShareItem[], { id, done }: { id: string; done: boolean }) =>
      current.map((item) => (item.id === id ? { ...item, done } : item)),
  );
  const [, startTransition] = useTransition();

  function toggle(item: ListShareItem) {
    if (!canWrite) return;
    const next = !item.done;
    startTransition(async () => {
      setOptimisticItems({ id: item.id, done: next });
      await toggleShareListItem(token, item.id);
    });
  }

  const open = optimisticItems.filter((i) => !i.done);
  const done = optimisticItems.filter((i) => i.done);

  return (
    <>
      <ShareEyebrow>
        <ListChecks className="size-3" />
        List
      </ShareEyebrow>
      <h1
        className="serif"
        style={{
          fontSize: "clamp(28px, 6vw, 38px)",
          lineHeight: 1.15,
          letterSpacing: "-0.02em",
          color: "var(--ink)",
          margin: "0 0 8px",
          textWrap: "pretty",
        }}
      >
        {data.name}
      </h1>
      <p className="muted text-[13px] capitalize mb-6">{data.type}</p>

      {optimisticItems.length === 0 ? (
        <p className="muted text-[13.5px]">This list is empty.</p>
      ) : (
        <div
          className="rounded-[var(--r-md)] overflow-hidden"
          style={{
            background: "var(--card)",
            border: "0.5px solid var(--hair)",
          }}
        >
          {open.length > 0 && (
            <>
              {open.map((item) => (
                <ItemRow key={item.id} item={item} canWrite={canWrite} onToggle={toggle} />
              ))}
            </>
          )}
          {done.length > 0 && (
            <details className="group">
              <summary
                className="cursor-pointer select-none eyebrow"
                style={{ padding: "12px 14px 8px", borderTop: "0.5px solid var(--hair)" }}
              >
                Done · {done.length}
              </summary>
              {done.map((item) => (
                <ItemRow key={item.id} item={item} canWrite={canWrite} onToggle={toggle} />
              ))}
            </details>
          )}
        </div>
      )}
    </>
  );
}

function ItemRow({
  item,
  canWrite,
  onToggle,
}: {
  item: ListShareItem;
  canWrite: boolean;
  onToggle: (item: ListShareItem) => void;
}) {
  return (
    <div className={`list-row ${item.done ? "checked" : ""}`}>
      <button
        type="button"
        aria-label={`Complete ${item.text}`}
        aria-pressed={item.done}
        className={`checkbox ${item.done ? "on" : ""}`}
        disabled={!canWrite}
        onClick={() => onToggle(item)}
      >
        {item.done && (
          <svg
            width="12"
            height="12"
            viewBox="0 0 24 24"
            fill="none"
            stroke="white"
            strokeWidth="2.4"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M5 12l5 5L20 7" />
          </svg>
        )}
      </button>
      <span className="row-text flex-1 text-[13.5px]">
        {item.text}
        {item.qty && <span className="ml-1 text-[11.5px] muted">×{item.qty}</span>}
      </span>
    </div>
  );
}
