'use client';

import Link from 'next/link';
import { useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  removeUserAppConnection,
  type UserApp,
  type UserAppConnection,
  type UserAppKey,
} from '@/features/integrations/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { DialogHead, SetDialog } from '../settings-ui';
import { connectionsLabel } from './admin-model';
import { connectorFor, connectorSoon, formatDateTime, initials } from './connections';
import { Icon, connectionLogo } from './icons';
import { DesignDropdown } from './ui';
import type { UserAppsState } from './userApps';

const MARKETPLACE_SOON = 'The app marketplace is coming soon';

export function UserAppLogo({ appKey }: { appKey: string }) {
  const logo = connectionLogo({ appKey, type: 'native' });
  return (
    <span className="su-app-row-logo" style={{ background: logo.bg, color: '#ffffff' }}>
      <Icon name={logo.icon} size={16} />
    </span>
  );
}

/**
 * Confirms removing one person's connection (design "Delete connection" / "Uninstall app").
 * Disconnects their Gmail or Google Calendar: they can connect again unless the app's approval
 * stops them.
 */
export function RemoveUserConnectionDialog({
  target,
  onClose,
  onRemoved,
}: {
  target: { appKey: UserAppKey; appName: string; person: UserAppConnection } | null;
  onClose: () => void;
  onRemoved: () => void;
}) {
  const toast = useToast();
  const [busy, setBusy] = useState(false);
  const close = () => {
    if (!busy) onClose();
  };
  const confirm = async () => {
    if (!target || busy) return;
    setBusy(true);
    try {
      await removeUserAppConnection(target.appKey, target.person.userId);
      toast(`Connection deleted for ${target.person.name}`, 'info');
      onRemoved();
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };
  return (
    <SetDialog
      open={target !== null}
      onClose={close}
      labelledBy="admin-user-uninst-title"
      className="ca-admin-user-uninstall-modal"
    >
      <div className="ca-admin-user-uninstall-content">
        <DialogHead id="admin-user-uninst-title" title="Uninstall app" onClose={close} />
        <div className="set-modal__body">
          <p className="crm-fs-7 crm-text-dark crm-mb-4">
            <strong>{target?.person.name}</strong>’s {target?.appName} connection will be
            disconnected. They can connect it again from their own settings if they are still
            allowed to install it.
          </p>
          <div className="crm-d-flex crm-align-items-center crm-gap-2">
            <button
              type="button"
              className={cn('btn-crm btn-crm--danger', busy && 'is-loading')}
              disabled={busy}
              aria-busy={busy}
              onClick={() => void confirm()}
            >
              Uninstall
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--secondary"
              disabled={busy}
              onClick={close}
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    </SetDialog>
  );
}

/** "Connections for <app>" drawer (design #ca-connections-drawer). */
function ConnectionsDrawer({
  app,
  onClose,
  onChanged,
}: {
  app: UserApp | null;
  onClose: () => void;
  onChanged: () => void;
}) {
  const [hideRemoved, setHideRemoved] = useState(false);
  const [removing, setRemoving] = useState<UserAppConnection | null>(null);
  const rows = (app?.connections ?? []).filter((c) => !hideRemoved || !c.removed);
  return (
    <>
      <SetDialog
        open={app !== null}
        onClose={onClose}
        drawer
        labelledBy="ca-connections-title"
        className="ca-connections-drawer"
      >
        <div className="ca-drawer-wrap">
          <DialogHead
            id="ca-connections-title"
            title={
              <>
                Connections for <span>{app?.name}</span>
              </>
            }
            onClose={onClose}
          />
          <div className="set-modal__body">
            <div className="crm-d-flex crm-justify-content-between crm-align-items-center crm-mb-3">
              <span className="crm-fs-7 crm-text-muted">{connectionsLabel(rows.length)}</span>
              <label className="check crm-d-flex crm-align-items-center crm-gap-2">
                <input
                  type="checkbox"
                  checked={hideRemoved}
                  onChange={(e) => setHideRemoved(e.target.checked)}
                />
                <span className="check__box" />
                <span className="crm-fs-8 crm-text-dark">Hide removed users</span>
              </label>
            </div>
            <div className="card set-table-card ca-connections-table-card">
              <table className="set-table su-table ca-connections-table">
                <thead>
                  <tr>
                    <th className="col-user">Connected by</th>
                    <th className="col-date">Installed date</th>
                    <th className="col-action crm-text-end">
                      <span className="crm-visually-hidden">Action</span>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((u) => (
                    <tr key={u.userId}>
                      <td>
                        <div className="crm-d-flex crm-align-items-center crm-gap-2">
                          <span className="avatar avatar--xs avatar--round avatar--brand-xs">
                            {initials(u.name)}
                          </span>
                          <div>
                            <strong className="crm-fs-8 crm-d-block">
                              {u.name}
                              {u.removed ? (
                                <span className="crm-text-subtle crm-fw-normal"> (removed)</span>
                              ) : null}
                            </strong>
                            <span className="crm-fs-8 crm-text-subtle">{u.email}</span>
                            {u.status === 'needs_attention' ? (
                              <span className="crm-d-block crm-fs-8 crm-text-warning">
                                Needs to reconnect
                              </span>
                            ) : null}
                          </div>
                        </div>
                      </td>
                      <td className="crm-fs-8 crm-text-muted">
                        {formatDateTime(u.installedAt, false) || '—'}
                      </td>
                      <td className="crm-text-end">
                        <button
                          type="button"
                          className="icon-btn icon-btn--ghost text-danger"
                          title="Delete connection"
                          aria-label={`Delete ${u.name}’s connection`}
                          onClick={() => setRemoving(u)}
                        >
                          <Icon name="trash" size={14} />
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              {rows.length === 0 ? <p className="su-empty">No connections.</p> : null}
            </div>
          </div>
          <div className="set-modal__foot">
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Close
            </button>
          </div>
        </div>
      </SetDialog>
      <RemoveUserConnectionDialog
        target={
          app && removing ? { appKey: app.appKey, appName: app.name, person: removing } : null
        }
        onClose={() => setRemoving(null)}
        onRemoved={onChanged}
      />
    </>
  );
}

/** "Other apps installed by users in my organization" (design .ca-user-apps-section). */
export function UserAppsSection({
  state,
  reload,
}: {
  state: UserAppsState;
  reload: (quiet?: boolean) => Promise<void>;
}) {
  const [viewing, setViewing] = useState<UserAppKey | null>(null);
  const apps = state.status === 'ready' ? state.apps.filter((a) => a.connections.length > 0) : [];
  const viewingApp =
    state.status === 'ready' ? (apps.find((a) => a.appKey === viewing) ?? null) : null;

  return (
    <div className="set-card ca-user-apps-section crm-mt-4" aria-labelledby="heading-user-apps">
      <div className="set-card__head">
        <h2 id="heading-user-apps" className="set-card__title">
          Other apps installed by users in my organization
        </h2>
      </div>
      <div className="card set-table-card">
        <table className="set-table su-table" id="user-installed-apps-table">
          <thead>
            <tr>
              <th className="col-app">App</th>
              <th className="col-connections">Connections</th>
              <th className="col-actions crm-text-end">
                <span className="crm-visually-hidden">Actions</span>
              </th>
            </tr>
          </thead>
          <tbody>
            {apps.map((a) => {
              const connector = connectorFor(a);
              return (
                <tr key={a.appKey} data-user-app={a.name}>
                  <td>
                    <div className="crm-d-flex crm-align-items-center crm-gap-3">
                      <UserAppLogo appKey={a.appKey} />
                      <button
                        type="button"
                        className="crm-fw-semibold crm-fs-7 link ca-link-btn"
                        onClick={() => setViewing(a.appKey)}
                      >
                        {a.name}
                      </button>
                    </div>
                  </td>
                  <td>
                    <span className="crm-text-body-secondary crm-fs-7">
                      {connectionsLabel(a.connectionCount)}
                    </span>
                  </td>
                  <td className="crm-text-end">
                    <DesignDropdown
                      toggleClassName="btn-crm btn-crm--outline btn-crm--sm"
                      menuClassName="dropdown__menu--right"
                      toggle={
                        <>
                          <span>Actions</span>
                          <Icon name="caret-down" size={14} />
                        </>
                      }
                    >
                      {(close) => (
                        <>
                          <button
                            type="button"
                            className="dropdown__item"
                            onClick={() => {
                              close();
                              setViewing(a.appKey);
                            }}
                          >
                            View connections
                          </button>
                          <button
                            type="button"
                            className="dropdown__item"
                            aria-disabled="true"
                            title={MARKETPLACE_SOON}
                          >
                            View in Marketplace (coming soon)
                          </button>
                          {connector?.href ? (
                            <Link className="dropdown__item" href={connector.href}>
                              Install
                            </Link>
                          ) : (
                            <button
                              type="button"
                              className="dropdown__item"
                              aria-disabled="true"
                              title={connectorSoon(a.name)}
                            >
                              Install (coming soon)
                            </button>
                          )}
                        </>
                      )}
                    </DesignDropdown>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {state.status === 'loading' ? (
          <p className="su-empty" role="status">
            Loading apps…
          </p>
        ) : state.status === 'error' ? (
          <div className="ca-state" role="alert">
            <p className="crm-mb-0">Couldn’t load the apps installed by users. {state.message}</p>
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm"
              onClick={() => void reload()}
            >
              Try again
            </button>
          </div>
        ) : apps.length === 0 ? (
          <p className="su-empty">
            Nobody in your organization has connected Gmail or Google Calendar yet.
          </p>
        ) : null}
      </div>

      <ConnectionsDrawer
        app={viewingApp}
        onClose={() => setViewing(null)}
        onChanged={() => void reload(true)}
      />
    </div>
  );
}
