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

interface LinkModalProps {
  isOpen: boolean;
  initialUrl: string;
  onConfirm: (url: string) => void;
  onCancel: () => void;
}

const LinkModal: React.FC<LinkModalProps> = ({ isOpen, initialUrl, onConfirm, onCancel }) => {
  const [url, setUrl] = useState(initialUrl);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen) {
      console.log('Модальное окно открыто, синхронизируем url с initialUrl:', initialUrl);
      setUrl(initialUrl);
      setError(null);
    }
  }, [isOpen, initialUrl]);

  const validateUrl = (value: string): boolean => {
    const urlPattern = /^(https?:\/\/)?([\w-]+\.)+[\w-]+(\/[\w-./?%&=]*)?$/i;
    const mailtoPattern = /^mailto:[\w-.]+@([\w-]+\.)+[\w-]{2,4}$/i;
    const telPattern = /^tel:\+?[0-9-]+$/i;
    return urlPattern.test(value) || mailtoPattern.test(value) || telPattern.test(value);
  };

  const handleApply = () => {
    if (!validateUrl(url) && url.trim() !== '') {
      setError('Пожалуйста, введите корректный URL (например, https://example.com)');
      return;
    }
    setError(null);
    console.log('handleApply вызван, URL:', url);
    onConfirm(url);
  };

  const handleRemoveLink = () => {
    console.log('Удаляем ссылку');
    onConfirm('');
  };

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      handleApply();
    } else if (e.key === 'Escape') {
      onCancel();
    }
  };

  const handleBackdropClick = (e: React.MouseEvent<HTMLDivElement>) => {
    if (e.target === e.currentTarget) {
      onCancel();
    }
  };

  useEffect(() => {
    const handleGlobalKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onCancel();
      }
    };

    document.addEventListener('keydown', handleGlobalKeyDown);
    return () => document.removeEventListener('keydown', handleGlobalKeyDown);
  }, [isOpen, onCancel]);

  if (!isOpen) return null;

  return (
      <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 transition-opacity duration-300 ease-in-out"
          onClick={handleBackdropClick}
      >
        <div className="bg-white rounded-lg p-6 max-w-sm w-full transform transition-all duration-300 ease-in-out scale-100 opacity-100">
          <h3 className="text-lg font-medium text-gray-900 mb-4">
            {initialUrl ? 'Редактировать ссылку' : 'Добавить ссылку'}
          </h3>
          <div>
            <input
                type="text"
                value={url}
                onChange={(e) => {
                  setUrl(e.target.value);
                  setError(null);
                }}
                onKeyDown={handleKeyDown}
                placeholder="Введите URL (например, https://example.com)"
                className={`w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 mb-4 transition-all duration-300 ${
                    error ? 'border-red-500' : initialUrl ? 'border-blue-500 bg-blue-50' : 'border-gray-300'
                }`}
                autoFocus
            />
            {error ? (
                <p className="text-red-500 text-sm mb-4">{error}</p>
            ) : (
                <p className="text-gray-500 text-sm mb-4">
                  {url.trim() === '' ? 'Введите URL или удалите ссылку' : 'Нажмите "Применить", чтобы сохранить изменения'}
                </p>
            )}
            <div className="flex justify-end space-x-3">
              {initialUrl && (
                  <button
                      type="button"
                      onClick={handleRemoveLink}
                      className="px-4 py-2 border border-red-300 text-sm font-medium rounded-md text-red-700 bg-white hover:bg-red-50 focus:outline-none"
                  >
                    Удалить
                  </button>
              )}
              <button
                  type="button"
                  onClick={onCancel}
                  className="px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
              >
                Отмена
              </button>
              <button
                  type="button"
                  onClick={handleApply}
                  className="px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none"
              >
                Применить
              </button>
            </div>
          </div>
        </div>
      </div>
  );
};

export default LinkModal;