'use client';

import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import type { NotificationProfile } from '../types';
import {
  PROFILE_CHANNEL_ICONS,
  PROFILE_CHANNEL_TIPS,
  PROFILE_CHANNELS,
  PROFILE_TOPIC_GROUPS,
  type ProfileTopic,
} from './notification-profile-topics';
import { DialogHead, SetDialog } from './settings-ui';

const NEW_PROFILE_PREFIX = 'Unnamed notification profile';

const dayOrdinal = (day: number) => {
  const mod100 = day % 100;
  if (mod100 >= 11 && mod100 <= 13) return `${day}th`;
  if (day % 10 === 1) return `${day}st`;
  if (day % 10 === 2) return `${day}nd`;
  if (day % 10 === 3) return `${day}rd`;
  return `${day}th`;
};

/** "Unnamed notification profile - November 20th, 2026, 4:38:15 pm" */
const unnamedProfileName = (at = new Date()) => {
  const month = at.toLocaleString('en-US', { month: 'long' });
  let hours = at.getHours();
  const suffix = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12 || 12;
  const minute = String(at.getMinutes()).padStart(2, '0');
  const second = String(at.getSeconds()).padStart(2, '0');
  return `${NEW_PROFILE_PREFIX} - ${month} ${dayOrdinal(at.getDate())}, ${at.getFullYear()}, ${hours}:${minute}:${second} ${suffix}`;
};

/** "Sales reps (clone)", trimmed so the stored name stays within 80 characters. */
const cloneProfileName = (name: string) => {
  const suffix = ' (clone)';
  const base = name
    .trim()
    .slice(0, 80 - suffix.length)
    .trimEnd();
  return `${base}${suffix}`;
};

const ALL_TOPICS = PROFILE_TOPIC_GROUPS.flatMap((group) => group.items);

const offers = (topic: ProfileTopic, channel: number) => topic.channels[channel] === '1';
const cellKey = (topic: ProfileTopic, channel: number) => `${topic.key}:${channel}`;

const formatUpdated = (profile: NotificationProfile) => {
  if (!profile.updatedAt) return '—';
  const date = new Date(profile.updatedAt).toLocaleDateString('en-GB', {
    day: 'numeric',
    month: 'short',
    year: 'numeric',
  });
  return profile.updatedBy ? `${date} by ${profile.updatedBy}` : date;
};

function ChannelIcon({ channel, className }: { channel: number; className: string }) {
  return (
    <svg viewBox="0 0 32 32" className={className} aria-hidden="true" focusable="false">
      {PROFILE_CHANNEL_ICONS[channel]?.map((d) => (
        <path key={d} d={d} />
      ))}
    </svg>
  );
}

function Check({
  checked,
  indeterminate = false,
  disabled,
  label,
  onChange,
}: {
  checked: boolean;
  indeterminate?: boolean;
  disabled?: boolean;
  label: string;
  onChange: (checked: boolean) => void;
}) {
  const ref = useRef<HTMLInputElement>(null);
  useEffect(() => {
    if (ref.current) ref.current.indeterminate = indeterminate;
  }, [indeterminate]);
  return (
    <label className="check np-check crm-m-0">
      <input
        ref={ref}
        type="checkbox"
        aria-label={label}
        checked={checked}
        disabled={disabled}
        onChange={(e) => onChange(e.target.checked)}
      />
      <span className="check__box" />
    </label>
  );
}

type Draft = { id: string | null; name: string; off: Set<string> };

