// @design-system: domain/HoursEditor

'use client';

import { cn } from '@/lib/cn';
import { Switch } from '@/components/ui/primitives/Switch';
import { Label } from '@/components/ui/primitives/Label';
import { LabelWithTooltip } from '@/components/ui/primitives/LabelWithTooltip';
import { Textarea } from '@/components/ui/primitives/Textarea';
import { Icon } from '@/components/ui/icons/Icon';
import { useT } from '@/lib/i18n/react';

/** Compact HH:MM spinner with up/down arrow buttons */
export function TimeSpinner({
  value,
  onChange,
  ariaLabel,
}: {
  value: string;
  onChange: (v: string) => void;
  ariaLabel: string;
}) {
  const parts = value.split(':');
  const hh = Number(parts[0] ?? 0);
  const mm = Number(parts[1] ?? 0);

  const pad = (n: number) => String(n).padStart(2, '0');

  const adjustHour = (delta: number) => {
    const next = (hh + delta + 24) % 24;
    onChange(`${pad(next)}:${pad(mm)}`);
  };

  const adjustMinute = (delta: number) => {
    const next = (mm + delta + 60) % 60;
    onChange(`${pad(hh)}:${pad(next)}`);
  };

  return (
    <div
      role="group"
      aria-label={ariaLabel}
      dir="ltr"
      className="bg-surface-base border-border-default flex items-center overflow-hidden rounded-md border"
    >
      {/* Hours column */}
      <div className="flex flex-col items-center">
        <button
          type="button"
          onClick={() => adjustHour(1)}
          aria-label={`${ariaLabel} hour up`}
          className="text-text-muted hover:text-text-primary flex h-5 w-8 items-center justify-center transition-colors hover:bg-neutral-50"
        >
          <Icon name="ChevronUp" size="xs" color="inherit" />
        </button>
        <span className="text-text-primary w-8 py-0.5 text-center text-xs leading-none font-medium tabular-nums">
          {pad(hh)}
        </span>
        <button
          type="button"
          onClick={() => adjustHour(-1)}
          aria-label={`${ariaLabel} hour down`}
          className="text-text-muted hover:text-text-primary flex h-5 w-8 items-center justify-center transition-colors hover:bg-neutral-50"
        >
          <Icon name="ChevronDown" size="xs" color="inherit" />
        </button>
      </div>

      <span className="text-text-muted px-0.5 text-xs font-medium select-none">:</span>

      {/* Minutes column */}
      <div className="flex flex-col items-center">
        <button
          type="button"
          onClick={() => adjustMinute(15)}
          aria-label={`${ariaLabel} minute up`}
          className="text-text-muted hover:text-text-primary flex h-5 w-8 items-center justify-center transition-colors hover:bg-neutral-50"
        >
          <Icon name="ChevronUp" size="xs" color="inherit" />
        </button>
        <span className="text-text-primary w-8 py-0.5 text-center text-xs leading-none font-medium tabular-nums">
          {pad(mm)}
        </span>
        <button
          type="button"
          onClick={() => adjustMinute(-15)}
          aria-label={`${ariaLabel} minute down`}
          className="text-text-muted hover:text-text-primary flex h-5 w-8 items-center justify-center transition-colors hover:bg-neutral-50"
        >
          <Icon name="ChevronDown" size="xs" color="inherit" />
        </button>
      </div>
    </div>
  );
}

/** Day of week identifier */
export type DayOfWeek =
  | 'monday'
  | 'tuesday'
  | 'wednesday'
  | 'thursday'
  | 'friday'
  | 'saturday'
  | 'sunday';

const ALL_DAYS: DayOfWeek[] = [
  'sunday',
  'monday',
  'tuesday',
  'wednesday',
  'thursday',
  'friday',
  'saturday',
];

/** Hours for a single day */
export interface DayHours {
  open: boolean;
  openTime: string; // "HH:mm"
  closeTime: string; // "HH:mm"
}

/** Props for HoursEditor */
export interface HoursEditorProps {
  /** Current hours for each day. */
  value: Record<DayOfWeek, DayHours>;
  /** Called when hours change. */
  onChange: (value: Record<DayOfWeek, DayHours>) => void;
  /** Special notes / exceptions. */
  specialNotes?: string;
  /** Called when special notes change. */
  onNotesChange?: (notes: string) => void;
  /** Additional class names. */
  className?: string;
}

/**
 * HoursEditor - 7-day grid of open/close/closed toggles + special notes (FDS §5.7).
 *
 * @example
 * ```tsx
 * <HoursEditor value={hoursData} onChange={setHoursData} specialNotes={notes} onNotesChange={setNotes} />
 * ```
 */
export function HoursEditor({
  value,
  onChange,
  specialNotes = '',
  onNotesChange,
  className,
}: HoursEditorProps) {
  const t = useT('domain_hours');

  const dayLabelMap: Record<DayOfWeek, string> = {
    monday: t('days_monday'),
    tuesday: t('days_tuesday'),
    wednesday: t('days_wednesday'),
    thursday: t('days_thursday'),
    friday: t('days_friday'),
    saturday: t('days_saturday'),
    sunday: t('days_sunday'),
  };

  const updateDay = (day: DayOfWeek, patch: Partial<DayHours>) => {
    onChange({ ...value, [day]: { ...value[day], ...patch } });
  };

  return (
    <div className={cn('flex flex-col gap-4', className)}>
      {/* Day grid */}
      <div className="bg-surface-base border-border-default flex flex-col divide-y divide-neutral-100 rounded-xl border">
        {ALL_DAYS.map((day) => {
          const hours = value[day];
          const switchId = `hours-${day}-open`;
          return (
            <div key={day} className="flex items-center gap-3 px-4 py-3">
              {/* Day label */}
              <span className="text-text-primary w-16 shrink-0 text-sm font-medium">
                {dayLabelMap[day]}
              </span>

              {/* Open toggle */}
              <Switch
                id={switchId}
                checked={hours.open}
                onCheckedChange={(checked) => updateDay(day, { open: checked })}
                aria-label={`${dayLabelMap[day]} ${hours.open ? t('open') : t('closed')}`}
              />
              <Label htmlFor={switchId} className="text-text-secondary text-xs">
                {hours.open ? t('open') : t('closed')}
              </Label>

              {/* Time spinners - only when open */}
              {hours.open && (
                <div className="ms-auto flex items-center gap-2">
                  <TimeSpinner
                    value={hours.openTime}
                    onChange={(v) => updateDay(day, { openTime: v })}
                    ariaLabel={`${dayLabelMap[day]} open time`}
                  />
                  <span className="text-text-muted text-xs select-none">–</span>
                  <TimeSpinner
                    value={hours.closeTime}
                    onChange={(v) => updateDay(day, { closeTime: v })}
                    ariaLabel={`${dayLabelMap[day]} close time`}
                  />
                </div>
              )}
            </div>
          );
        })}
      </div>

      {/* Special notes */}
      {onNotesChange && (
        <div className="flex flex-col gap-1.5">
          <LabelWithTooltip
            htmlFor="hours-special-notes"
            label={t('special_notes')}
            tooltip={t('special_notes_tooltip')}
          />
          <Textarea
            id="hours-special-notes"
            rows={3}
            placeholder={t('special_notes_placeholder')}
            value={specialNotes}
            onChange={(e) => onNotesChange(e.target.value)}
          />
        </div>
      )}
    </div>
  );
}
