'use client';

/**
 * TimeSelector
 *
 * Clean time picker with hour and minute selects.
 */

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';
import { Clock } from 'lucide-react';
import { useCronTime } from '../context/hooks';

const HOURS = Array.from({ length: 24 }, (_, i) => i);
const MINUTES = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55];

export interface TimeSelectorProps {
  format?: '12h' | '24h';
  disabled?: boolean;
  className?: string;
}

export function TimeSelector({
  format = '24h',
  disabled,
  className,
}: TimeSelectorProps) {
  const { hour, minute, setTime } = useCronTime();

  const is24h = format === '24h';
  const displayHour = is24h ? hour : (hour % 12) || 12;
  const isPM = hour >= 12;

  const handleHourChange = (value: string) => {
    let newHour = parseInt(value, 10);
    if (!is24h) {
      if (isPM && newHour !== 12) newHour += 12;
      else if (!isPM && newHour === 12) newHour = 0;
    }
    setTime(newHour, minute);
  };

  const handleMinuteChange = (value: string) => {
    setTime(hour, parseInt(value, 10));
  };

  const handlePeriodChange = (value: string) => {
    const newIsPM = value === 'PM';
    let newHour = hour;
    if (newIsPM && hour < 12) newHour = hour + 12;
    else if (!newIsPM && hour >= 12) newHour = hour - 12;
    setTime(newHour, minute);
  };

  const hours = is24h ? HOURS : Array.from({ length: 12 }, (_, i) => i + 1);

  return (
    <div className={cn('flex items-center gap-3', className)}>
      <div className="flex items-center gap-2 text-muted-foreground">
        <Clock aria-hidden="true" className="h-4 w-4" />
        <span className="text-sm">Run at</span>
      </div>

      <div className="flex items-center gap-1.5 flex-1">
        {/* Hour */}
        <Select
          value={displayHour.toString()}
          onValueChange={handleHourChange}
          disabled={disabled}
        >
          <SelectTrigger className="w-[70px] h-9">
            <SelectValue>
              {displayHour.toString().padStart(2, '0')}
            </SelectValue>
          </SelectTrigger>
          <SelectContent className="max-h-48">
            {hours.map((h) => (
              <SelectItem key={h} value={h.toString()}>
                {h.toString().padStart(2, '0')}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        <span className="text-muted-foreground font-medium">:</span>

        {/* Minute */}
        <Select
          value={minute.toString()}
          onValueChange={handleMinuteChange}
          disabled={disabled}
        >
          <SelectTrigger className="w-[70px] h-9">
            <SelectValue>
              {minute.toString().padStart(2, '0')}
            </SelectValue>
          </SelectTrigger>
          <SelectContent className="max-h-48">
            {MINUTES.map((m) => (
              <SelectItem key={m} value={m.toString()}>
                {m.toString().padStart(2, '0')}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        {/* AM/PM for 12h */}
        {!is24h && (
          <Select
            value={isPM ? 'PM' : 'AM'}
            onValueChange={handlePeriodChange}
            disabled={disabled}
          >
            <SelectTrigger className="w-[70px] h-9">
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="AM">AM</SelectItem>
              <SelectItem value="PM">PM</SelectItem>
            </SelectContent>
          </Select>
        )}
      </div>
    </div>
  );
}
