import * as React from 'react';
import { useState, useEffect } from 'react';
import {
  validateIpAddress,
  type ValidationResult,
} from '../utils/ipValidation';

interface IpAddressInputProps {
  initialValue?: string;
  name: string;
  id?: string;
  placeholder?: string;
  onChange?: (value: string, isValid: boolean) => void;
  className?: string;
}

const IpAddressInput: React.FC<IpAddressInputProps> = ({
  initialValue = '',
  name = 'ip_address_role[ip_address]',
  id,
  placeholder = 'Example: 192.168.1.1, 2001:db8::1, or 10.0.0.0/24',
  onChange,
  className = '',
}) => {
  const [value, setValue] = useState(initialValue);
  const [validation, setValidation] = useState<ValidationResult>({
    isValid: true,
    message: '',
    type: 'none',
  });
  const [isFocused, setIsFocused] = useState(false);

  // Update validation when value changes
  useEffect(() => {
    const result = validateIpAddress(value);
    setValidation(result);

    // Call onChange callback if provided
    if (onChange) {
      onChange(value, result.isValid);
    }
  }, [value, onChange]);

  // Get border color based on validation state
  const getBorderColorClass = () => {
    if (!isFocused) return 'border-slate-300';
    if (value === '') return 'border-sky-500';
    return validation.isValid ? 'border-emerald-500' : 'border-red-500';
  };

  return (
    <div className="relative">
      <input
        type="text"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        onFocus={() => setIsFocused(true)}
        onBlur={() => setIsFocused(false)}
        placeholder={placeholder}
        className={`block w-full rounded-md font-mono shadow-sm focus:ring-sky-500 sm:text-sm ${getBorderColorClass()} ${className}`}
        id={id || 'ip_address_input'}
      />

      {/* This is a direct input that will be properly included in form submission */}
      <input
        type="text"
        name={name}
        value={value}
        readOnly
        style={{ display: 'none' }}
      />

      {/* Validation feedback */}
      {value !== '' && (
        <div
          className={`mt-1 text-sm ${validation.isValid ? 'text-emerald-600' : 'text-red-600'}`}
        >
          <div className="flex items-center">
            {validation.isValid ? (
              <svg
                className="mr-1 h-4 w-4"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
                  clipRule="evenodd"
                />
              </svg>
            ) : (
              <svg
                className="mr-1 h-4 w-4"
                fill="currentColor"
                viewBox="0 0 20 20"
              >
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                  clipRule="evenodd"
                />
              </svg>
            )}
            <span>{validation.message}</span>
          </div>
        </div>
      )}

      {/* Additional helpful information */}
      <div className="mt-2 min-w-[400px] text-sm text-slate-500">
        <div className="flex items-center">
          {validation.type === 'cidr-v4' || validation.type === 'cidr-v6' ? (
            <span>
              CIDR notation represents an IP range (e.g., 10.0.0.0/24 for IPv4
              or 2001:db8::/32 for IPv6)
            </span>
          ) : (
            <span>
              Enter a single IP address (IPv4: 192.168.1.1 or IPv6: 2001:db8::1)
              or an IP range in CIDR notation
            </span>
          )}
        </div>
      </div>
    </div>
  );
};

export default IpAddressInput;
