'use client';

import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { LpIcon } from '@/features/list-page/ui/LpIcon';
import { cn } from '@/lib/utils/cn';

function ChevronIcon() {
  return (
    <svg className="crm-collapsible-card__chevron" viewBox="0 0 24 24" aria-hidden>
      <path d="m6 9 6 6 6-6" />
    </svg>
  );
}

/**
 * B4: inside a list preview that asks for it (Companies), cards draw as the 28 Oct design's
 * preview sections (`lp-pv__sec` with an `lp-pv__sh` toggle, list-page.js:3623). Off by default:
 * every record page keeps its own card.
 */
export const PreviewSectionLook = createContext(false);

/** Whether the cards here draw as the design's preview sections (`PreviewSectionLook`). */
export function usePreviewSectionLook(): boolean {
  return useContext(PreviewSectionLook);
}

/**
 * R4: the contact and company record pages' sidebars. Right side: each card's open state is kept
 * per viewer (browser storage `storageKey`, as the design's `rt.collapsed.<object>`,
 * record-tabs.js:262-264, :341-349), with `defaultCollapsed` until the viewer chooses. Left side
 * (`phoneCollapsed`): property cards start collapsed below 768px (record-tabs.js:250-251). Null
 * everywhere else: cards open as before.
 */
export interface CardMemoryValue {
  storageKey: string | null;
  defaultCollapsed: readonly string[];
  phoneCollapsed?: boolean;
}
export const CardMemory = createContext<CardMemoryValue | null>(null);

function readCollapsed(key: string): string[] | null {
  try {
    const v: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null');
    return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : null;
  } catch {
    return null;
  }
}

function writeCollapsed(key: string, id: string, collapsed: boolean, defaults: readonly string[]) {
  try {
    const list = new Set(readCollapsed(key) ?? defaults);
    if (collapsed) list.add(id);
    else list.delete(id);
    window.localStorage.setItem(key, JSON.stringify([...list]));
  } catch {
    // Storage blocked (private window): the choice lasts for this page only.
  }
}

/**
 * A sidebar card's open state. Without `CardMemory`, `defaultOpen` as before. With it, after
 * mount (so the server's markup and the first paint match): the viewer's saved choice, else the
 * page's defaults; a toggle is saved.
 */
export function useCardOpen(
  cardId: string | undefined,
  defaultOpen: boolean,
): [boolean, (next: boolean) => void] {
  const memory = useContext(CardMemory);
  const [open, setOpenState] = useState(defaultOpen);
  useEffect(() => {
    if (!memory || !cardId) return;
    if (memory.phoneCollapsed && window.matchMedia?.('(max-width: 767.98px)').matches) {
      setOpenState(false);
      return;
    }
    if (!memory.storageKey) return;
    const saved = readCollapsed(memory.storageKey) ?? [...memory.defaultCollapsed];
    setOpenState(!saved.includes(cardId));
    // eslint-disable-next-line react-hooks/exhaustive-deps -- once, after mount
  }, []);
  const setOpen = (next: boolean) => {
    setOpenState(next);
    if (memory?.storageKey && cardId) {
      writeCollapsed(memory.storageKey, cardId, !next, memory.defaultCollapsed);
    }
  };
  return [open, setOpen];
}

const CompanyCardState = createContext<{ on: boolean; open: boolean; toggle: () => void } | null>(
  null,
);

/**
 * R4: a company page right card (`.company-associated-card`). Inside `CardMemory` its title is
 * the design's toggle (every right card collapses, record-tabs.js:274-277) and a collapsed card
 * shows only its head; elsewhere (previews, Deals) the same markup as before.
 */
export function CompanyCard({
  cardId,
  dataCardId,
  children,
}: {
  cardId: string;
  /** `data-card-id`, as the card set it before. */
  dataCardId?: string;
  children: ReactNode;
}) {
  const memory = useContext(CardMemory);
  const [open, setOpen] = useCardOpen(cardId, true);
  const on = Boolean(memory);
  return (
    <section
      className={cn('card company-associated-card', on && !open && 'is-collapsed')}
      data-card-id={dataCardId}
    >
      <CompanyCardState.Provider value={{ on, open, toggle: () => setOpen(!open) }}>
        {children}
      </CompanyCardState.Provider>
    </section>
  );
}

/** The `<h2>` of a `CompanyCard`: the toggle inside `CardMemory`, plain text elsewhere. */
export function CompanyCardTitle({ children }: { children: ReactNode }) {
  const state = useContext(CompanyCardState);
  if (!state?.on) return <h2>{children}</h2>;
  return (
    <h2>
      <button
        type="button"
        className="company-card-toggle"
        aria-expanded={state.open}
        onClick={state.toggle}
      >
        <ChevronIcon />
        {children}
      </button>
    </h2>
  );
}

/** A sidebar card of the record page (`.crm-collapsible-card`, details.css). */
export function CollapsibleCard({
  title,
  action,
  defaultOpen = true,
  children,
  cardId,
}: {
  title: string;
  action?: ReactNode;
  defaultOpen?: boolean;
  children: ReactNode;
  cardId?: string;
}) {
  const [open, setOpen] = useCardOpen(cardId, defaultOpen);
  const section = usePreviewSectionLook();
  if (section) {
    // The design's section: its heading holds only the toggle; a card's own action sits beside
    // it. Closed, the body stays and the design's CSS hides it (list-page.css:476).
    const heading = (
      <h3>
        <button
          type="button"
          className="lp-pv__sh"
          aria-expanded={open}
          onClick={() => setOpen(!open)}
        >
          <LpIcon name="caret" />
          {title}
        </button>
      </h3>
    );
    return (
      <section className="lp-pv__sec" data-card-id={cardId}>
        {action ? (
          <div className="lp-pv__shrow">
            {heading}
            {action}
          </div>
        ) : (
          heading
        )}
        <div className="lp-pv__fields">{children}</div>
      </section>
    );
  }
  return (
    <section className={cn('crm-collapsible-card', !open && 'is-collapsed')} data-card-id={cardId}>
      <header className="crm-collapsible-card__header">
        <button
          type="button"
          className="crm-collapsible-card__toggle"
          aria-expanded={open}
          onClick={() => setOpen(!open)}
        >
          <ChevronIcon />
          <span title={title}>{title}</span>
        </button>
        {action}
      </header>
      <div className="crm-collapsible-card__body">
        <div className="crm-collapsible-card__body-inner">{children}</div>
      </div>
    </section>
  );
}
