import { useEffect, useRef, type FormEvent } from 'react';
import { Trans, useTranslation } from 'react-i18next';

import { CloseIcon, SpinnerIcon } from '../../ui/icons';

interface ClearFiltersDialogProps {
  open: boolean;
  saveName: string;
  saveError: string | null;
  savingSearch?: boolean;
  editingSearchName?: string | null;
  onClose: () => void;
  onSaveNameChange: (value: string) => void;
  onSaveAndClear: (e: FormEvent) => void;
  onUpdateAndClear?: () => void;
  onClearWithoutSaving: () => void;
}

export function ClearFiltersDialog({
  open,
  saveName,
  saveError,
  savingSearch,
  editingSearchName,
  onClose,
  onSaveNameChange,
  onSaveAndClear,
  onUpdateAndClear,
  onClearWithoutSaving,
}: ClearFiltersDialogProps) {
  const { t } = useTranslation();
  const isEditing = !!editingSearchName && !!onUpdateAndClear;
  const dialogRef = useRef<HTMLDivElement>(null);
  const previouslyFocusedRef = useRef<HTMLElement | null>(null);

  useEffect(() => {
    if (!open) return;
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [open, onClose]);

  useEffect(() => {
    if (!open) return;
    previouslyFocusedRef.current = document.activeElement as HTMLElement | null;
    const firstFocusable = dialogRef.current?.querySelector<HTMLElement>(
      'input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])'
    );
    (firstFocusable ?? dialogRef.current)?.focus();
    return () => {
      previouslyFocusedRef.current?.focus?.();
    };
  }, [open]);

  if (!open) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center"
      onClick={onClose}
      role="presentation"
    >
      <div className="absolute inset-0 bg-black/50 dark:bg-black/70" aria-hidden="true" />
      <div
        ref={dialogRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby="clear-filters-dialog-title"
        tabIndex={-1}
        className="relative w-full max-w-sm mx-4 bg-white dark:bg-warm-900 rounded-lg shadow-xl border border-warm-200 dark:border-warm-700 outline-none"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-5 pt-5 pb-3">
          <h2
            id="clear-filters-dialog-title"
            className="text-lg font-semibold text-navy-950 dark:text-white"
          >
            {t('filters.clearAllTitle')}
          </h2>
          <button
            onClick={onClose}
            className="text-warm-400 hover:text-warm-700 dark:text-warm-400 dark:hover:text-warm-200"
          >
            <CloseIcon className="w-5 h-5" />
          </button>
        </div>
        {isEditing ? (
          <div className="p-5 pt-2 space-y-4">
            <p className="text-sm text-warm-600 dark:text-warm-400">
              <Trans
                i18nKey="filters.clearAllUpdatePrompt"
                values={{ name: editingSearchName }}
                components={{
                  strong: <strong className="font-semibold text-navy-950 dark:text-warm-100" />,
                }}
              />
            </p>
            {saveError && <p className="text-sm text-red-600 dark:text-red-300">{saveError}</p>}
            <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-center">
              <button
                type="button"
                onClick={onClearWithoutSaving}
                className="px-4 py-2 text-sm rounded border border-warm-200 dark:border-warm-700 text-warm-700 dark:text-warm-300 hover:bg-warm-50 dark:hover:bg-warm-700"
              >
                {t('filters.clearWithoutUpdating')}
              </button>
              <button
                type="button"
                onClick={onUpdateAndClear}
                disabled={savingSearch}
                className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded bg-teal-600 text-white font-medium hover:bg-teal-700 disabled:opacity-50 disabled:cursor-wait"
              >
                {savingSearch && <SpinnerIcon className="w-4 h-4 animate-spin" />}
                {savingSearch ? t('savedPage.updating') : t('filters.updateAndClear')}
              </button>
            </div>
          </div>
        ) : (
          <form onSubmit={onSaveAndClear} className="p-5 pt-2 space-y-4">
            <p className="text-sm text-warm-600 dark:text-warm-400">
              {t('filters.clearAllSavePrompt')}
            </p>
            <div>
              <input
                type="text"
                value={saveName}
                onChange={(e) => onSaveNameChange(e.target.value)}
                className="w-full px-3 py-2 text-sm rounded border border-warm-200 dark:border-warm-700 bg-white dark:bg-warm-800 text-navy-950 dark:text-white placeholder-warm-400 dark:placeholder-warm-500 outline-none focus:ring-2 ring-teal-400 dark:ring-teal-500"
                placeholder={t('saveSearch.namePlaceholder')}
                autoFocus
              />
            </div>
            {saveError && <p className="text-sm text-red-600 dark:text-red-300">{saveError}</p>}
            <div className="flex flex-col items-stretch gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-center">
              <button
                type="button"
                onClick={onClearWithoutSaving}
                className="px-4 py-2 text-sm rounded border border-warm-200 dark:border-warm-700 text-warm-700 dark:text-warm-300 hover:bg-warm-50 dark:hover:bg-warm-700"
              >
                {t('filters.clearWithoutSaving')}
              </button>
              <button
                type="submit"
                disabled={!saveName.trim() || savingSearch}
                className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded bg-teal-600 text-white font-medium hover:bg-teal-700 disabled:opacity-50 disabled:cursor-wait"
              >
                {savingSearch && <SpinnerIcon className="w-4 h-4 animate-spin" />}
                {savingSearch ? t('saveSearch.saving') : t('filters.saveAndClear')}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
