'use client';

/**
 * Settings > Properties > Groups (HUB-252), as the design: the object's live field groups with
 * how many properties each holds, sortable; Edit (rename), View properties and Delete on hover.
 * Deleting a group that still has properties moves them to another group first. Archived
 * groups are listed apart and can be restored. A group's name never changes (fields point at
 * it); its label does.
 */
import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  updateCustomProperty,
  type CustomPropertyDefinition,
} from '@/features/custom-properties/api.client';
import {
  createPropertyGroup,
  setPropertyGroupArchived,
  setStandardPropertyGroup,
  updatePropertyGroup,
  type PropertyGroup,
} from '@/features/data-model/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { groupDeleteText } from '../groupDelete';
import { Ico, PpModal } from './properties-ui';

type SortKey = 'name' | 'count';

export function PropertyGroupsTab({
  objectType,
  groups,
  properties,
  canManage,
  onChanged,
  onView,
}: {
  objectType: string;
  /** Archived ones included. */
  groups: PropertyGroup[];
  /** The object's fields, built-in ones included (they carry their group's label). */
  properties: CustomPropertyDefinition[];
  canManage: boolean;
  onChanged: () => Promise<void> | void;
  /** "View properties": the Properties tab filtered to the group. */
  onView: (groupName: string) => void;
}) {
  const toast = useToast();
  const [sort, setSort] = useState<{ key: SortKey; dir: 'asc' | 'desc' }>({
    key: 'count',
    dir: 'desc',
  });
  const [naming, setNaming] = useState<{ group: PropertyGroup | null; label: string } | null>(null);
  const [deleting, setDeleting] = useState<PropertyGroup | null>(null);
  const [moveTo, setMoveTo] = useState('');
  const [showArchived, setShowArchived] = useState(false);

  const membersOf = (g: PropertyGroup) =>
    properties.filter(
      (p) => !p.archived && (p.groupName === g.name || (p.standard && p.groupName === g.label)),
    );
  const live = groups.filter((g) => !g.archived);
  const archived = groups.filter((g) => g.archived);
  const d = sort.dir === 'asc' ? 1 : -1;
  const rows = live
    .map((g) => ({ g, count: membersOf(g).length }))
    .sort(
      (a, b) =>
        (sort.key === 'count' ? a.count - b.count : a.g.label.localeCompare(b.g.label)) * d ||
        a.g.label.localeCompare(b.g.label),
    );

  const taken = (label: string, except?: PropertyGroup | null) =>
    live.some(
      (g) => g.id !== except?.id && g.label.trim().toLowerCase() === label.trim().toLowerCase(),
    );

  const th = (key: SortKey, text: string) => {
    const on = sort.key === key;
    return (
      <th
        scope="col"
        className={key === 'count' ? 'pp-num' : undefined}
        aria-sort={on ? (sort.dir === 'asc' ? 'ascending' : 'descending') : 'none'}
      >
        <button
          type="button"
          className={cn('pp-sort', on && 'is-on')}
          onClick={() => setSort({ key, dir: on && sort.dir === 'asc' ? 'desc' : 'asc' })}
        >
          {text}
          <Ico name={on ? (sort.dir === 'asc' ? 'up' : 'down') : 'sort'} className="pp-sorti" />
        </button>
      </th>
    );
  };

  const restore = async (g: PropertyGroup) => {
    try {
      await setPropertyGroupArchived(g.id, false);
      toast(`${g.label} restored`, 'success');
      await onChanged();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const members = deleting ? membersOf(deleting) : [];
  const text = groupDeleteText(members.length);
  const others = deleting
    ? live.filter((g) => g.id !== deleting.id).sort((a, b) => a.label.localeCompare(b.label))
    : [];

  return (
    <>
      <div className="pp-toolbar pp-toolbar--end">
        <button
          type="button"
          className="pp-btn pp-btn--primary"
          disabled={!canManage}
          onClick={() => setNaming({ group: null, label: '' })}
        >
          Create group
        </button>
      </div>
      <div className="pp-tablewrap">
        <table className="pp-table pp-table--groups">
          <thead>
            <tr>
              {th('name', 'Name')}
              {th('count', 'Number of properties')}
            </tr>
          </thead>
          <tbody>
            {rows.map(({ g, count }) => (
              <tr key={g.id}>
                <td>
                  <div className="pp-grow">
                    <span>{g.label}</span>
                    <span className="pp-rowacts pp-rowacts--hover">
                      <button
                        type="button"
                        className="pp-btn pp-btn--outline pp-btn--xs"
                        disabled={!canManage}
                        onClick={() => setNaming({ group: g, label: g.label })}
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        className="pp-btn pp-btn--outline pp-btn--xs"
                        onClick={() => onView(g.name)}
                      >
                        View properties
                      </button>
                      <button
                        type="button"
                        className="pp-btn pp-btn--outline pp-btn--xs"
                        disabled={!canManage}
                        onClick={() => {
                          setMoveTo('');
                          setDeleting(g);
                        }}
                      >
                        Delete
                      </button>
                    </span>
                  </div>
                </td>
                <td className="pp-num">{count}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {rows.length === 0 && (
          <div className="pp-empty">
            <p>This object has no property groups yet.</p>
          </div>
        )}
      </div>

      {archived.length > 0 && (
        <>
          <p className="pp-p crm-mt-3">
            <button
              type="button"
              className="pp-textlink"
              aria-expanded={showArchived}
              onClick={() => setShowArchived((v) => !v)}
            >
              {showArchived ? 'Hide' : 'Show'} archived groups ({archived.length})
            </button>
          </p>
          {showArchived && (
            <div className="pp-tablewrap">
              <table className="pp-table pp-table--groups">
                <thead>
                  <tr>
                    <th scope="col">Archived group</th>
                    <th scope="col" className="pp-num">
                      Number of properties
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {archived
                    .slice()
                    .sort((a, b) => a.label.localeCompare(b.label))
                    .map((g) => (
                      <tr key={g.id}>
                        <td>
                          <div className="pp-grow">
                            <span>{g.label}</span>
                            <span className="pp-rowacts pp-rowacts--hover">
                              <button
                                type="button"
                                className="pp-btn pp-btn--pill pp-btn--xs pp-btn--soft"
                                disabled={!canManage}
                                onClick={() => void restore(g)}
                              >
                                Restore
                              </button>
                            </span>
                          </div>
                        </td>
                        <td className="pp-num">{membersOf(g).length}</td>
                      </tr>
                    ))}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}

      {naming && (
        <PpModal
          title={naming.group ? 'Edit property group' : 'Create property group'}
          okLabel="Save"
          onClose={() => setNaming(null)}
          onOk={async () => {
            const label = naming.label.trim();
            if (!label) return false;
            if (taken(label, naming.group)) {
              toast('A group with this name already exists.', 'danger');
              return false;
            }
            try {
              if (naming.group) await updatePropertyGroup(naming.group.id, { label });
              else await createPropertyGroup({ objectType, label });
              toast(naming.group ? 'Group renamed' : 'Group created', 'success');
              await onChanged();
            } catch (err) {
              toast(errorText(err), 'danger');
              return false;
            }
          }}
        >
          <p className="pp-p">
            You can create custom property groups to better organize any custom properties for each
            object.
          </p>
          <label className="pp-field">
            <span className="pp-label">Name</span>
            <input
              className="pp-input"
              maxLength={100}
              autoFocus
              value={naming.label}
              onChange={(e) => setNaming({ ...naming, label: e.target.value })}
            />
          </label>
          {naming.group && (
            <p className="pp-help">
              Its internal name ({naming.group.name}) stays the same, so its properties keep it.
            </p>
          )}
        </PpModal>
      )}

      {deleting && (
        <PpModal
          title={`Delete ${deleting.label}?`}
          okLabel={members.length ? 'Move and delete' : 'Delete'}
          danger
          onClose={() => setDeleting(null)}
          onOk={async () => {
            if (members.length && !moveTo) {
              toast(others.length ? text.choose : text.onlyGroup, 'danger');
              return false;
            }
            // One move at a time, then the archive. Moving is repeatable, so after a failure
            // the user can just try again; the toast says how far it got.
            let moved = 0;
            try {
              for (const p of members) {
                if (p.standard) await setStandardPropertyGroup(objectType, p.name, moveTo);
                else await updateCustomProperty(p.id, { groupName: moveTo });
                moved++;
              }
              await setPropertyGroupArchived(deleting.id, true);
              const to = others.find((g) => g.name === moveTo)?.label;
              toast(text.deleted(deleting.label, to), 'success');
              await onChanged();
            } catch (err) {
              toast(text.failed(moved, errorText(err)), 'danger');
              if (moved) await onChanged();
              return false;
            }
          }}
        >
          {members.length && !others.length ? (
            <p className="pp-p">{text.onlyGroup}</p>
          ) : members.length ? (
            <>
              <p className="pp-p">{text.body}</p>
              <label className="pp-field">
                <span className="pp-label">{text.moveLabel}</span>
                <select
                  className="pp-input"
                  value={moveTo}
                  onChange={(e) => setMoveTo(e.target.value)}
                >
                  <option value="" disabled>
                    Choose a group
                  </option>
                  {others.map((g) => (
                    <option key={g.id} value={g.name}>
                      {g.label}
                    </option>
                  ))}
                </select>
              </label>
            </>
          ) : (
            <p className="pp-p">This group has no properties.</p>
          )}
        </PpModal>
      )}
    </>
  );
}