function ProfileEditor({
  draft,
  setDraft,
  onBack,
  onSave,
}: {
  draft: Draft;
  setDraft: React.Dispatch<React.SetStateAction<Draft | null>>;
  onBack: () => void;
  onSave: () => void;
}) {
  const [editingTitle, setEditingTitle] = useState(false);
  const [titleText, setTitleText] = useState(draft.name);
  const [noteOpen, setNoteOpen] = useState(true);
  const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
  const titleInput = useRef<HTMLInputElement>(null);
  const openedAs = useRef(draft.name);

  useEffect(() => {
    if (editingTitle) titleInput.current?.select();
  }, [editingTitle]);

  useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => {
      document.body.style.overflow = prev;
    };
  }, []);

  const commitTitle = () => {
    const name = titleText.trim() || openedAs.current;
    setTitleText(name);
    setDraft((d) => (d ? { ...d, name } : d));
    setEditingTitle(false);
  };

  const setCells = (cells: string[], on: boolean) =>
    setDraft((d) => {
      if (!d) return d;
      const off = new Set(d.off);
      for (const c of cells) {
        if (on) off.delete(c);
        else off.add(c);
      }
      return { ...d, off };
    });

  const channelState = (topics: ProfileTopic[], channel: number) => {
    const cells = topics.filter((t) => offers(t, channel)).map((t) => cellKey(t, channel));
    const onCount = cells.filter((c) => !draft.off.has(c)).length;
    return {
      cells,
      checked: cells.length > 0 && onCount === cells.length,
      indeterminate: onCount > 0 && onCount < cells.length,
    };
  };

  const allExpanded = expanded.size === PROFILE_TOPIC_GROUPS.length;
  const allCells = ALL_TOPICS.flatMap((t) =>
    PROFILE_CHANNELS.map((_, ch) => ch)
      .filter((ch) => offers(t, ch))
      .map((ch) => cellKey(t, ch)),
  );

  return (
    <div className="np-subview" id="profile-editor-view" role="dialog" aria-modal="true">
      <header className="np-subview-head">
        <div className="np-subview-head__left">
          <button type="button" className="np-subview-back" id="np-editor-back" onClick={onBack}>
            <CrmIcon name="chevron-left" className="iconSize-16" />
            Back
          </button>
        </div>
        <div className="np-subview-head__center">
          <div className="np-subview-title-edit">
            {editingTitle ? (
              <input
                ref={titleInput}
                type="text"
                className="input np-title-inline-input"
                id="np-profile-title-input"
                aria-label="Notification profile name"
                maxLength={80}
                value={titleText}
                onChange={(e) => setTitleText(e.target.value)}
                onBlur={commitTitle}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') commitTitle();
                  if (e.key === 'Escape') {
                    setTitleText(draft.name);
                    setEditingTitle(false);
                  }
                }}
              />
            ) : (
              <>
                <span className="np-subview-title" id="np-profile-title-display">
                  {draft.name}
                </span>
                <button
                  type="button"
                  className="np-title-edit-btn"
                  id="np-profile-title-edit"
                  title="Rename notification profile"
                  aria-label="Rename notification profile"
                  onClick={() => setEditingTitle(true)}
                >
                  <CrmIcon name="pencil" className="iconSize-16" />
                </button>
              </>
            )}
          </div>
        </div>
        <div className="np-subview-head__right">
          <button type="button" className="np-subview-save" id="np-editor-save" onClick={onSave}>
            Save
          </button>
        </div>
      </header>

      <div className="np-subview-body">
        <div className="np-subview-inner">
          {noteOpen ? (
            <div className="np-note-banner" id="np-note-banner">
              <div className="crm-d-flex crm-align-items-center crm-gap-2">
                <span className="np-note-badge">Note:</span>
                <span className="crm-fs-7">
                  Users can still change their notification preferences at any time. User changes
                  will override the defaults you create here.
                </span>
              </div>
              <button
                type="button"
                className="icon-btn icon-btn--ghost crm-p-0"
                aria-label="Dismiss"
                onClick={() => setNoteOpen(false)}
              >
                <CrmIcon name="x" className="iconSize-16" />
              </button>
            </div>
          ) : null}

          <div className="crm-mb-4">
            <h2 className="crm-fs-4 crm-fw-bold crm-mb-1">Select channels and topics</h2>
            <p className="crm-text-body-secondary crm-mb-0 crm-fs-7">
              Note that you can&apos;t turn off notifications for important messages about their
              account, like status and password reset.
            </p>
          </div>

          <div className="np-channels-container">
            {PROFILE_CHANNELS.map((label, ch) => {
              const state = channelState(ALL_TOPICS, ch);
              return (
                <div key={label} className="np-channel-item">
                  <span className="np-channel-label">{label}</span>
                  <div className="np-channel-icon-card" title={PROFILE_CHANNEL_TIPS[ch]}>
                    <ChannelIcon channel={ch} className="np-channel-svg" />
                  </div>
                  <Check
                    label={`${label} notifications`}
                    checked={state.checked}
                    indeterminate={state.indeterminate}
                    onChange={(on) => setCells(state.cells, on)}
                  />
                </div>
              );
            })}
          </div>

          <div className="crm-mb-3">
            <p className="crm-text-body-secondary crm-mb-2 crm-fs-7">
              Choose what topics matter to them and how they get notified about them.
            </p>
            <div className="crm-d-flex crm-align-items-center crm-gap-2 crm-fs-7">
              <button
                type="button"
                className="link crm-fw-semibold"
                id="np-toggle-all-items"
                onClick={() =>
                  setExpanded(
                    allExpanded ? new Set() : new Set(PROFILE_TOPIC_GROUPS.map((g) => g.name)),
                  )
                }
              >
                {allExpanded ? 'Collapse all items' : 'Expand all items'}
              </button>
              <span className="crm-text-muted">|</span>
              <button
                type="button"
                className="link crm-fw-semibold"
                id="np-toggle-all-preferences"
                onClick={() => setCells(allCells, false)}
              >
                Clear all preferences
              </button>
            </div>
          </div>

          <div className="np-topics-accordion-list" id="np-topics-list">
            {PROFILE_TOPIC_GROUPS.map((group) => {
              const open = expanded.has(group.name);
              const bodyId = `np-topic-${group.name.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
              return (
                <div key={group.name} className={open ? 'np-acc is-open' : 'np-acc'}>
                  <button
                    type="button"
                    className="np-acc__head"
                    aria-expanded={open}
                    aria-controls={bodyId}
                    onClick={() =>
                      setExpanded((prev) => {
                        const next = new Set(prev);
                        if (next.has(group.name)) next.delete(group.name);
                        else next.add(group.name);
                        return next;
                      })
                    }
                  >
                    <span className="np-acc__title-wrap">
                      <CrmIcon name="chevron-right" className="iconSize-14 np-acc__arrow" />
                      <span className="np-acc__title">{group.name}</span>
                    </span>
                  </button>
                  {open ? (
                    <div className="np-acc__body" id={bodyId}>
                      <table className="np-topic-table">
                        <thead>
                          <tr>
                            {PROFILE_CHANNELS.map((label, ch) => {
                              const state = channelState(group.items, ch);
                              return (
                                <th key={label} className="np-channel-col-header">
                                  <div className="crm-d-flex crm-flex-column crm-align-items-center crm-gap-1">
                                    <ChannelIcon channel={ch} className="np-th-svg" />
                                    {state.cells.length > 0 ? (
                                      <Check
                                        label={`${label} for all ${group.name} topics`}
                                        checked={state.checked}
                                        indeterminate={state.indeterminate}
                                        onChange={(on) => setCells(state.cells, on)}
                                      />
                                    ) : (
                                      <span className="crm-text-subtle np-dash">—</span>
                                    )}
                                  </div>
                                </th>
                              );
                            })}
                            <th>NOTIFICATION TOPICS</th>
                          </tr>
                        </thead>
                        <tbody>
                          {group.items.map((topic) => (
                            <tr key={topic.key}>
                              {PROFILE_CHANNELS.map((label, ch) => (
                                <td key={label} className="np-channel-col-cell">
                                  {offers(topic, ch) ? (
                                    <Check
                                      label={`${label}: ${topic.title}`}
                                      checked={!draft.off.has(cellKey(topic, ch))}
                                      onChange={(on) => setCells([cellKey(topic, ch)], on)}
                                    />
                                  ) : (
                                    <span className="crm-text-subtle np-dash">—</span>
                                  )}
                                </td>
                              ))}
                              <td>
                                <strong className="np-topic-title">{topic.title}</strong>
                                <p className="crm-text-muted crm-m-0 np-topic-desc">
                                  {topic.description}
                                </p>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  ) : null}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

/**
 * The account's default notifications (HubSpot: Account Defaults › User Defaults › Notifications ›
 * Manage account defaults): a profile kept with the others under this id, for every user not in a
 * preset profile. It can be edited but not deleted.
 */
export const ACCOUNT_DEFAULTS_PROFILE_ID = 'account-defaults';

/**
 * Account Defaults › Notification Profiles: profiles table, full-page profile
 * editor, and the Update / Clone / Delete dialogs.
 */
export function NotificationProfilesPanel({
  isAdmin,
  profiles,
  currentUserName,
  onSave,
  openAccountDefaults = 0,
}: {
  /** Bumped to open the account defaults editor (User Defaults › Manage account defaults). */
  openAccountDefaults?: number;
  isAdmin: boolean;
  profiles: NotificationProfile[];
  currentUserName: string;
  /** Saves the whole list; resolves `false` when the save failed. */
  onSave: (next: NotificationProfile[]) => Promise<boolean>;
}) {
  const toast = useToast();
  const [draft, setDraft] = useState<Draft | null>(null);
  const [updateOpen, setUpdateOpen] = useState(false);
  const [cloneSource, setCloneSource] = useState<NotificationProfile | null>(null);
  const [cloneName, setCloneName] = useState('');
  const [cloneError, setCloneError] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<NotificationProfile | null>(null);
  const [busy, setBusy] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => setMounted(true), []);

  // Account defaults first, then the newest change.
  const sorted = useMemo(
    () =>
      [...profiles].sort(
        (a, b) =>
          Number(b.id === ACCOUNT_DEFAULTS_PROFILE_ID) -
            Number(a.id === ACCOUNT_DEFAULTS_PROFILE_ID) ||
          (b.updatedAt || '').localeCompare(a.updatedAt || ''),
      ),
    [profiles],
  );

  const stamp = () => ({ updatedAt: new Date().toISOString(), updatedBy: currentUserName });

  const run = async (next: NotificationProfile[], message: string) => {
    setBusy(true);
    const ok = await onSave(next);
    setBusy(false);
    if (ok) toast(message, 'success');
    return ok;
  };

  const confirmUpdate = async () => {
    if (!draft) return;
    const row: NotificationProfile = {
      id: draft.id ?? crypto.randomUUID(),
      name: draft.name.trim() || unnamedProfileName(),
      off: [...draft.off],
      ...stamp(),
    };
    const exists = draft.id !== null && profiles.some((p) => p.id === draft.id);
    const next = exists ? profiles.map((p) => (p.id === draft.id ? row : p)) : [...profiles, row];
    if (await run(next, 'Notification profile saved')) {
      setUpdateOpen(false);
      setDraft(null);
    }
  };

  const confirmClone = async () => {
    if (!cloneSource) return;
    const name = cloneName.trim();
    if (!name) {
      setCloneError(true);
      return;
    }
    const row: NotificationProfile = {
      id: crypto.randomUUID(),
      name,
      off: [...cloneSource.off],
      ...stamp(),
    };
    if (await run([...profiles, row], 'Notification profile cloned')) {
      setCloneSource(null);
      openEditor(row);
    }
  };

  const confirmDelete = async () => {
    if (!deleteTarget) return;
    const next = profiles.filter((p) => p.id !== deleteTarget.id);
    if (await run(next, 'Notification profile deleted')) setDeleteTarget(null);
  };

  const openEditor = (profile: NotificationProfile | null) => {
    setDraft(
      profile
        ? { id: profile.id, name: profile.name, off: new Set(profile.off) }
        : { id: null, name: unnamedProfileName(), off: new Set() },
    );
  };

  const openAccountDefaultsEditor = () => {
    const saved = profiles.find((p) => p.id === ACCOUNT_DEFAULTS_PROFILE_ID);
    setDraft(
      saved
        ? { id: saved.id, name: saved.name, off: new Set(saved.off) }
        : { id: ACCOUNT_DEFAULTS_PROFILE_ID, name: 'Account Defaults', off: new Set() },
    );
  };

  useEffect(() => {
    if (openAccountDefaults > 0 && isAdmin) openAccountDefaultsEditor();
    // Opens on each request only, not when the profiles change.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [openAccountDefaults, isAdmin]);

  const openClone = (profile: NotificationProfile) => {
    setCloneSource(profile);
    setCloneName(cloneProfileName(profile.name));
    setCloneError(false);
  };

  return (
    <>
      <p className="set-intro">These defaults will be used for user defaults and presets.</p>

      <div className="set-block crm-mb-3">
        <h2 className="set-block__title">Notification Profiles</h2>
        <p className="set-block__sub">
          Set notification defaults for a group of users within a preset. To add or edit Presets go
          to{' '}
          <Link className="link" href="/settings/users">
            Presets
          </Link>
          .
        </p>
      </div>

      <button
        type="button"
        className="btn-crm btn-crm--outline crm-mb-4"
        id="btn-create-np"
        disabled={!isAdmin}
        onClick={() => openEditor(null)}
      >
        Create notification profile
      </button>

      {sorted.length > 0 ? (
        <div className="card set-table-card" id="np-table-card">
          <table className="set-table su-table np-table">
            <thead>
              <tr>
                <th style={{ width: '32%' }}>Name</th>
                <th style={{ width: '25%' }}>Assigned to</th>
                <th style={{ width: '30%' }}>Last Updated</th>
                <th className="col-actions" style={{ width: '13%', textAlign: 'right' }}>
                  <span className="crm-visually-hidden">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody id="np-table-rows">
              {sorted.map((profile) => (
                <tr key={profile.id}>
                  <td className="crm-fw-semibold">{profile.name}</td>
                  <td className="crm-text-body-secondary">—</td>
                  <td className="crm-text-body-secondary">{formatUpdated(profile)}</td>
                  <td className="col-actions">
                    {isAdmin ? (
                      <div className="np-row-actions">
                        <button
                          type="button"
                          className="icon-btn icon-btn--ghost"
                          aria-label={`Edit ${profile.name}`}
                          title="Edit"
                          onClick={() => openEditor(profile)}
                        >
                          <CrmIcon name="pencil" className="iconSize-16" />
                        </button>
                        <button
                          type="button"
                          className="icon-btn icon-btn--ghost"
                          aria-label={`Clone ${profile.name}`}
                          title="Clone"
                          onClick={() => openClone(profile)}
                        >
                          <CrmIcon name="copy" className="iconSize-16" />
                        </button>
                        {profile.id === ACCOUNT_DEFAULTS_PROFILE_ID ? null : (
                          <button
                            type="button"
                            className="icon-btn icon-btn--ghost np-row-delete"
                            aria-label={`Delete ${profile.name}`}
                            title="Delete"
                            onClick={() => setDeleteTarget(profile)}
                          >
                            <CrmIcon name="trash" className="iconSize-16" />
                          </button>
                        )}
                      </div>
                    ) : null}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      ) : null}

      {mounted && draft
        ? createPortal(
            <ProfileEditor
              key={draft.id ?? 'new'}
              draft={draft}
              setDraft={setDraft}
              onBack={() => setDraft(null)}
              onSave={() => setUpdateOpen(true)}
            />,
            document.body,
          )
        : null}

      <SetDialog
        open={updateOpen}
        onClose={() => setUpdateOpen(false)}
        labelledBy="update-dialog-title"
        id="update-profile-dialog"
      >
        <DialogHead
          id="update-dialog-title"
          title="Update notification profile"
          onClose={() => setUpdateOpen(false)}
        />
        <div className="set-modal__body">
          <p className="crm-text-body">
            The notification profile will be saved. To apply these settings, add the profile to a
            preset.
          </p>
        </div>
        <div className="set-modal__foot">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            id="btn-confirm-update"
            disabled={busy}
            onClick={() => void confirmUpdate()}
          >
            Update notification profile
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setUpdateOpen(false)}
          >
            Cancel
          </button>
        </div>
      </SetDialog>

      <SetDialog
        open={cloneSource !== null}
        onClose={() => setCloneSource(null)}
        labelledBy="clone-dialog-title"
        id="clone-profile-dialog"
      >
        <form
          id="clone-profile-form"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void confirmClone();
          }}
        >
          <DialogHead
            id="clone-dialog-title"
            title="Clone this notification profile"
            onClose={() => setCloneSource(null)}
          />
          <div className="set-modal__body">
            <div className={cloneError ? 'field is-invalid' : 'field'}>
              <label className="field__label" htmlFor="clone-profile-name">
                Choose a name for the new cloned notification profile{' '}
                <span className="field__req">*</span>
              </label>
              <input
                className="input"
                id="clone-profile-name"
                maxLength={80}
                value={cloneName}
                aria-invalid={cloneError}
                onChange={(e) => {
                  setCloneName(e.target.value);
                  if (e.target.value.trim()) setCloneError(false);
                }}
              />
              {cloneError ? <p className="field__error">Enter a profile name</p> : null}
            </div>
          </div>
          <div className="set-modal__foot">
            <button type="submit" className="btn-crm btn-crm--primary" disabled={busy}>
              Clone
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setCloneSource(null)}
            >
              Cancel
            </button>
          </div>
        </form>
      </SetDialog>

      <SetDialog
        open={deleteTarget !== null}
        onClose={() => setDeleteTarget(null)}
        labelledBy="delete-dialog-title"
        id="delete-profile-dialog"
      >
        <DialogHead
          id="delete-dialog-title"
          title="Delete notification profile?"
          onClose={() => setDeleteTarget(null)}
        />
        <div className="set-modal__body">
          <p className="crm-text-body" id="delete-dialog-message">
            Deleting the <strong id="delete-profile-name-text">{deleteTarget?.name}</strong> profile
            will permanently remove it from your account and this can&apos;t be undone. This will
            not change any existing user&apos;s notifications sets.
          </p>
        </div>
        <div className="set-modal__foot">
          <button
            type="button"
            className="btn-crm btn-crm--danger"
            id="btn-confirm-delete"
            disabled={busy}
            onClick={() => void confirmDelete()}
          >
            Delete
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            onClick={() => setDeleteTarget(null)}
          >
            Cancel
          </button>
        </div>
      </SetDialog>
    </>
  );
}
