import { useState, useEffect, useRef } from 'react';
import { cn } from '@/lib/utils';
import { validateStackName } from '@/lib/validation';
import { TypewriterText } from './TypewriterText';
import type { TranslationKey } from '@/lib/i18n';

interface DeployFormProps {
  t: (key: TranslationKey) => string;
  onDeploy: (name: string) => void;
  isDeploying: boolean;
}

type ValidationStatus = 'idle' | 'checking' | 'valid' | 'invalid';

export function DeployForm({ t, onDeploy, isDeploying }: DeployFormProps) {
  const [name, setName] = useState('');
  const [validationStatus, setValidationStatus] = useState<ValidationStatus>('idle');
  const [validationMessage, setValidationMessage] = useState('');
  const checkTimeoutRef = useRef<NodeJS.Timeout>(undefined);

  useEffect(() => {
    if (!name) {
      setValidationStatus('idle');
      setValidationMessage('');
      return;
    }

    const validation = validateStackName(name);
    if (!validation.valid && validation.error) {
      setValidationStatus('invalid');
      setValidationMessage(t(validation.error));
      return;
    }

    setValidationStatus('checking');
    setValidationMessage(t('checkingAvailability'));

    if (checkTimeoutRef.current) {
      clearTimeout(checkTimeoutRef.current);
    }

    checkTimeoutRef.current = setTimeout(async () => {
      try {
        const response = await fetch(`/api/check/${validation.name}`);
        const data = await response.json();

        if (data.available && data.valid) {
          setValidationStatus('valid');
          setValidationMessage(t('nameAvailable'));
        } else {
          setValidationStatus('invalid');
          setValidationMessage(data.error || t('nameNotAvailable'));
        }
      } catch {
        setValidationStatus('invalid');
        setValidationMessage(t('checkFailed'));
      }
    }, 500);

    return () => {
      if (checkTimeoutRef.current) {
        clearTimeout(checkTimeoutRef.current);
      }
    };
  }, [name, t]);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (validationStatus === 'valid') {
      onDeploy(name.trim().toLowerCase());
    }
  };

  const previewName = name || t('yournamePlaceholder');

  return (
    <div className="backdrop-blur-md bg-black/20 rounded-2xl p-10 border border-white/10 shadow-2xl transition-all hover:border-white/20">
      <h2 className="text-2xl font-bold mb-4 min-h-[2.4rem] text-white">
        <TypewriterText text={t('chooseStackName')} />
      </h2>
      
      <p className="text-gray-400 mb-8 text-[0.95rem]">
        {t('availableAt')}{' '}
        <strong className="text-blue-400 font-medium">
          {previewName}.ai.flexinit.nl
        </strong>
      </p>

      <form onSubmit={handleSubmit}>
        <div className="mb-6">
          <label className="block font-medium mb-2 text-gray-400 text-sm">
            {t('stackName')}
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value.toLowerCase())}
            placeholder={t('placeholder')}
            className={cn(
              'w-full py-3 px-4 bg-white/5 border border-white/10 rounded-xl',
              'text-xl font-mono text-white placeholder-gray-600',
              'focus:outline-none focus:border-white/30 focus:bg-white/10 transition-all',
              validationStatus === 'invalid' && 'border-red-500/50 focus:border-red-500',
              validationStatus === 'valid' && 'border-green-500/50 focus:border-green-500',
              validationStatus === 'checking' && 'border-blue-400/50 focus:border-blue-400'
            )}
            autoComplete="off"
            disabled={isDeploying}
          />
          <p className="text-sm text-gray-500 mt-2">{t('inputHint')}</p>
          
          {validationMessage && (
            <p
              className={cn(
                'text-sm mt-2 min-h-[1.25rem]',
                validationStatus === 'invalid' && 'text-red-400',
                validationStatus === 'valid' && 'text-green-400',
                validationStatus === 'checking' && 'text-gray-400'
              )}
            >
              {validationMessage}
            </p>
          )}
        </div>

        <button
          type="submit"
          disabled={validationStatus !== 'valid' || isDeploying}
          className={cn(
            'w-full flex items-center justify-center gap-2',
            'py-3.5 px-6 rounded-xl font-semibold text-base',
            'transition-all duration-300',
            validationStatus === 'valid' && !isDeploying
              ? 'bg-white text-black hover:bg-white/90 shadow-[0_0_15px_rgba(255,255,255,0.1)] hover:translate-y-[-2px]'
              : 'bg-white/5 text-gray-500 border border-white/5 cursor-not-allowed'
          )}
        >
          <span>{isDeploying ? t('deployingText') : t('deployBtn')}</span>
          {!isDeploying && (
            <svg className="w-5 h-5 rtl:scale-x-[-1]" viewBox="0 0 20 20" fill="none">
              <path d="M10 4V16M4 10H16" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
            </svg>
          )}
        </button>
      </form>
    </div>
  );
}
