'use client';

import { createContext, useContext, useEffect, useMemo, useState } from 'react';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { getProfile } from './api.client';
import { homePathOf, type Profile, type RecordActionButton, type RegionFormat } from './types';

/** The user's time zone (profile, else the business's) and meeting length preference. */
export interface UserPrefs {
  timeZone: string;
  /** The profile's own time zone; null while loading or when the business's applies. */
  profileTimeZone: string | null;
  /** The profile has loaded (profileTimeZone is known). */
  profileLoaded: boolean;
  meetingMinutes: number;
  /** HTML signature added to emails, or null. */
  signature: string | null;
  /** Date format (us 12/31/2026, uk / in 31/12/2026, de 31.12.2026). */
  regionFormat: RegionFormat;
  /** General › Profile: where the logo and the root URL open (#517). */
  homePath: string;
  /** General › Tasks: the due date Create task starts with. */
  taskDefaultDue: Profile['preferences']['taskDefaultDue'];
  /** General › Tasks: the reminder Create task starts with. */
  taskDefaultReminder: Profile['preferences']['taskDefaultReminder'];
  /** General › Tasks: the due time Create task starts with ("HH:MM"). */
  taskDefaultTime: string;
  /** HUB-572: record quick action buttons in the user's order. */
  recordActionButtons: RecordActionButton[];
  /** HUB-572: activity types record timelines show by default; null: all. */
  timelineTypes: string[] | null;
  /** General › Automation: the zoom a workflow canvas opens at (25 to 200). */
  workflowDefaultZoom: number;
  /** General › Automation: show the workflow canvas minimap (#518). */
  workflowMinimap: boolean;
  /** General › Profile: the signed-in user has a photo (navbar and account menu). */
  hasAvatar: boolean;
  /** Cache key for that photo; changes when it is replaced or removed. */
  avatarVersion: string;
}

/** The profile as prefs; without one (it failed to load), the business's time zone and defaults. */
export function userPrefsFrom(profile: Profile | null, businessTimeZone: string): UserPrefs {
  const buttons = profile?.preferences.recordActionButtons;
  return {
    timeZone: profile?.timezone || businessTimeZone,
    profileTimeZone: profile?.timezone || null,
    profileLoaded: profile !== null,
    meetingMinutes: profile?.preferences.meetingDefaultMinutes || 30,
    signature: profile?.emailSignature ?? null,
    regionFormat: profile?.regionFormat ?? 'us',
    homePath: homePathOf(profile?.preferences.defaultHomePage),
    taskDefaultDue: profile?.preferences.taskDefaultDue ?? 'none',
    taskDefaultReminder: profile?.preferences.taskDefaultReminder ?? 'none',
    taskDefaultTime: profile?.preferences.taskDefaultTime ?? '08:00',
    recordActionButtons: buttons?.length ? buttons : ['note', 'email', 'call', 'task', 'meeting'],
    timelineTypes: profile?.preferences.timelineTypes ?? null,
    workflowDefaultZoom: clampZoom(profile?.preferences.workflowDefaultZoom),
    workflowMinimap: profile?.preferences.workflowMinimap !== false,
    hasAvatar: profile?.hasAvatar === true,
    avatarVersion: profile?.updatedAt ?? '',
  };
}

/** Same bounds as the Automation setting (25% to 200%). */
function clampZoom(value: number | undefined): number {
  if (value == null || !Number.isFinite(value)) return 100;
  return Math.min(200, Math.max(25, Math.round(value)));
}

const UserPrefsContext = createContext<{
  prefs: UserPrefs;
  applyProfile: (profile: Profile) => void;
} | null>(null);

/**
 * One copy of the user's prefs for the whole CRM shell. The app layout passes the profile in, so
 * the first render already has the user's date format and time zone; when that load failed, it
 * is tried once more from the browser.
 */
export function UserPrefsProvider({
  initialProfile,
  children,
}: {
  initialProfile: Profile | null;
  children: React.ReactNode;
}) {
  const businessTimeZone = useCurrentUser().business.timezone;
  // #488 / #215: without a time zone of their own, a user sees times in their browser's zone (as
  // HubSpot does), not the business's. Read after the first render, so the server's and the
  // browser's first render match.
  const [browserTimeZone, setBrowserTimeZone] = useState<string | null>(null);
  useEffect(() => {
    try {
      setBrowserTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone || null);
    } catch {
      // no Intl time zone support: the business's applies
    }
  }, []);
  const fallbackTimeZone = browserTimeZone ?? businessTimeZone;
  const [profile, setProfile] = useState(initialProfile);
  useEffect(() => {
    if (profile) return;
    let alive = true;
    getProfile().then(
      (p) => {
        if (alive) setProfile(p);
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, [profile]);
  const value = useMemo(
    () => ({ prefs: userPrefsFrom(profile, fallbackTimeZone), applyProfile: setProfile }),
    [profile, fallbackTimeZone],
  );
  return <UserPrefsContext.Provider value={value}>{children}</UserPrefsContext.Provider>;
}

function useUserPrefsContext() {
  const value = useContext(UserPrefsContext);
  if (!value) throw new Error('useUserPrefs() must be used inside the (app) layout');
  return value;
}

export function useUserPrefs(): UserPrefs {
  return useUserPrefsContext().prefs;
}

/** Puts a saved profile (PATCH /me/profile) into the shared prefs. */
export function useApplyProfile(): (profile: Profile) => void {
  return useUserPrefsContext().applyProfile;
}
