/* eslint-disable @typescript-eslint/no-explicit-any */
'use client';

import { X } from 'lucide-react';
import { Control, useController } from 'react-hook-form';

import { cn } from '@/lib/utils';

import { FieldWrapper } from './FieldWrapper';

const HOURS = Array.from({ length: 24 }).map((_, i) => String(i).padStart(2, '0'));
const MINUTES = ['00', '15', '30', '45'];

interface TimePickerProps {
  control: Control<any>;
  name: string;
  label?: string;
  required?: boolean;
  helper?: string;
  clearable?: boolean;
}

export function TimePickerField({
  control,
  name,
  label,
  required,
  helper,
  clearable = false,
}: TimePickerProps) {
  const {
    field,
    fieldState: { error },
  } = useController({ control, name });

  const [hour, minute] = field.value ? field.value.split(':') : ['', ''];

  const handleHourChange = (h: string) => {
    const newMinute = minute || '00';
    field.onChange(h ? `${h}:${newMinute}` : '');
  };

  const handleMinuteChange = (m: string) => {
    if (hour) {
      field.onChange(`${hour}:${m}`);
    }
  };

  const handleClear = () => {
    field.onChange('');
  };

  return (
    <FieldWrapper label={label} required={required} helper={helper} error={error?.message}>
      <div className="flex gap-2 items-center">
        <select
          value={hour}
          onChange={(e) => handleHourChange(e.target.value)}
          className={cn(
            'flex-1 h-11 px-3 py-2 text-base text-mma-blue border border-input bg-transparent rounded-none',
            'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mma-blue',
            'disabled:cursor-not-allowed disabled:opacity-50',
            !hour && 'text-muted-foreground'
          )}
        >
          <option value="" disabled>
            óra
          </option>
          {HOURS.map((h) => (
            <option key={h} value={h}>
              {h}
            </option>
          ))}
        </select>

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

        <select
          value={minute}
          onChange={(e) => handleMinuteChange(e.target.value)}
          disabled={!hour}
          className={cn(
            'flex-1 h-11 px-3 py-2 text-base text-mma-blue border border-input bg-transparent rounded-none',
            'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mma-blue',
            'disabled:cursor-not-allowed disabled:opacity-50',
            !minute && 'text-muted-foreground'
          )}
        >
          <option value="" disabled>
            perc
          </option>
          {MINUTES.map((m) => (
            <option key={m} value={m}>
              {m}
            </option>
          ))}
        </select>

        {clearable && field.value && (
          <button type="button" onClick={handleClear} className="p-2 hover:bg-mma-cyan/20 rounded">
            <X className="h-4 w-4 text-gray-500" />
          </button>
        )}
      </div>
    </FieldWrapper>
  );
}
