'use client';

import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
import { updateProfile } from '@/features/settings/api.client';
import type { Profile } from '@/features/settings/types';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import {
  currentZoneName,
  sameZone,
  timezoneOptions,
  zoneNames,
  zoneOffsetMinutes,
  zonePlaces,
} from '@/features/settings/ui/accountDefaultsZones';
import { cn } from '@/lib/utils/cn';

/**
 * The calendar time zone picker of /calendar (#215), shared with /meetings (QA #647); design
 * components/tz-picker.js (Meetings spec 1): a pill with a globe, "UTC -08:00
 * America/Los_Angeles" and a chevron, opening "Select Calendar Timezone" with a search and the
 * groups Detected timezone (the user's own zone) / Common US timezones / Global timezones / All
 * timezones. The choice is saved to the profile's `calendarTimeZone`, so both pages open in the
 * zone last picked on either.
 */

const COMMON_US = [
  'America/Los_Angeles',
  'America/Denver',
  'America/Phoenix',
  'America/Chicago',
  'America/New_York',
  'America/Anchorage',
  'Pacific/Honolulu',
];
const GLOBAL = [
  'Europe/London',
  'Europe/Paris',
  'Europe/Berlin',
  'Asia/Dubai',
  'Asia/Kolkata',
  'Asia/Singapore',
  'Asia/Tokyo',
  'Australia/Sydney',
];

/** "UTC -08:00" for a zone right now (the design's offset text). */
export function tzOffset(zone: string, at = new Date()): string {
  const minutes = zoneOffsetMinutes(zone, at) ?? 0;
  const abs = Math.abs(minutes);
  const hh = String(Math.floor(abs / 60)).padStart(2, '0');
  const mm = String(abs % 60).padStart(2, '0');
  return `UTC ${minutes < 0 ? '-' : '+'}${hh}:${mm}`;
}

/** "Pacific Standard Time" style name, when the browser has one. */
function tzName(zone: string, at = new Date()): string {
  try {
    const name =
      new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'long' })
        .formatToParts(at)
        .find((p) => p.type === 'timeZoneName')?.value ?? '';
    return /^GMT/.test(name) ? '' : name;
  } catch {
    return '';
  }
}

/**
 * The pill's text: "UTC -08:00 America/Los_Angeles" (QA final BUG-17: the zone's current name).
 * MT-14 `places`: HubSpot's booking page names, "UTC +05:30 New Delhi, Mumbai, Calcutta".
 */
export function tzLabel(zone: string, at = new Date(), places = false): string {
  return `${tzOffset(zone, at)} ${places ? zonePlaces(zone) : currentZoneName(zone)}`;
}

const squash = (s: string) => s.toLowerCase().replace(/\s+/g, '_');
const city = (zone: string) => zone.split('/').pop()!.replace(/_/g, ' ');

export type ZoneGroup = { title: string; zones: string[] };

/**
 * The popover's list, as the design: with a search, up to 80 "Results" matching the zone, its
 * city, offset or name; without, the detected zone, the common US and global ones, then the rest.
 * QA final BUG-17: a renamed zone matches its current and old names ("Kolkata", "Calcutta"), and
 * one listed under both names (the saved one kept by timezoneOptions) shows once.
 */
export function zoneGroups(term: string, detected: string, all: string[]): ZoneGroup[] {
  const seen = new Set<string>();
  const zones = all.filter((z) => {
    const name = currentZoneName(z);
    if (seen.has(name)) return false;
    seen.add(name);
    return true;
  });
  const q = squash(term.trim());
  if (q) {
    const at = new Date();
    const hit = (z: string) =>
      [
        ...zoneNames(z).flatMap((n) => [n, city(n)]),
        tzOffset(z, at),
        tzName(z, at),
        // MT-14: the places the booking page names ("Mumbai").
        zonePlaces(z),
      ].some((t) => squash(t).includes(q));
    const found = zones.filter(hit);
    return found.length ? [{ title: 'Results', zones: found.slice(0, 80) }] : [];
  }
  const us = COMMON_US.filter((z) => !sameZone(z, detected));
  const global = GLOBAL.filter((z) => !sameZone(z, detected));
  const pinned = new Set([detected, ...us, ...global].map(currentZoneName));
  return [
    { title: 'Detected timezone', zones: [detected] },
    { title: 'Common US timezones', zones: us },
    { title: 'Global timezones', zones: global },
    { title: 'All timezones', zones: zones.filter((z) => !pinned.has(currentZoneName(z))) },
  ].filter((g) => g.zones.length);
}

