'use client';

import { useEffect, useState } from 'react';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { setConnectionOwner, type Connection } from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DialogHead, SetDialog } from '../settings-ui';
import { useDirectory } from './directory';

/**
 * "Manage app owner" (design #manage-owner-modal, and the detail page's Manage): picks an
 * active member of the business as the app's owner.
 */
export function ChangeOwnerDialog({
  connection,
  onClose,
  onSaved,
}: {
  /** The app whose owner changes; null = closed. */
  connection: Pick<Connection, 'id' | 'name' | 'owner'> | null;
  onClose: () => void;
  onSaved: (c: Connection) => void;
}) {
  const toast = useToast();
  const open = connection !== null;
  const directory = useDirectory(open);
  const [owner, setOwner] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (connection) setOwner(connection.owner?.id ?? '');
  }, [connection]);

  const options = directory.members.map((m) => ({
    value: m.userId,
    label: `${m.name} (${m.email})`,
  }));
  // The current owner may be deactivated: still show who it is.
  if (connection?.owner && !directory.byId.has(connection.owner.id)) {
    options.unshift({
      value: connection.owner.id,
      label: `${connection.owner.name} (${connection.owner.email})`,
    });
  }

  const close = () => {
    if (!busy) onClose();
  };

  const save = async () => {
    if (!connection || busy) return;
    if (!owner || owner === connection.owner?.id) {
      onClose();
      return;
    }
    setBusy(true);
    try {
      const updated = await setConnectionOwner(connection.id, owner);
      const name = updated.owner?.name ?? directory.byId.get(owner)?.name ?? 'the new owner';
      toast(`App owner updated to ${name}`, 'success');
      onSaved(updated);
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <SetDialog
      open={open}
      onClose={close}
      labelledBy="manage-owner-title"
      className="ca-manage-owner-modal"
    >
      <form
        noValidate
        id="manage-owner-form"
        onSubmit={(e) => {
          e.preventDefault();
          void save();
        }}
      >
        <DialogHead id="manage-owner-title" title="Manage app owner" onClose={close} />
        <div className="set-modal__body">
          <p className="crm-text-muted crm-fs-7 crm-mb-4">
            The app owner is the person that owns the app. As the owner they can make changes to the
            app settings that control access and permissions. The app owner can be changed at any
            time.
          </p>
          <div className="field crm-mb-3">
            <label className="field__label" htmlFor="manage-owner-select">
              App owner
            </label>
            <p className="crm-fs-8 crm-text-subtle crm-mb-2">
              Only active users in your account can be app owners.
            </p>
            <CustomSelect
              id="manage-owner-select"
              className="ca-owner-select-wrap crm-w-100"
              placeholder={directory.status === 'loading' ? 'Loading users…' : 'Select an owner'}
              value={owner}
              options={options}
              onChange={setOwner}
              searchable
              disabled={directory.status !== 'ready' || busy}
              menuActions={false}
            />
            {directory.status === 'error' ? (
              <p className="field__help crm-text-danger" role="alert">
                Couldn’t load users. {directory.error}
              </p>
            ) : null}
          </div>
        </div>
        <div className="set-modal__foot">
          <button
            type="submit"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            id="save-owner-btn"
            disabled={busy || !owner}
            aria-busy={busy}
          >
            Save
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
            Cancel
          </button>
        </div>
      </form>
    </SetDialog>
  );
}
