'use client';

import { useEffect, useMemo, useState } from 'react';
import { MultiCustomSelect } from '@/components/crm/MultiCustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { listTeamOptions, type TeamOption } from '@/features/members/api.client';
import type { ShareState } from '@/features/message-templates/model';
import { ShareDrawer, type ShareOptions } from '@/features/message-templates/ui/ShareDrawer';
import { listOwners, type Owner } from '@/features/owners/api.client';
import { errorText } from '@/lib/api/errors';
import { updateSequence } from '../api.client';
import type { Sequence, SequenceSharedWith, SequenceVisibility } from '../types';

/** The users and teams a sequence can be shared with: active users, every team. */
function useShareChoices(): { owners: Owner[]; teams: TeamOption[] } {
  const [owners, setOwners] = useState<Owner[]>([]);
  const [teams, setTeams] = useState<TeamOption[]>([]);
  useEffect(() => {
    listOwners({ limit: 200, includeDeactivated: false }).then(
      (res) => setOwners(res.data.filter((o) => o.active)),
      () => setOwners([]),
    );
    listTeamOptions().then(
      (res) => setTeams(res.data),
      () => setTeams([]),
    );
  }, []);
  return { owners, teams };
}

/**
 * #53: "Specific users and teams": who else may use the sequence besides its owner (HubSpot's
 * sharing). A team reaches its members. Shown when the sequence is shared with `specific`.
 */
export function SequenceSharingPickers({
  sharedWith,
  onChange,
  disabled,
  idPrefix,
}: {
  sharedWith: SequenceSharedWith;
  onChange: (next: SequenceSharedWith) => void;
  disabled?: boolean;
  idPrefix: string;
}) {
  const { owners, teams } = useShareChoices();
  const userOptions = useMemo(
    () => owners.map((o) => ({ value: o.userId, label: o.name, sub: o.email })),
    [owners],
  );
  const teamOptions = useMemo(() => teams.map((t) => ({ value: t.id, label: t.name })), [teams]);
  return (
    <div className="seqsh">
      <div className="field">
        <label className="field__label" htmlFor={`${idPrefix}Users`}>
          Users
        </label>
        <MultiCustomSelect
          id={`${idPrefix}Users`}
          placeholder="Choose users"
          value={sharedWith.userIds}
          options={userOptions}
          searchable
          disabled={disabled}
          selectedText="users"
          onChange={(userIds) => onChange({ ...sharedWith, userIds })}
        />
      </div>
      <div className="field">
        <label className="field__label" htmlFor={`${idPrefix}Teams`}>
          Teams
        </label>
        <MultiCustomSelect
          id={`${idPrefix}Teams`}
          placeholder="Choose teams"
          value={sharedWith.teamIds}
          options={teamOptions}
          searchable
          disabled={disabled}
          selectedText="teams"
          onChange={(teamIds) => onChange({ ...sharedWith, teamIds })}
        />
      </div>
      <p className="crm-fs-8 crm-text-muted crm-mb-0">
        The owner and the people in these teams can use the sequence. Admins see every sequence.
      </p>
    </div>
  );
}

/** Design sequences.php: the Private option's tip (Sequences #53). */
export const SEQUENCE_PRIVATE_TIP = 'Only you and super admins can see and use this sequence.';

const MODE_OF: Record<SequenceVisibility, ShareState['mode']> = {
  personal: 'private',
  shared: 'everyone',
  specific: 'specific',
};
const VISIBILITY_OF: Record<ShareState['mode'], SequenceVisibility> = {
  private: 'personal',
  everyone: 'shared',
  specific: 'specific',
};
/** Design sequences-actions.js: "{} are now {}". */
const SHARED_LABEL: Record<ShareState['mode'], string> = {
  private: 'private',
  everyone: 'shared with everyone',
  specific: 'shared with specific users or teams',
};

function shareOf(sequence: Sequence | undefined): ShareState {
  if (!sequence) return { mode: 'private', users: [], teams: [] };
  return {
    mode: MODE_OF[sequence.visibility],
    users: sequence.sharedWith?.userIds ?? [],
    teams: sequence.sharedWith?.teamIds ?? [],
  };
}

/**
 * Sequences #53: the design's "Manage sharing settings" drawer (Private / Everyone / Specific
 * users or teams, with Teams and Users tabs) for one sequence or a selection. A selection starts
 * from its sharing when all its sequences share alike, otherwise from Private.
 */
export function SequenceSharingDrawer({
  sequences,
  onClose,
  onSaved,
}: {
  sequences: Sequence[];
  onClose: () => void;
  /** The sequences as saved (the toast is already shown). */
  onSaved: (updated: Sequence[]) => void;
}) {
  const toast = useToast();
  const { owners, teams } = useShareChoices();
  const [saving, setSaving] = useState(false);
  const options: ShareOptions = useMemo(
    () => ({
      users: owners.map((o) => ({ id: o.userId, name: o.name })),
      teams: teams.map((t) => ({ id: t.id, name: t.name })),
    }),
    [owners, teams],
  );
  const first = sequences[0];
  const alike = sequences.every(
    (s) =>
      s.visibility === first?.visibility &&
      (s.visibility !== 'specific' ||
        JSON.stringify(s.sharedWith) === JSON.stringify(first.sharedWith)),
  );
  const initial = alike ? shareOf(first) : shareOf(undefined);

  const save = async (share: ShareState) => {
    setSaving(true);
    const visibility = VISIBILITY_OF[share.mode];
    const results = await Promise.allSettled(
      sequences.map((s) =>
        updateSequence(s.id, {
          visibility,
          ...(visibility === 'specific'
            ? { sharedWith: { userIds: share.users, teamIds: share.teams } }
            : {}),
          updatedAt: s.updatedAt,
        }),
      ),
    );
    setSaving(false);
    const saved = results.flatMap((r) => (r.status === 'fulfilled' ? [r.value] : []));
    const failed = results.find((r) => r.status === 'rejected');
    if (saved.length) {
      const who =
        sequences.length === 1 ? (first?.name ?? 'This sequence') : `${saved.length} sequences`;
      const verb = saved.length === 1 ? 'is' : 'are';
      toast(`${who} ${verb} now ${SHARED_LABEL[share.mode]}`, 'success');
    }
    if (failed?.status === 'rejected') {
      toast(`${results.length - saved.length} not changed: ${errorText(failed.reason)}`, 'danger', {
        durationMs: 9000,
      });
    }
    if (saved.length) onSaved(saved);
  };

  return (
    <ShareDrawer
      noun="sequence"
      privateTip={SEQUENCE_PRIVATE_TIP}
      lockedUserId={sequences.length === 1 ? first?.ownerId : undefined}
      // A mixed selection starts from Private, which saving as is must still allow.
      saveNeedsChange={alike}
      share={initial}
      options={options}
      saving={saving}
      onClose={saving ? () => {} : onClose}
      onSave={(share) => void save(share)}
    />
  );
}

/** One sequence's Manage sharing (its row's Actions, and the sequence page's Actions). */
export function SharingModal({
  open,
  sequence,
  onClose,
  onSaved,
}: {
  open: boolean;
  sequence: Sequence;
  onClose: () => void;
  onSaved: (updated: Sequence) => void;
}) {
  if (!open) return null;
  return (
    <SequenceSharingDrawer
      sequences={[sequence]}
      onClose={onClose}
      onSaved={(updated) => {
        if (updated[0]) onSaved(updated[0]);
      }}
    />
  );
}