export function useCalendarZone() {
  // #215: the user's own zone (profile, else the browser's), then the one they last chose here.
  const prefs = useUserPrefs();
  const [homeZone, setHomeZone] = useState(prefs.timeZone);
  const [timeZone, setTimeZone] = useState(prefs.timeZone);
  const profileRef = useRef<Profile | null>(null);
  /** A zone came from the profile or a pick here: the user's zone no longer moves it. */
  const settledRef = useRef(false);

  // HUB-707 #751: the browser's zone is known only after the first render, so the first value is
  // the account's (often America/Los_Angeles). Follow the user's zone until one is settled.
  useEffect(() => {
    if (settledRef.current) return;
    setHomeZone(prefs.timeZone);
    setTimeZone(prefs.timeZone);
  }, [prefs.timeZone]);

  /** Call with the loaded profile: its zone becomes "home" and its saved choice is applied. */
  const adoptProfile = useCallback((p: Profile) => {
    profileRef.current = p;
    if (p.timezone) setHomeZone(p.timezone);
    const chosen = p.preferences.calendarTimeZone || p.timezone;
    if (chosen) {
      settledRef.current = true;
      setTimeZone(chosen);
    }
  }, []);

  const chooseZone = useCallback((z: string) => {
    settledRef.current = true;
    setTimeZone(z);
    const profile = profileRef.current;
    if (!profile) return;
    updateProfile({ preferences: { calendarTimeZone: z }, updatedAt: profile.updatedAt }).then(
      (saved) => {
        profileRef.current = saved;
      },
      () => {},
    );
  }, []);

  // Chrome reports "Asia/Calcutta"; show the current IANA name, as the picker lists it.
  return {
    timeZone: currentZoneName(timeZone),
    homeZone: currentZoneName(homeZone),
    adoptProfile,
    chooseZone,
  };
}

