import {
  useEffect,
  useRef,
  useState,
} from 'react';

import { CalendarIcon } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import { inputFieldClass } from '@/components/ui/input';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';

import {
  applyDateInputMask,
  formatUnixDate,
  isMaskComplete,
  parseMaskedDate,
} from './dateInputUtils';

type DateEditableFieldProps = {
  withTime: boolean;
  value: number | null | undefined;
  onChange: (value: number | null) => void;
  placeholder?: string;
};

export function DateEditableField({
  withTime,
  value,
  onChange,
  placeholder,
}: DateEditableFieldProps) {
  const [inputText, setInputText] = useState(() => formatUnixDate(value, withTime));
  const [open, setOpen] = useState(false);
  const isFocusedRef = useRef(false);

  useEffect(() => {
    if (isFocusedRef.current) return;
    setInputText(formatUnixDate(value, withTime));
  }, [value, withTime]);

  const commitInput = (text: string) => {
    if (!text.trim()) {
      onChange(null);
      setInputText('');
      return;
    }

    const parsed = parseMaskedDate(text, withTime);
    if (parsed !== null) {
      onChange(parsed);
      setInputText(formatUnixDate(parsed, withTime));
      return;
    }

    setInputText(formatUnixDate(value, withTime));
  };

  const handleInputChange = (raw: string) => {
    const masked = applyDateInputMask(raw, withTime);
    setInputText(masked);

    if (isMaskComplete(masked, withTime)) {
      const parsed = parseMaskedDate(masked, withTime);
      if (parsed !== null) {
        onChange(parsed);
      }
    }
  };

  const handleBlur = () => {
    isFocusedRef.current = false;
    commitInput(inputText);
  };

  const handleCalendarChange = (date: number | null) => {
    onChange(date);
    setInputText(formatUnixDate(date, withTime));
    setOpen(false);
  };

  return (
    <div className="flex w-full items-stretch">
      <input
        type="text"
        inputMode="numeric"
        data-slot="input"
        className={cn(
          inputFieldClass,
          'min-w-0 flex-1 rounded-r-none border-r-0 focus-visible:z-10',
        )}
        value={inputText}
        placeholder={placeholder}
        onChange={(e) => handleInputChange(e.target.value)}
        onFocus={() => {
          isFocusedRef.current = true;
        }}
        onBlur={handleBlur}
      />
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger asChild>
          <Button
            type="button"
            variant="outline"
            size="icon"
            className="shrink-0 rounded-l-none focus-visible:z-10"
            aria-label={placeholder}
          >
            <CalendarIcon />
          </Button>
        </PopoverTrigger>
        <PopoverContent className="w-auto overflow-hidden p-0" align="end">
          <Calendar
            mode="single"
            withTime={withTime}
            value={value ?? null}
            captionLayout="dropdown"
            onChange={handleCalendarChange}
          />
        </PopoverContent>
      </Popover>
    </div>
  );
}
