'use client';

import { Check, ChevronDown, Globe } from 'lucide-react';
import { useId, useMemo, useState, type KeyboardEvent } from 'react';

import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';

const ALL_ZONES: readonly string[] =
  typeof Intl !== 'undefined' && 'supportedValuesOf' in Intl ? Intl.supportedValuesOf('timeZone') : ['UTC', 'America/New_York', 'Europe/London', 'Asia/Karachi'];

/** "UTC+5" style offset for a zone, computed from the browser's Intl data. */
export const zoneOffset = (zone: string): string => {
  try {
    const part = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'shortOffset' }).formatToParts(new Date()).find((item) => item.type === 'timeZoneName');
    const value = part?.value ?? 'GMT';
    return value === 'GMT' ? 'UTC' : value.replace('GMT', 'UTC');
  } catch {
    return 'UTC';
  }
};

/** Searchable time zone picker that shows the UTC offset, e.g. Asia/Karachi (UTC+5). */
export function TimeZoneCombobox({ id, value, onChange }: { id: string; value: string; onChange: (zone: string) => void }) {
  const listId = useId();
  const [query, setQuery] = useState('');
  const [open, setOpen] = useState(false);
  const [highlight, setHighlight] = useState(0);
  const matches = useMemo(() => {
    const needle = query.trim().toLowerCase().replace(/\s+/g, '_');
    return ALL_ZONES.filter((zone) => needle.length === 0 || zone.toLowerCase().includes(needle)).slice(0, 50);
  }, [query]);

  const choose = (zone: string) => {
    onChange(zone);
    setOpen(false);
  };

  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.key === 'ArrowDown') {
      event.preventDefault();
      setOpen(true);
      setHighlight((current) => Math.min(matches.length - 1, current + 1));
    } else if (event.key === 'ArrowUp') {
      event.preventDefault();
      setHighlight((current) => Math.max(0, current - 1));
    } else if (event.key === 'Enter' && open) {
      const match = matches[highlight];
      if (match !== undefined) {
        event.preventDefault();
        choose(match);
      }
    } else if (event.key === 'Escape') {
      setOpen(false);
    }
  };

  return (
    <div className="relative">
      <Input
        id={id}
        role="combobox"
        aria-expanded={open}
        aria-controls={listId}
        aria-autocomplete="list"
        autoComplete="off"
        leading={<Globe />}
        trailing={<ChevronDown className="mr-3 h-4 w-4 text-subtle-foreground" aria-hidden="true" />}
        value={open ? query : `${value.replaceAll('_', ' ')} (${zoneOffset(value)})`}
        placeholder="Search time zones"
        onFocus={() => {
          setOpen(true);
          setQuery('');
          setHighlight(0);
        }}
        onChange={(event) => {
          setQuery(event.target.value);
          setHighlight(0);
          setOpen(true);
        }}
        onKeyDown={onKeyDown}
        onBlur={() => window.setTimeout(() => setOpen(false), 150)}
      />
      {open ? (
        <ul id={listId} role="listbox" className="absolute z-30 mt-1.5 max-h-64 w-full overflow-auto rounded-lg border border-border bg-surface p-1 shadow-md">
          {matches.length === 0 ? <li className="px-3 py-2 text-small text-muted-foreground">No matching time zone</li> : null}
          {matches.map((zone, index) => (
            <li
              key={zone}
              role="option"
              aria-selected={zone === value}
              onMouseDown={(event) => event.preventDefault()}
              onMouseEnter={() => setHighlight(index)}
              onClick={() => choose(zone)}
              className={cn('flex h-9 cursor-pointer items-center gap-2 rounded-md px-2.5 text-small', index === highlight ? 'bg-surface-muted' : 'hover:bg-surface-muted')}
            >
              <span className="flex-1 truncate">{zone.replaceAll('_', ' ')}</span>
              <span className="text-caption tabular-nums text-muted-foreground">{zoneOffset(zone)}</span>
              {zone === value ? <Check className="h-4 w-4 text-primary" aria-hidden="true" /> : null}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}
