'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { listPropertyUserValues } from '@/features/custom-properties/api.client';
import { usersOfTeams, userTablePage } from '@/features/custom-properties/crm-user';
import { useTeamOptions } from '@/features/custom-properties/useTeamOptions';
import { useOwners } from '@/features/owners/useOwners';
import { DmIcon } from './icons';
import { CheckFilter } from './primitives';

/**
 * DMG9: the 20 Nov design's CRM user settings in Field type (data-model.js:1176-1195): how many
 * users can be chosen, "Filter users by team", and the users the field can take with how many
 * records hold each. The teams and who is on them come from GET /owners/teams (every member may
 * read it); until they load, or when that fails, the table isn't limited by team.
 */
export function CrmUserFields({
  propertyId,
  objectKey,
  multipleUsers,
  userTeamIds,
  readOnly,
  settingsLinks,
  onChange,
}: {
  /** The saved field (edit), for "With value"; null when creating or cloning. */
  propertyId: string | null;
  objectKey: string;
  multipleUsers: boolean;
  userTeamIds: string[];
  readOnly: boolean;
  /** Settings pages open for the user: "here." is a link, else plain text. */
  settingsLinks: boolean;
  onChange: (patch: { multipleUsers?: boolean; userTeamIds?: string[] }) => void;
}) {
  // Active users only: they are the ones a record can be given.
  const { owners } = useOwners(true, false);
  const loaded = useTeamOptions();
  const teams = loaded ?? [];
  /** userId → records; undefined while loading, null when it failed. */
  const [counts, setCounts] = useState<Map<string, number> | null | undefined>(undefined);
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(1);

  useEffect(() => {
    // A new field has no records yet.
    if (!propertyId) {
      setCounts(new Map());
      return;
    }
    let alive = true;
    setCounts(undefined);
    listPropertyUserValues(propertyId).then(
      (rows) => alive && setCounts(new Map(rows.map((r) => [r.userId, r.records]))),
      () => alive && setCounts(null),
    );
    return () => {
      alive = false;
    };
  }, [propertyId]);

  const teamName = (id: string) => teams.find((t) => t.id === id)?.name ?? id;
  const teamLabel = userTeamIds.length ? userTeamIds.map(teamName).join(', ') : '';
  const rows = useMemo(
    () => usersOfTeams(owners, userTeamIds, loaded).map((o) => ({ name: o.name, id: o.userId })),
    [owners, userTeamIds, loaded],
  );
  const shown = userTablePage(rows, search, page);
  // Owner fields name record owners only on contacts and companies (batch P2b, the API's
  // `record_owner_field_users`); elsewhere the field gives no edit rights.
  const ownerRights = objectKey === 'contact' || objectKey === 'company';

  return (
    <>
      <fieldset className="dm-field dm-pe__fs">
        <legend className="dm-field__label">How many users can be selected? *</legend>
        {(
          [
            [false, 'Only one user can be selected'],
            [true, 'Multiple users can be selected'],
          ] as const
        ).map(([multi, label]) => (
          <label key={label} className="dm-radio">
            <input
              type="radio"
              name="dm-pe-multi"
              value={multi ? '1' : '0'}
              checked={multipleUsers === multi}
              disabled={readOnly}
              onChange={() => onChange({ multipleUsers: multi })}
            />
            <span>{label}</span>
          </label>
        ))}
      </fieldset>
      <div className="dm-field">
        <span className="dm-field__label">Filter users by team</span>
        <span className="dm-field__hint">
          Optionally limit which users can be selected by restricting to specific teams. Leave empty
          to allow all users.
        </span>
        {readOnly ? (
          <div className="dm-select">
            <button type="button" className="dm-select__btn is-ro" disabled>
              <span>{teamLabel || <em className="dm-pe__ph">Select teams</em>}</span>
            </button>
          </div>
        ) : (
          <CheckFilter
            label={teamLabel || 'Select teams'}
            options={[
              ...teams.map((t) => ({ value: t.id, label: t.name })),
              // A chosen team deleted since stays listed, so it can be unticked.
              ...userTeamIds
                .filter((id) => !teams.some((t) => t.id === id))
                .map((id) => ({ value: id, label: id })),
            ]}
            selected={userTeamIds}
            onChange={(next) => {
              onChange({ userTeamIds: next });
              setPage(1);
            }}
            search={teams.length > 6}
            className="dm-pe__teams"
          />
        )}
      </div>
      <p className="dm-pe__text">
        Manage your CRM users and teams{' '}
        {settingsLinks ? (
          <Link href="/settings/users">
            here. <DmIcon name="external" size={12} />
          </Link>
        ) : (
          'here.'
        )}
        {ownerRights
          ? ' Users selected for this property will be treated as record owners, and will have the same edit permissions to the record that an owner would have. Other users on their teams may also be able to edit the record based on their permissions.'
          : null}
      </p>
      <label className="dm-field">
        <span className="dm-field__label">Search options</span>
        <span className="dm-search dm-search--wide">
          <input
            type="search"
            placeholder="Search"
            aria-label="Search users"
            value={search}
            onChange={(e) => {
              setSearch(e.target.value);
              setPage(1);
            }}
          />
          <DmIcon name="search" />
        </span>
      </label>
      <div className="dm-table-wrap">
        <table className="dm-table dm-pe__table">
          <thead>
            <tr>
              <th>Label</th>
              <th>Internal name</th>
              <th className="dm-pe__num">With value</th>
            </tr>
          </thead>
          <tbody>
            {!shown.rows.length && (
              <tr className="dm-table__empty">
                <td colSpan={3}>No users match your search.</td>
              </tr>
            )}
            {shown.rows.map((u) => (
              <tr key={u.id}>
                <td>{u.name}</td>
                <td>
                  <code>{u.id}</code>
                </td>
                <td className="dm-pe__num">{counts ? (counts.get(u.id) ?? 0) : '--'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
      <nav className="dm-pager" aria-label="Users pagination">
        <button
          type="button"
          className="dm-pager__step"
          disabled={shown.page <= 1}
          onClick={() => setPage(shown.page - 1)}
        >
          <DmIcon name="chevron-left" size={14} />
          Prev
        </button>
        <span className="dm-pager__num is-current">{shown.page}</span>
        <button
          type="button"
          className="dm-pager__step"
          disabled={shown.page >= shown.pages}
          onClick={() => setPage(shown.page + 1)}
        >
          Next
          <DmIcon name="chevron-right" size={14} />
        </button>
      </nav>
    </>
  );
}
