'use client';

import { useCallback, useEffect, useState } from 'react';
import { assigneeCount, assigneeRows } from '@/features/custom-properties/access-assignees';
import {
  ACCESS_LEVEL_CHOICES,
  assigneeKey,
  levelOf,
  type AccessAssignees,
  type AccessLevel,
} from '@/features/custom-properties/api.client';
import { listTeamOptions, type TeamOption } from '@/features/members/api.client';
import { useOwners } from '@/features/owners/useOwners';

export { hasAssignees } from '@/features/custom-properties/access-assignees';

/** One fetch of the teams per page load, like the owners (survives Strict Mode remounts). */
let teamsOnce: Promise<TeamOption[]> | null = null;

function loadTeams(): Promise<TeamOption[]> {
  teamsOnce ??= listTeamOptions().then(
    (r) => r.data,
    (err) => {
      teamsOnce = null;
      throw err;
    },
  );
  return teamsOnce;
}

/**
 * "Users and teams who can view and edit" (HUB-226, the design's "Assign to users and teams"):
 * the business's teams, then its active members, each with a checkbox, with a search and how many
 * are ticked. Assignees no longer in those lists (a deleted team, a deactivated user) are listed
 * too, so they can be unticked.
 */
export function AccessAssigneesField({
  value,
  onChange,
  disabled,
  replacesOn,
}: {
  value: AccessAssignees;
  onChange: (next: AccessAssignees) => void;
  disabled?: boolean;
  /** Bulk Manage access: how many properties the list replaces the assignees of. */
  replacesOn?: number;
}) {
  // Deactivated members too: an assignee who left is named, not "Inactive user".
  const { owners, loading, error } = useOwners(true, true);
  const [teams, setTeams] = useState<TeamOption[] | null>(null);
  const [teamsFailed, setTeamsFailed] = useState(false);
  const [query, setQuery] = useState('');
  const fetchTeams = useCallback(() => {
    setTeamsFailed(false);
    setTeams(null);
    let alive = true;
    loadTeams().then(
      (rows) => alive && setTeams(rows),
      () => {
        if (!alive) return;
        setTeams([]);
        setTeamsFailed(true);
      },
    );
    return () => {
      alive = false;
    };
  }, []);
  useEffect(() => fetchTeams(), [fetchTeams]);

  const toggle = (key: 'userIds' | 'teamIds', id: string, on: boolean) =>
    onChange({
      ...value,
      [key]: on ? [...value[key], id] : value[key].filter((x) => x !== id),
    });
  // G10: HubSpot's level per user or team.
  const setLevel = (kind: 'user' | 'team', id: string, level: AccessLevel) =>
    onChange({ ...value, levels: { ...value.levels, [assigneeKey(kind, id)]: level } });
  const rows = assigneeRows(value, teams ?? [], owners, query);
  const count = assigneeCount(value);

  return (
    <fieldset className="pp-assign" disabled={disabled}>
      <legend className="pp-label">Users and teams with access</legend>
      <p className="pp-help">
        Each one can view and edit, or only view. Anyone not listed can&apos;t see it. Super admins
        always see and edit it.
      </p>
      {replacesOn !== undefined && replacesOn > 1 && (
        <p className="pp-help">
          This replaces who has access on all {replacesOn} properties. The list starts empty.
        </p>
      )}
      {teams === null || loading ? (
        <p className="pp-help">Loading users and teams…</p>
      ) : (
        <>
          <input
            className="pp-input"
            type="search"
            placeholder="Search users and teams"
            aria-label="Search users and teams"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <p className="pp-help" aria-live="polite">
            {count} selected
          </p>
          {rows.map((r) => {
            const ticked = (r.kind === 'team' ? value.teamIds : value.userIds).includes(r.id);
            return (
              <div key={`${r.kind}:${r.id}`} className="pp-assign__row">
                <label className="pp-check">
                  <input
                    type="checkbox"
                    checked={ticked}
                    onChange={(e) =>
                      toggle(r.kind === 'team' ? 'teamIds' : 'userIds', r.id, e.target.checked)
                    }
                  />
                  <span>
                    {r.name} <small>{r.sub}</small>
                  </span>
                </label>
                {ticked && (
                  <select
                    className="pp-input pp-assign__level"
                    aria-label={`Access for ${r.name}`}
                    value={levelOf(value, r.kind, r.id)}
                    onChange={(e) => setLevel(r.kind, r.id, e.target.value as AccessLevel)}
                  >
                    {ACCESS_LEVEL_CHOICES.map((c) => (
                      <option key={c.value} value={c.value}>
                        {c.label}
                      </option>
                    ))}
                  </select>
                )}
              </div>
            );
          })}
          {teamsFailed && (
            <p className="pp-help">
              Teams couldn&apos;t be loaded.{' '}
              <button type="button" className="pp-textlink" onClick={fetchTeams}>
                Retry
              </button>
            </p>
          )}
          {error && (
            <p className="pp-help">Users couldn&apos;t be loaded. Reload the page to try again.</p>
          )}
          {!rows.length && !error && !teamsFailed && (
            <p className="pp-help">{query.trim() ? 'No matches.' : 'No users or teams yet.'}</p>
          )}
        </>
      )}
    </fieldset>
  );
}
