'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import {
  assignUserAccessPresetMembers,
  createUserAccessPreset,
  deleteUserAccessPreset,
  listUserAccessPresets,
  SEAT_OPTIONS,
  updateUserAccessPreset,
  type Member,
  type SeatType,
  type Team,
  type UserAccessPreset,
} from '@/features/members/api.client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

const SEAT_LABEL = Object.fromEntries(SEAT_OPTIONS.map((o) => [o.value, o.label])) as Record<
  SeatType,
  string
>;

type AppliesItem =
  { kind: 'user'; id: string; label: string } | { kind: 'team'; id: string; label: string };

const HOMEPAGE_OPTIONS = [
  { value: 'contacts', label: 'Contacts' },
  { value: 'deals', label: 'Deals & Pipeline' },
  { value: 'reports', label: 'Sales Dashboard' },
  { value: 'tasks', label: 'Tasks Overview' },
] as const;

const LANGUAGE_OPTIONS = [
  { value: 'en', label: 'English (US)' },
  { value: 'es', label: 'Spanish' },
  { value: 'fr', label: 'French' },
  { value: 'de', label: 'German' },
] as const;

type EditorState = {
  mode: 'create' | 'edit';
  preset?: UserAccessPreset;
  name: string;
  /** Kept for API; not shown in the design Setup > General fields. */
  seat: SeatType;
  permissionSetId: string;
  defaultTeamId: string;
  homepage: string;
  language: string;
  applies: AppliesItem[];
  tab: 'setup' | 'users-teams';
  setupSubtab: 'general' | 'signature' | 'notifications';
  sigOn: boolean;
  sigText: string;
  notifyDigest: boolean;
  notifyLeads: boolean;
};

function editorSnapshot(editor: EditorState): string {
  return JSON.stringify({
    name: editor.name.trim(),
    seat: editor.seat,
    permissionSetId: editor.permissionSetId,
    defaultTeamId: editor.defaultTeamId,
    homepage: editor.homepage,
    language: editor.language,
    applies: editor.applies.map((item) => `${item.kind}:${item.id}`).sort(),
    sigOn: editor.sigOn,
    sigText: editor.sigText,
    notifyDigest: editor.notifyDigest,
    notifyLeads: editor.notifyLeads,
  });
}

const EMPTY_EDITOR = (mode: 'create' | 'edit' = 'create'): EditorState => ({
  mode,
  name: mode === 'create' ? 'Standard Sales Preset' : '',
  seat: 'core',
  permissionSetId: '',
  defaultTeamId: '',
  homepage: 'contacts',
  language: 'en',
  applies: [],
  tab: 'setup',
  setupSubtab: 'general',
  sigOn: false,
  sigText: '',
  notifyDigest: true,
  notifyLeads: true,
});

function PencilIcon() {
  return (
    <svg
      className="icon iconSize-14"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
      focusable={false}
    >
      <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z" />
    </svg>
  );
}

function PresetEmptyArt() {
  return (
    <svg className="preset-empty__art" viewBox="0 0 220 180" aria-hidden focusable="false">
      <ellipse cx="110" cy="164" rx="86" ry="10" fill="var(--surface-3)" />
      <rect x="34" y="118" width="150" height="34" rx="8" fill="var(--accent)" />
      <rect x="40" y="124" width="138" height="8" rx="4" fill="var(--surface)" opacity=".85" />
      <rect x="46" y="86" width="132" height="34" rx="8" fill="var(--brand)" />
      <rect x="52" y="92" width="120" height="8" rx="4" fill="var(--surface)" opacity=".85" />
      <rect x="58" y="56" width="110" height="32" rx="8" fill="var(--teal)" />
      <rect x="64" y="62" width="98" height="8" rx="4" fill="var(--surface)" opacity=".85" />
      <circle cx="78" cy="34" r="20" fill="var(--pink-bg)" stroke="var(--pink)" strokeWidth="3" />
      <circle cx="78" cy="29" r="6" fill="var(--pink)" />
      <path d="M66 46c3-7 21-7 24 0" fill="var(--pink)" />
      <circle
        cx="146"
        cy="30"
        r="20"
        fill="var(--indigo-bg)"
        stroke="var(--indigo)"
        strokeWidth="3"
      />
      <circle cx="146" cy="25" r="6" fill="var(--indigo)" />
      <path d="M134 42c3-7 21-7 24 0" fill="var(--indigo)" />
      <circle
        cx="112"
        cy="58"
        r="16"
        fill="var(--yellow-bg)"
        stroke="var(--yellow)"
        strokeWidth="3"
      />
      <circle cx="112" cy="54" r="5" fill="var(--yellow)" />
      <path d="M102 68c3-6 17-6 20 0" fill="var(--yellow)" />
    </svg>
  );
}

