'use client';

import { useEffect, useMemo, useState } from 'react';
import { MultiCustomSelect } from '@/components/crm/MultiCustomSelect';
import { listServiceKeys } from '@/features/integrations/api.client';
import { listTeamOptions } from '@/features/members/api.client';
import { listOwners } from '@/features/owners/api.client';
import { accessOf, accessSummary, accessToSave, sameAccess } from '@/features/pipelines/access';
import type { Pipeline, PipelineAccess } from '@/features/pipelines/api.client';
import { listAllPrivateApps } from '@/features/private-apps/api.client';
import { SwitchRow } from './primitives';

type Option = { value: string; label: string; sub?: string };

/**
 * DL15a (HubSpot pipeline access; the user's call, 25 Nov 2026, beyond the design): admins limit a
 * Deals, Leads or Tickets pipeline to chosen users, teams and apps. Everyone else doesn't see it
 * or its records. Others see who may use it, read-only.
 */
export function PipelineAccessSection({
  pipeline,
  noun,
  isAdmin,
  busy,
  onSave,
}: {
  pipeline: Pipeline;
  /** "deals". */
  noun: string;
  isAdmin: boolean;
  busy: boolean;
  onSave: (access: PipelineAccess) => void;
}) {
  const saved = accessOf(pipeline);
  const [draft, setDraft] = useState<PipelineAccess>(saved);
  const [options, setOptions] = useState<{ users: Option[]; teams: Option[]; apps: Option[] }>({
    users: [],
    teams: [],
    apps: [],
  });
  const [loadError, setLoadError] = useState(false);

  // A saved change (or another pipeline) resets the draft.
  const savedKey = JSON.stringify(saved);
  useEffect(() => {
    setDraft(JSON.parse(savedKey) as PipelineAccess);
  }, [pipeline.id, savedKey]);

  useEffect(() => {
    if (!isAdmin) return;
    let live = true;
    void Promise.allSettled([
      listOwners({ limit: 200, includeDeactivated: false }),
      listTeamOptions(),
      listAllPrivateApps(),
      listServiceKeys('active'),
    ]).then(([owners, teams, apps, keys]) => {
      if (!live) return;
      setLoadError([owners, teams, apps, keys].some((r) => r.status === 'rejected'));
      setOptions({
        users:
          owners.status === 'fulfilled'
            ? owners.value.data
                .filter((o) => o.active)
                .map((o) => ({ value: o.userId, label: o.name, sub: o.email }))
            : [],
        teams:
          teams.status === 'fulfilled'
            ? teams.value.data.map((t) => ({ value: t.id, label: t.name }))
            : [],
        apps: [
          ...(apps.status === 'fulfilled'
            ? apps.value.map((a) => ({ value: a.id, label: a.name, sub: 'Private app' }))
            : []),
          ...(keys.status === 'fulfilled'
            ? keys.value.map((k) => ({ value: k.id, label: k.name, sub: 'Service key' }))
            : []),
        ],
      });
    });
    return () => {
      live = false;
    };
  }, [isAdmin]);

  const changed = !sameAccess(draft, saved);
  const help = useMemo(
    () =>
      isAdmin
        ? `Only admins and the users, teams and apps you choose see this pipeline and its ${noun}, and can put ${noun} in it.`
        : `Who can see this pipeline and its ${noun}: ${accessSummary(saved)}. Only admins can change this.`,
    [isAdmin, noun, saved],
  );

  return (
    <div className="os-gap-sm">
      <SwitchRow
        label="Limit who can access this pipeline"
        help={help}
        checked={draft.restricted}
        disabled={!isAdmin || busy}
        onChange={(on) => setDraft({ ...draft, restricted: on })}
      />
      {isAdmin && draft.restricted ? (
        <div className="os-gap-sm">
          <div className="field">
            <label className="field__label" htmlFor={`pa-users-${pipeline.id}`}>
              Users
            </label>
            <MultiCustomSelect
              id={`pa-users-${pipeline.id}`}
              placeholder="Choose users"
              value={draft.userIds}
              options={options.users}
              searchable
              disabled={busy}
              selectedText="users"
              onChange={(userIds) => setDraft({ ...draft, userIds })}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor={`pa-teams-${pipeline.id}`}>
              Teams
            </label>
            <MultiCustomSelect
              id={`pa-teams-${pipeline.id}`}
              placeholder="Choose teams"
              value={draft.teamIds}
              options={options.teams}
              searchable
              disabled={busy}
              selectedText="teams"
              onChange={(teamIds) => setDraft({ ...draft, teamIds })}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor={`pa-apps-${pipeline.id}`}>
              Apps and service keys
            </label>
            <MultiCustomSelect
              id={`pa-apps-${pipeline.id}`}
              placeholder="Choose apps"
              value={draft.appIds}
              options={options.apps}
              searchable
              disabled={busy}
              selectedText="apps"
              onChange={(appIds) => setDraft({ ...draft, appIds })}
            />
          </div>
          {loadError ? (
            <p className="os-num-field__err">
              Some users, teams or apps couldn&apos;t be loaded. Reload to try again.
            </p>
          ) : null}
        </div>
      ) : null}
      {isAdmin && changed ? (
        <div className="os-tpl-head">
          <button
            type="button"
            className="btn-crm btn-crm--primary btn-crm--sm"
            disabled={busy}
            onClick={() => onSave(accessToSave(draft))}
          >
            Save access
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm"
            disabled={busy}
            onClick={() => setDraft(saved)}
          >
            Cancel
          </button>
        </div>
      ) : null}
    </div>
  );
}