export function TimeZonePicker({
  timeZone,
  homeZone,
  onChoose,
  title = 'Select Calendar Timezone',
  places = false,
}: {
  timeZone: string;
  homeZone: string;
  /** Presentational: the page keeps (or saves) the choice. */
  onChoose: (zone: string) => void;
  /** MT-14: the popover's heading (the public booking page's "Select your time zone"). */
  title?: string;
  /** MT-14: label zones by their places, as HubSpot's booking page. */
  places?: boolean;
}) {
  const popId = useId();
  const rootRef = useRef<HTMLDivElement>(null);
  const pillRef = useRef<HTMLButtonElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);
  const listRef = useRef<HTMLDivElement>(null);
  const [open, setOpen] = useState(false);
  const [query, setQuery] = useState('');
  const label = tzLabel(timeZone, undefined, places);

  // Every zone this browser knows (the saved one kept even if it doesn't), A to Z by the name
  // shown (QA final BUG-17: the current one, so Asia/Kolkata sorts as Kolkata, not Calcutta).
  const all = useMemo(
    () =>
      open
        ? timezoneOptions(new Date(), timeZone)
            .map((o) => o.value)
            .map((z) => [currentZoneName(z), z] as const)
            .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
            .map(([, z]) => z)
        : [],
    [open, timeZone],
  );
  const groups = useMemo(
    () => (open ? zoneGroups(query, homeZone, all) : []),
    [open, query, homeZone, all],
  );

  const close = useCallback((focus: boolean) => {
    setOpen(false);
    if (focus) pillRef.current?.focus();
  }, []);

  useEffect(() => {
    if (!open) return;
    searchRef.current?.focus();
    listRef.current?.querySelector('.is-selected')?.scrollIntoView({ block: 'nearest' });
    const onDown = (e: MouseEvent) => {
      if (!rootRef.current?.contains(e.target as Node)) close(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [open, close]);

  return (
    <div className="tzp" ref={rootRef}>
      <button
        ref={pillRef}
        type="button"
        className="tzp__pill"
        aria-haspopup="dialog"
        aria-expanded={open}
        aria-controls={popId}
        title={places ? label : `Calendar timezone: ${label}`}
        onClick={() => {
          setQuery('');
          setOpen((o) => !o);
        }}
      >
        <svg
          className="tzp__globe"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="1.8"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden
        >
          <circle cx="12" cy="12" r="9" />
          <path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" />
        </svg>
        <span className="tzp__label">{label}</span>
        <svg
          className="tzp__chev"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden
        >
          <path d="m6 9 6 6 6-6" />
        </svg>
      </button>
      <div
        className="tzp__pop"
        id={popId}
        role="dialog"
        aria-label={places ? title : 'Select calendar timezone'}
        hidden={!open}
        onKeyDown={(e) => {
          if (e.key === 'Escape') {
            e.stopPropagation();
            close(true);
            return;
          }
          if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp') return;
          const opts = Array.from(
            listRef.current?.querySelectorAll<HTMLButtonElement>('[data-tzp-zone]') ?? [],
          );
          if (!opts.length) return;
          e.preventDefault();
          const i = opts.indexOf(document.activeElement as HTMLButtonElement);
          const n = e.key === 'ArrowDown' ? Math.min(opts.length - 1, i + 1) : i <= 0 ? -1 : i - 1;
          if (n < 0) searchRef.current?.focus();
          else opts[n]!.focus();
        }}
      >
        <div className="tzp__head">
          <strong>{title}</strong>
          <button type="button" className="tzp__x" aria-label="Close" onClick={() => close(true)}>
            <svg
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              aria-hidden
            >
              <path d="M6 6l12 12M18 6 6 18" />
            </svg>
          </button>
        </div>
        <label className="tzp__search">
          <svg
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            aria-hidden
          >
            <circle cx="11" cy="11" r="7" />
            <path d="m20 20-3.5-3.5" />
          </svg>
          <input
            ref={searchRef}
            type="search"
            placeholder="Search timezone or city..."
            aria-label="Search timezone or city"
            autoComplete="off"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
        </label>
        <div className="tzp__list" role="listbox" aria-label="Timezones" ref={listRef}>
          {open && !groups.length ? (
            <p className="tzp__empty">No timezones match your search.</p>
          ) : (
            groups.map((g) => (
              <div className="tzp__group" role="group" aria-label={g.title} key={g.title}>
                <p className="tzp__gh">{g.title}</p>
                {g.zones.map((z) => {
                  // QA final BUG-17: the value stays as listed, so a saved zone still matches
                  // under either name; the current name is shown.
                  const on = sameZone(z, timeZone);
                  const name = tzName(z);
                  return (
                    <button
                      type="button"
                      key={z}
                      className={cn('tzp__opt', on && 'is-selected')}
                      role="option"
                      aria-selected={on}
                      data-tzp-zone={z}
                      onClick={() => {
                        onChoose(z);
                        close(true);
                      }}
                    >
                      <span className="tzp__radio" aria-hidden />
                      <span className="tzp__txt">
                        {places ? (
                          tzLabel(z, undefined, true)
                        ) : (
                          <>
                            {currentZoneName(z)}{' '}
                            <small>
                              ({name ? `${name} - ` : ''}
                              {tzOffset(z)})
                            </small>
                          </>
                        )}
                      </span>
                      {on ? <span className="tzp__sel">Selected</span> : null}
                    </button>
                  );
                })}
              </div>
            ))
          )}
        </div>
      </div>
    </div>
  );
}
