'use client';

import { useState, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { CheckCircle2, AlertCircle, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { FieldMessage } from '@/components/common/feedback/FieldMessage';
import { useTranslation } from '@/hooks/useTranslation';

export interface ValidationResult {
  valid: boolean;
  message?: string;
}

interface ValidatedInputProps {
  id?: string;
  label: string;
  value: string;
  onChange: (value: string) => void;
  onValidationChange?: (valid: boolean) => void;
  type?: string;
  placeholder?: string;
  required?: boolean;
  disabled?: boolean;
  className?: string;
  validator?: (value: string) => ValidationResult | Promise<ValidationResult>;
  validateOnBlur?: boolean;
  validateOnChange?: boolean;
  debounceMs?: number;
  helpText?: string;
}

export function ValidatedInput({
  id,
  label,
  value,
  onChange,
  onValidationChange,
  type = 'text',
  placeholder,
  required = false,
  disabled = false,
  className,
  validator,
  validateOnBlur = true,
  validateOnChange = true,
  debounceMs = 300,
  helpText,
}: ValidatedInputProps) {
  const { t } = useTranslation();
  const [touched, setTouched] = useState(false);
  const [validating, setValidating] = useState(false);
  const [validation, setValidation] = useState<ValidationResult>({ valid: true });

  // Debounced validation
  useEffect(() => {
    if (!validateOnChange || !validator || !touched || !value) {
      return;
    }

    setValidating(true);
    const timeoutId = setTimeout(async () => {
      try {
        const result = await Promise.resolve(validator(value));
        setValidation(result);
        onValidationChange?.(result.valid);
      } catch (error) {
        setValidation({ valid: false, message: t.common.validationFailed });
        onValidationChange?.(false);
      } finally {
        setValidating(false);
      }
    }, debounceMs);

    return () => clearTimeout(timeoutId);
  }, [value, validator, validateOnChange, debounceMs, touched, onValidationChange]);

  const handleBlur = async () => {
    setTouched(true);
    if (validateOnBlur && validator && value) {
      setValidating(true);
      try {
        const result = await Promise.resolve(validator(value));
        setValidation(result);
        onValidationChange?.(result.valid);
      } catch (error) {
        setValidation({ valid: false, message: t.common.validationFailed });
        onValidationChange?.(false);
      } finally {
        setValidating(false);
      }
    }
  };

  const showError = touched && !validation.valid && !validating;
  const showSuccess = touched && validation.valid && value && !validating;

  return (
    <div className={cn('space-y-2', className)}>
      <Label htmlFor={id} className="flex items-center gap-1">
        {label}
        {required && <span className="text-red-500">*</span>}
      </Label>
      
      <div className="relative">
        <Input
          id={id}
          type={type}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onBlur={handleBlur}
          placeholder={placeholder}
          disabled={disabled}
          className={cn(
            showError && 'border-red-500 focus-visible:ring-red-500',
            showSuccess && 'border-green-500 focus-visible:ring-green-500'
          )}
        />
        
        {/* Validation Status Icon */}
        <div className="absolute right-3 top-1/2 -translate-y-1/2">
          {validating && <Loader2 className="h-4 w-4 animate-spin text-gray-400" />}
          {showSuccess && <CheckCircle2 className="h-4 w-4 text-green-500" />}
          {showError && <AlertCircle className="h-4 w-4 text-red-500" />}
        </div>
      </div>

      {/* Help Text or Error Message */}
      {showError && validation.message && (
        <FieldMessage variant="error" message={validation.message} />
      )}
      
      {!showError && helpText && (
        <p className="text-sm text-gray-500">{helpText}</p>
      )}
    </div>
  );
}