export function PresetsTab({
  members,
  teams,
  permissionSets,
  canManage,
  onMembersChanged,
  openPresetId,
  onOpenPresetHandled,
}: {
  members: Member[];
  teams: Team[];
  permissionSets: Array<{ id: string; name: string }>;
  canManage: boolean;
  onMembersChanged?: () => void;
  /** #455: open this preset's editor when the Users row menu asks. */
  openPresetId?: string | null;
  onOpenPresetHandled?: () => void;
}) {
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const [presets, setPresets] = useState<UserAccessPreset[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editor, setEditor] = useState<EditorState | null>(null);
  const [savedSnap, setSavedSnap] = useState('');
  const [renaming, setRenaming] = useState(false);
  const [saving, setSaving] = useState(false);
  const [pickerValue, setPickerValue] = useState('');

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const result = await listUserAccessPresets();
      setPresets(result.data);
      setError(null);
    } catch (err) {
      setError(errorText(err));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load]);

  useEffect(() => {
    const open = Boolean(editor);
    document.body.classList.toggle('ut-subview-open', open);
    document.querySelector('.settings')?.classList.toggle('ut-subview-open', open);
    return () => {
      document.body.classList.remove('ut-subview-open');
      document.querySelector('.settings')?.classList.remove('ut-subview-open');
    };
  }, [editor]);

  const openCreate = () => {
    const next = EMPTY_EDITOR('create');
    setRenaming(false);
    setPickerValue('');
    setSavedSnap(editorSnapshot(next));
    setEditor(next);
  };

  const openEdit = useCallback(
    (preset: UserAccessPreset) => {
      const applies: AppliesItem[] = members
        .filter((m) => m.status === 'active' && m.accessPresetId === preset.id)
        .map((m) => ({ kind: 'user', id: m.userId, label: `${m.name} (${m.email})` }));
      const next: EditorState = {
        ...EMPTY_EDITOR('edit'),
        mode: 'edit',
        preset,
        name: preset.name,
        seat: preset.seat,
        permissionSetId: preset.permissionSetId ?? '',
        defaultTeamId: preset.defaultTeamId ?? '',
        homepage: 'contacts',
        language: 'en',
        applies,
      };
      setRenaming(false);
      setPickerValue('');
      setSavedSnap(editorSnapshot(next));
      setEditor(next);
    },
    [members],
  );

  const closeEditor = () => {
    setEditor(null);
    setRenaming(false);
    setPickerValue('');
  };

  const requestClose = async () => {
    if (editor && editorSnapshot(editor) !== savedSnap) {
      const ok = await confirm({
        title: 'Discard changes?',
        message: 'You have unsaved changes on this preset. Leave without saving?',
        confirmLabel: 'Discard',
        danger: true,
      });
      if (!ok) return;
    }
    closeEditor();
  };

  useEffect(() => {
    if (!openPresetId || loading) return;
    const preset = presets.find((item) => item.id === openPresetId);
    if (preset) openEdit(preset);
    else toast('That preset is no longer on this account.', 'info');
    onOpenPresetHandled?.();
  }, [openPresetId, loading, presets, onOpenPresetHandled, toast, openEdit]);

  const resolveUserIds = (applies: AppliesItem[]): string[] => {
    const ids = new Set<string>();
    for (const item of applies) {
      if (item.kind === 'user') ids.add(item.id);
      else {
        const team = teams.find((t) => t.id === item.id);
        for (const id of team?.memberIds ?? []) ids.add(id);
      }
    }
    return [...ids];
  };

  const onSave = async () => {
    if (!editor || saving || !canManage) return;
    const name = editor.name.trim() || (editor.mode === 'create' ? 'New Preset' : '');
    if (!name) {
      toast('Enter a preset name.', 'danger');
      return;
    }
    setSaving(true);
    try {
      const body = {
        name,
        seat: editor.seat,
        permissionSetId: editor.permissionSetId || null,
        defaultTeamId: editor.defaultTeamId || null,
      };
      let presetId = editor.preset?.id;
      if (editor.mode === 'create') {
        const created = await createUserAccessPreset(body);
        presetId = created.id;
        toast(`Preset "${name}" created.`, 'success');
      } else if (editor.preset) {
        await updateUserAccessPreset(editor.preset.id, body);
        toast(`Preset "${name}" saved.`, 'success');
      }
      if (presetId) {
        await assignUserAccessPresetMembers(presetId, {
          userIds: resolveUserIds(editor.applies),
        });
        onMembersChanged?.();
      }
      closeEditor();
      await load();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setSaving(false);
    }
  };

  const onDelete = async (preset: UserAccessPreset) => {
    const ok = await confirm({
      title: 'Delete preset?',
      message: `Delete "${preset.name}"? Users keep their current seat and permissions.`,
      confirmLabel: 'Delete',
      danger: true,
    });
    if (!ok) return;
    try {
      await deleteUserAccessPreset(preset.id);
      toast(`Preset "${preset.name}" deleted.`, 'success');
      await load();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const pickerOptions = useMemo(() => {
    const used = new Set(editor?.applies.map((a) => `${a.kind}:${a.id}`) ?? []);
    return [
      { value: '', label: 'Search users or teams' },
      ...teams
        .filter((t) => !used.has(`team:${t.id}`))
        .map((t) => ({ value: `team:${t.id}`, label: `${t.name} (Team)` })),
      ...members
        .filter((m) => m.status === 'active' && !used.has(`user:${m.userId}`))
        .map((m) => ({
          value: `user:${m.userId}`,
          label: `${m.name} (${m.email})`,
        })),
    ];
  }, [editor?.applies, members, teams]);

  const addApplies = (value: string) => {
    if (!value || !editor) return;
    const [kind, id] = value.split(':') as ['user' | 'team', string];
    if (!kind || !id) return;
    if (editor.applies.some((a) => a.kind === kind && a.id === id)) {
      setPickerValue('');
      return;
    }
    const label =
      kind === 'team'
        ? `${teams.find((t) => t.id === id)?.name ?? 'Team'} (Team)`
        : (() => {
            const m = members.find((x) => x.userId === id);
            return m ? `${m.name} (${m.email})` : 'User';
          })();
    setEditor({
      ...editor,
      applies: [...editor.applies, { kind, id, label }],
    });
    setPickerValue('');
  };

  if (loading) {
    return (
      <section role="tabpanel">
        <p className="crm-text-body-secondary">Loading presets…</p>
      </section>
    );
  }

  if (error) {
    return (
      <section role="tabpanel">
        <p className="crm-text-danger">{error}</p>
      </section>
    );
  }

  return (
    <section role="tabpanel">
      {presets.length === 0 ? (
        <div className="preset-empty" data-r-empty="">
          <div className="preset-empty__text">
            <h2 className="preset-empty__title">Set preferences for a large group of users</h2>
            <p>
              Presets let you manage users all in one place. Here you can preset user preferences
              for everyone to have the same access.
            </p>
            <a className="link ut-ext" href="#">
              Learn more about presets
              <CrmIcon name="external" className="iconSize-14" />
            </a>
            <div>
              <button
                type="button"
                className="btn-crm btn-crm--primary crm-mt-3"
                disabled={!canManage}
                onClick={openCreate}
              >
                Create preset
              </button>
            </div>
          </div>
          <PresetEmptyArt />
        </div>
      ) : (
        <div data-r-list="">
          <p className="ut-lead">
            Presets let you manage users all in one place. Set seat, permissions and team once, then
            apply the preset to new users.
          </p>
          <div className="ut-actions-row">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={!canManage}
              onClick={openCreate}
            >
              Create preset
            </button>
          </div>
          <div className="ut-shell">
            <div className="lp-tablewrap" data-presets-tablewrap="">
              <table className="lp-table rs-table">
                <thead>
                  <tr>
                    <th className="lp-th">Preset</th>
                    <th className="lp-th">Seat</th>
                    <th className="lp-th">Permission set</th>
                    <th className="lp-th">Default team</th>
                    <th className="lp-th">Users</th>
                    <th className="lp-th col-actions">
                      <span className="crm-visually-hidden">Actions</span>
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {presets.map((preset) => (
                    <tr key={preset.id} className="lp-tr">
                      <td className="lp-td crm-fw-semibold">{preset.name}</td>
                      <td className="lp-td">{SEAT_LABEL[preset.seat]}</td>
                      <td className="lp-td">
                        {preset.permissionSetName ?? (
                          <span className="crm-text-body-secondary">--</span>
                        )}
                      </td>
                      <td className="lp-td">
                        {preset.defaultTeamName ?? (
                          <span className="crm-text-body-secondary">--</span>
                        )}
                      </td>
                      <td className="lp-td">{preset.userCount}</td>
                      <td className="lp-td col-actions">
                        <span className="crm-d-inline-flex" style={{ gap: 14 }}>
                          <button
                            type="button"
                            className="link"
                            disabled={!canManage}
                            onClick={() => openEdit(preset)}
                          >
                            Edit
                          </button>
                          <button
                            type="button"
                            className="link ut-danger"
                            disabled={!canManage}
                            onClick={() => void onDelete(preset)}
                          >
                            Delete
                          </button>
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {editor ? (
        <div className="ut-subview" id="preset-subview">
          <header className="ut-subview-head">
            <div className="ut-subview-head__left">
              <button type="button" className="ut-subview-back" onClick={() => void requestClose()}>
                <CrmIcon name="chevron-left" className="iconSize-16" /> Back
              </button>
            </div>
            <div className="ut-subview-head__center">
              <div className="ut-subview-title-edit">
                {renaming ? (
                  <input
                    type="text"
                    className="input ut-title-inline-input"
                    value={editor.name}
                    maxLength={60}
                    autoFocus
                    onChange={(e) => setEditor({ ...editor, name: e.target.value })}
                    onBlur={() => {
                      setEditor((e) =>
                        e
                          ? {
                              ...e,
                              name:
                                e.name.trim() ||
                                (e.mode === 'create' ? 'Standard Sales Preset' : e.name),
                            }
                          : e,
                      );
                      setRenaming(false);
                    }}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') (e.target as HTMLInputElement).blur();
                    }}
                  />
                ) : (
                  <>
                    <span className="ut-subview-title">{editor.name}</span>
                    <button
                      type="button"
                      className="ut-title-edit-btn"
                      title="Rename preset"
                      onClick={() => setRenaming(true)}
                    >
                      <PencilIcon />
                    </button>
                  </>
                )}
              </div>
            </div>
            <div className="ut-subview-head__right">
              <button
                type="button"
                className="ut-subview-save"
                disabled={!canManage || saving}
                onClick={() => void onSave()}
              >
                {saving ? 'Saving…' : 'Save preset'}
              </button>
            </div>
          </header>

          <nav className="ut-subview-tabs" role="tablist">
            <button
              type="button"
              className={cn('ut-subview-tab', editor.tab === 'setup' && 'active')}
              role="tab"
              aria-selected={editor.tab === 'setup'}
              onClick={() => setEditor({ ...editor, tab: 'setup' })}
            >
              Setup
            </button>
            <button
              type="button"
              className={cn('ut-subview-tab', editor.tab === 'users-teams' && 'active')}
              role="tab"
              aria-selected={editor.tab === 'users-teams'}
              onClick={() => setEditor({ ...editor, tab: 'users-teams' })}
            >
              Users &amp; Teams
            </button>
          </nav>

          <div className="ut-subview-body">
            <div
              className={cn('ut-subview-pane', editor.tab === 'setup' && 'is-active')}
              data-preset-pane="setup"
            >
              <div className="ut-pane-intro">
                <h2 className="ut-pane-title">Setup</h2>
                <p className="ut-pane-desc">
                  Users can change their default preferences at any time. User changes will override
                  the preset defaults.
                </p>
              </div>

              <nav className="set-tabs set-tabs--sm crm-mb-4" role="tablist">
                <button
                  type="button"
                  className={cn('set-tab', editor.setupSubtab === 'general' && 'active')}
                  data-preset-subtab="general"
                  onClick={() => setEditor({ ...editor, setupSubtab: 'general' })}
                >
                  General
                </button>
                <button
                  type="button"
                  className={cn('set-tab', editor.setupSubtab === 'signature' && 'active')}
                  data-preset-subtab="signature"
                  onClick={() => setEditor({ ...editor, setupSubtab: 'signature' })}
                >
                  Email Signature
                </button>
                <button
                  type="button"
                  className={cn('set-tab', editor.setupSubtab === 'notifications' && 'active')}
                  data-preset-subtab="notifications"
                  onClick={() => setEditor({ ...editor, setupSubtab: 'notifications' })}
                >
                  Notifications
                </button>
              </nav>

              <div
                className={cn('ut-preset-subpane', editor.setupSubtab === 'general' && 'is-active')}
                data-preset-subpane="general"
                hidden={editor.setupSubtab !== 'general'}
              >
                <div className="card crm-p-4">
                  <div className="field crm-mb-3">
                    <label className="field__label">Default Homepage / Dashboard</label>
                    <CustomSelect
                      placeholder="Default Homepage / Dashboard"
                      value={editor.homepage}
                      onChange={(v) => setEditor({ ...editor, homepage: v })}
                      options={[...HOMEPAGE_OPTIONS]}
                    />
                  </div>
                  <div className="field">
                    <label className="field__label">Language</label>
                    <CustomSelect
                      placeholder="Language"
                      value={editor.language}
                      onChange={(v) => setEditor({ ...editor, language: v })}
                      options={[...LANGUAGE_OPTIONS]}
                    />
                  </div>
                </div>
              </div>

              <div
                className={cn(
                  'ut-preset-subpane',
                  editor.setupSubtab === 'signature' && 'is-active',
                )}
                data-preset-subpane="signature"
                hidden={editor.setupSubtab !== 'signature'}
              >
                <div className="card ut-sig-card">
                  <div className="ut-sig-card__main">
                    <div className="ut-sig-card__text">
                      <h3 className="ut-sig-card__title">Email Signature</h3>
                      <p className="ut-sig-card__desc">
                        Turn on to manage email signatures for users in this preset. This preset
                        email signature will be used in one-on-one emails throughout HubSpot CRM.
                      </p>
                    </div>
                    <label className="switch">
                      <input
                        type="checkbox"
                        checked={editor.sigOn}
                        onChange={(e) => setEditor({ ...editor, sigOn: e.target.checked })}
                      />
                      <span className="switch__track" />
                      <span className="switch__state-label">{editor.sigOn ? 'ON' : 'OFF'}</span>
                    </label>
                  </div>
                  <div className="ut-sig-card__editor" hidden={!editor.sigOn}>
                    <textarea
                      className="input"
                      rows={4}
                      placeholder={'Best regards,\n{{user.name}}\n{{company.name}}'}
                      value={editor.sigText}
                      onChange={(e) => setEditor({ ...editor, sigText: e.target.value })}
                    />
                  </div>
                </div>
              </div>

              <div
                className={cn(
                  'ut-preset-subpane',
                  editor.setupSubtab === 'notifications' && 'is-active',
                )}
                data-preset-subpane="notifications"
                hidden={editor.setupSubtab !== 'notifications'}
              >
                <div className="card crm-p-4">
                  <h3 className="crm-fs-6 crm-fw-semibold crm-mb-3">
                    Default notification channels
                  </h3>
                  <div className="field">
                    <label className="check-row">
                      <span className="check">
                        <input
                          type="checkbox"
                          checked={editor.notifyDigest}
                          onChange={(e) => setEditor({ ...editor, notifyDigest: e.target.checked })}
                        />
                        <span className="check__box" />
                      </span>
                      <span>Send daily email digests</span>
                    </label>
                  </div>
                  <div className="field">
                    <label className="check-row">
                      <span className="check">
                        <input
                          type="checkbox"
                          checked={editor.notifyLeads}
                          onChange={(e) => setEditor({ ...editor, notifyLeads: e.target.checked })}
                        />
                        <span className="check__box" />
                      </span>
                      <span>Instant alerts on new leads assigned</span>
                    </label>
                  </div>
                </div>
              </div>
            </div>

            <div
              className={cn('ut-subview-pane', editor.tab === 'users-teams' && 'is-active')}
              data-preset-pane="users-teams"
            >
              <div className="ut-pane-intro">
                <h2 className="ut-pane-title">Add users &amp; teams to preset</h2>
                <p className="ut-pane-desc">
                  These default preferences will be applied to all users in this preset. Once you
                  apply the preset, existing users will be notified about the changes you made.
                </p>
              </div>

              <div className="field crm-mt-4">
                <CustomSelect
                  placeholder="Search users or teams"
                  value={pickerValue}
                  searchable
                  onChange={addApplies}
                  options={pickerOptions}
                />
              </div>

              <div className="crm-mt-4">
                <p className="field__label set-label">
                  Who does this preset apply to:
                  <span
                    className="set-info"
                    tabIndex={0}
                    title="Users and teams configured will automatically receive the preset settings."
                    aria-label="Preset applies to information"
                  >
                    <CrmIcon name="info" className="iconSize-14" />
                  </span>
                </p>
                <div className="ut-preset-applies" data-preset-applies-list="">
                  {editor.applies.length === 0 ? (
                    <p className="crm-text-body-secondary" data-preset-no-users="">
                      No users or teams
                    </p>
                  ) : (
                    editor.applies.map((item, i) => (
                      <span key={`${item.kind}:${item.id}`} className="ut-preset-applies-pill">
                        {item.label}
                        <button
                          type="button"
                          aria-label={`Remove ${item.label}`}
                          onClick={() =>
                            setEditor({
                              ...editor,
                              applies: editor.applies.filter((_, idx) => idx !== i),
                            })
                          }
                        >
                          <CrmIcon name="x" className="iconSize-12" />
                        </button>
                      </span>
                    ))
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : null}

      {confirmDialog}
    </section>
  );
}
