'use client';

import { useEffect, useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import {
  listCustomProperties,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import { listObjectDefinitions } from '@/features/objects/api.client';
import type { FieldAccessRule, FieldRules } from '@/features/permission-sets/api.client';
import {
  STANDARD_FIELD_ACCESS,
  type StandardAccessObject,
} from '@/features/permission-sets/field-access';
import { errorText } from '@/lib/api/errors';

/**
 * Field access in the permission set editor (HUB-317, on HUB-316): per object, which fields the
 * set's users see but can't change (View only) or don't see at all (Hidden). No rule: Can edit.
 * Built-in fields (email, amount…) come first, then custom ones. Super admins are never limited.
 * The record's name, owner and stage, and fields the CRM provides, can only be made view-only.
 */

/** One row of the grid: a built-in or custom field. */
interface Row {
  name: string;
  label: string;
  /** Under the label: "Built-in field" or the internal name. */
  sub: string;
  /** Why it can't take every level, if so. */
  note: string | null;
  canHide: boolean;
  /** Its own access setting already hides it from everyone but super admins. */
  fixed: boolean;
}

const BUILT_IN = [
  { key: 'contact', label: 'Contacts' },
  { key: 'company', label: 'Companies' },
  { key: 'deal', label: 'Deals' },
];

type Access = 'edit' | FieldAccessRule;

const ACCESS_LABEL: Record<Access, string> = {
  edit: 'Can edit',
  view: 'View only',
  hidden: 'Hidden',
};

const crmProvided = (f: CustomPropertyDefinition) => Boolean(f.crmProvided || f.system);

/** The rules with one field's access changed; objects without rules are left out. */
function withAccess(rules: FieldRules, object: string, name: string, access: Access): FieldRules {
  const fields = { ...(rules[object] ?? {}) };
  if (access === 'edit') delete fields[name];
  else fields[name] = access;
  const next = { ...rules, [object]: fields };
  if (!Object.keys(fields).length) delete next[object];
  return next;
}

export function FieldAccessGrid({
  value,
  disabled,
  onChange,
}: {
  value: FieldRules;
  disabled: boolean;
  onChange: (next: FieldRules) => void;
}) {
  const [objects, setObjects] = useState(BUILT_IN);
  const [object, setObject] = useState('contact');
  const [fields, setFields] = useState<Record<string, CustomPropertyDefinition[]>>({});
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState('');

  useEffect(() => {
    listObjectDefinitions().then(
      (defs) =>
        setObjects([...BUILT_IN, ...defs.map((d) => ({ key: d.key, label: d.pluralLabel }))]),
      () => undefined,
    );
  }, []);

  useEffect(() => {
    if (fields[object]) return;
    let live = true;
    setError(null);
    listCustomProperties({ objectType: object }).then(
      (list) => {
        if (live) setFields((cur) => ({ ...cur, [object]: list }));
      },
      (err: unknown) => {
        if (live) setError(errorText(err));
      },
    );
    return () => {
      live = false;
    };
  }, [object, fields]);

  const list = fields[object];
  const shown = useMemo(() => {
    const builtIn: Row[] = (STANDARD_FIELD_ACCESS[object as StandardAccessObject] ?? []).map(
      (f) => ({
        name: f.name,
        label: f.label,
        sub: 'Built-in field',
        note: f.hideable ? null : 'Can be made view-only, not hidden',
        canHide: f.hideable,
        fixed: false,
      }),
    );
    const custom: Row[] = (list ?? []).map((f) => ({
      name: f.name,
      label: f.label,
      sub: f.name,
      note:
        f.access === 'super_admins'
          ? 'Only super admins see it (field setting)'
          : f.access === 'everyone_view'
            ? 'Everyone may only view it (field setting)'
            : f.access === 'assigned'
              ? 'Only the users and teams assigned to it see it (field setting)'
              : crmProvided(f)
                ? 'Provided by the CRM: can be made view-only, not hidden'
                : null,
      canHide: !crmProvided(f),
      fixed: f.access === 'super_admins',
    }));
    const q = query.trim().toLowerCase();
    return [...builtIn, ...custom].filter(
      (r) => !q || r.label.toLowerCase().includes(q) || r.name.toLowerCase().includes(q),
    );
  }, [object, list, query]);
  const rules = value[object] ?? {};
  const count = (key: string) => Object.keys(value[key] ?? {}).length;

  return (
    <div className="ps-fields">
      <div className="ps-fields__bar">
        <label className="ps-fields__object">
          <span className="crm-visually-hidden">Object</span>
          <select
            className="input"
            value={object}
            onChange={(e) => {
              setObject(e.target.value);
              setQuery('');
            }}
          >
            {objects.map((o) => (
              <option key={o.key} value={o.key}>
                {o.label}
                {count(o.key) ? ` (${count(o.key)} limited)` : ''}
              </option>
            ))}
          </select>
        </label>
        <label className="settings-nav__search su-search ps-fields__search">
          <span className="crm-visually-hidden">Search fields</span>
          <CrmIcon name="search" className="iconSize-16" />
          <input
            type="search"
            placeholder="Search fields"
            autoComplete="off"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </label>
      </div>
      <div className="set-table-card ps-editor__table ps-fields__table">
        <table className="set-table">
          <thead>
            <tr>
              <th>Field</th>
              <th>Access</th>
            </tr>
          </thead>
          <tbody>
            {shown.map((f) => {
              const access: Access = rules[f.name] ?? 'edit';
              return (
                <tr key={f.name}>
                  <td data-label="Field">
                    <span className="crm-fw-semibold">{f.label}</span>
                    <span className="ps-fields__name">{f.sub}</span>
                    {f.note ? <span className="ps-fields__note">{f.note}</span> : null}
                  </td>
                  <td data-label="Access">
                    <select
                      className="input"
                      aria-label={`Access to ${f.label}`}
                      value={access}
                      disabled={disabled || f.fixed}
                      onChange={(e) =>
                        onChange(withAccess(value, object, f.name, e.target.value as Access))
                      }
                    >
                      {(Object.keys(ACCESS_LABEL) as Access[]).map((a) => (
                        <option
                          key={a}
                          value={a}
                          disabled={a === 'hidden' && !f.canHide && access !== 'hidden'}
                        >
                          {ACCESS_LABEL[a]}
                        </option>
                      ))}
                    </select>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {!shown.length ? (
          <p className="su-empty">
            {error ??
              (list === undefined
                ? 'Loading…'
                : list.length
                  ? 'No fields match your search.'
                  : 'This object has no fields.')}
          </p>
        ) : null}
      </div>
      <p className="field__help">
        View only: the set&apos;s users see the field but can&apos;t change it, on records, in
        imports or through the API. Hidden: they don&apos;t see it on records, lists, filters,
        search, exports, reports or history. Super admins always see and edit every field.
      </p>
    </div>
  );
}
