'use client';

/** The design's "Manage sharing settings" drawer (#dShare): Private, Everyone, or specific users/teams. */
import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { MtIcon, MtModal, MtModalHead, MtSprite } from '@/features/snippets/ui/mt';
import type { ShareState } from '../model';

export interface ShareOptions {
  users: Array<{ id: string; name: string }>;
  teams: Array<{ id: string; name: string }>;
}

function Check({
  label,
  checked,
  disabled,
  onChange,
}: {
  label: string;
  checked: boolean;
  disabled?: boolean;
  onChange: (on: boolean) => void;
}) {
  return (
    <label className="check">
      <input
        type="checkbox"
        checked={checked}
        disabled={disabled}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className="check__box" />
      {label}
    </label>
  );
}

const toggleIn = (list: string[], id: string, on: boolean) =>
  on ? (list.includes(id) ? list : [...list, id]) : list.filter((x) => x !== id);

const sameIds = (a: string[], b: string[]) =>
  a.length === b.length && a.every((id) => b.includes(id));

export function ShareDrawer({
  share,
  options,
  saving,
  onClose,
  onSave,
  noun = 'template',
  privateTip,
  lockedUserId,
  saveNeedsChange = false,
}: {
  /** What is being shared, for the drawer's wording. */
  noun?: 'template' | 'snippet' | 'sequence' | 'folder';
  /** The Private option's tip, when it differs (Sequences #53: super admins see them too). */
  privateTip?: string;
  /**
   * IDX-13 (HubSpot): a user always shown ticked and locked in the Users list (a sequence's
   * owner, who can always see it). Never saved in `users`.
   */
  lockedUserId?: string;
  /**
   * IDX-13 (HubSpot): Save stays disabled until the choice differs from `share`, and while
   * "Specific users or teams" has nobody ticked.
   */
  saveNeedsChange?: boolean;
  share: ShareState;
  options: ShareOptions;
  saving?: boolean;
  onClose: () => void;
  onSave: (s: ShareState) => void;
}) {
  const toast = useToast();
  const [mode, setMode] = useState(share.mode);
  const [users, setUsers] = useState(share.users.filter((id) => id !== lockedUserId));
  const [teams, setTeams] = useState(share.teams);
  const [tab, setTab] = useState<'teams' | 'users'>('teams');
  const [uq, setUq] = useState('');
  const q = uq.trim().toLowerCase();
  const shownUsers = [...options.users]
    .sort((a, b) => a.name.localeCompare(b.name))
    .filter((u) => !q || u.name.toLowerCase().includes(q));
  const nobodyPicked = mode === 'specific' && !users.length && !teams.length;
  const unchanged =
    mode === share.mode &&
    (mode !== 'specific' ||
      (sameIds(
        users,
        share.users.filter((id) => id !== lockedUserId),
      ) &&
        sameIds(teams, share.teams)));
  const saveBlocked = saveNeedsChange && (unchanged || nobodyPicked);

  return (
    <MtModal
      id="dShare"
      drawer
      onClose={onClose}
      labelledBy="dShareT"
      focus="input[name=mttShareMode]:checked"
    >
      {/* Sequences SQ-3: its own icons (ⓘ, ✕), so it works on pages that mount no sprite (the
          sequences pages); where the page has one, that one comes first and is used. */}
      <MtSprite />
      <MtModalHead id="dShareT" title="Manage sharing settings" onClose={onClose} />
      <div className="mt-drawer__body" id="shareBody">
        <div className="field__label" id="shareQ">
          Who can see this {noun}?
        </div>
        <div className="mt-radio-group" role="radiogroup" aria-labelledby="shareQ">
          {(
            [
              ['private', 'Private', privateTip ?? `Only you can view and use this ${noun}`],
              ['everyone', 'Everyone', ''],
              ['specific', 'Specific users or teams', ''],
            ] as const
          ).map(([value, label, tip]) => (
            <label key={value} className="mt-radio">
              <input
                type="radio"
                name="mttShareMode"
                value={value}
                checked={mode === value}
                onChange={() => setMode(value)}
              />
              <span className="mt-radio__dot" />
              <span>{label}</span>
              {tip ? (
                <span className="mt-tip" data-mt-tip={tip}>
                  <MtIcon name="info" />
                </span>
              ) : null}
            </label>
          ))}
        </div>
        {mode === 'specific' ? (
          <div id="shareDetail">
            <div className="mt-tabs" role="tablist">
              {(
                [
                  ['teams', 'Teams'],
                  ['users', 'Users'],
                ] as const
              ).map(([key, label]) => (
                <button
                  key={key}
                  type="button"
                  className="mt-tab"
                  role="tab"
                  aria-selected={tab === key}
                  onClick={() => setTab(key)}
                >
                  {label}
                </button>
              ))}
            </div>
            <div role="tabpanel">
              {tab === 'teams' ? (
                <div className="mt-checklist">
                  {options.teams.length ? (
                    options.teams.map((t) => (
                      <Check
                        key={t.id}
                        label={t.name}
                        checked={teams.includes(t.id)}
                        onChange={(on) => setTeams((cur) => toggleIn(cur, t.id, on))}
                      />
                    ))
                  ) : (
                    <div className="mt-empty-opt">No teams yet</div>
                  )}
                </div>
              ) : (
                <>
                  <div className="mt-search mt-search--block" style={{ marginBottom: 12 }}>
                    <input
                      className="input"
                      type="search"
                      placeholder="Search"
                      aria-label="Search users"
                      autoComplete="off"
                      value={uq}
                      onChange={(e) => setUq(e.target.value)}
                    />
                    <MtIcon name="search" className="mt-search__icon" />
                  </div>
                  <div className="mt-checklist">
                    {shownUsers.map((u) => (
                      <Check
                        key={u.id}
                        label={u.name}
                        checked={u.id === lockedUserId || users.includes(u.id)}
                        disabled={u.id === lockedUserId}
                        onChange={(on) => setUsers((cur) => toggleIn(cur, u.id, on))}
                      />
                    ))}
                    {!shownUsers.length ? <div className="mt-empty-opt">No users found</div> : null}
                  </div>
                </>
              )}
            </div>
          </div>
        ) : null}
      </div>
      <div className="mt-modal__foot">
        <button
          type="button"
          className="btn-crm btn-crm--primary"
          id="shareSave"
          disabled={saving || saveBlocked}
          onClick={() => {
            if (nobodyPicked) {
              toast('Choose at least one user or team.', 'danger');
              return;
            }
            onSave({
              mode,
              users: mode === 'specific' ? users : [],
              teams: mode === 'specific' ? teams : [],
            });
          }}
        >
          Save
        </button>
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Cancel
        </button>
      </div>
    </MtModal>
  );
}
