'use client';

import { forwardRef, useState, useEffect } from 'react';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import { MathFormula, validateFormula } from '@/components/math/MathFormula';
import { X, Check, ChevronRight, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * Common math symbols for quick input
 */
const MATH_SYMBOLS = [
  { label: '+', value: '+' },
  { label: '-', value: '-' },
  { label: '×', value: '\\times' },
  { label: '÷', value: '\\div' },
  { label: '=', value: '=' },
  { label: '≠', value: '\\neq' },
  { label: '√', value: '\\sqrt{}' },
  { label: 'x²', value: '^{2}' },
  { label: 'xⁿ', value: '^{}' },
  { label: '½', value: '\\frac{}{}' },
  { label: 'π', value: '\\pi' },
  { label: '∞', value: '\\infty' },
  { label: 'θ', value: '\\theta' },
  { label: 'α', value: '\\alpha' },
  { label: 'β', value: '\\beta' },
  { label: '∑', value: '\\sum' },
  { label: '∫', value: '\\int' },
  { label: '(', value: '\\left(' },
  { label: ')', value: '\\right)' },
  { label: '[', value: '\\left[' },
  { label: ']', value: '\\right]' },
];

/**
 * AnswerInput component props
 */
export interface AnswerInputProps {
  /**
   * Input value (LaTeX string)
   */
  value: string;

  /**
   * Change handler
   */
  onChange: (value: string) => void;

  /**
   * Submit handler
   */
  onSubmit: () => void;

  /**
   * Input placeholder
   */
  placeholder?: string;

  /**
   * Disable the input
   */
  disabled?: boolean;

  /**
   * Show live preview
   */
  showPreview?: boolean;

  /**
   * Show math symbol buttons
   */
  showSymbols?: boolean;

  /**
   * Additional CSS classes
   */
  className?: string;

  /**
   * Input label
   */
  label?: string;

  /**
   * Error message
   */
  error?: string;

  /**
   * Is the answer correct?
   */
  isCorrect?: boolean;

  /**
   * Is the answer incorrect?
   */
  isIncorrect?: boolean;

  /**
   * Show check/cross icons
   */
  showValidation?: boolean;

  /**
   * Ref for the input element
   */
  inputRef?: React.RefObject<HTMLInputElement>;
}

/**
 * AnswerInput component - math input with LaTeX support and live preview
 */
export const AnswerInput = forwardRef<HTMLDivElement, AnswerInputProps>(
  (
    {
      value,
      onChange,
      onSubmit,
      placeholder = 'Enter your answer...',
      disabled = false,
      showPreview = true,
      showSymbols = true,
      className,
      label = 'Your Answer',
      error,
      isCorrect,
      isIncorrect,
      showValidation = true,
      inputRef,
    },
    ref
  ) => {
    const [cursorPosition, setCursorPosition] = useState(0);
    const [previewError, setPreviewError] = useState<string | null>(null);

    // FIX: Validar fórmula en useEffect, NO durante render
    useEffect(() => {
      if (!showPreview || !value || value.length === 0) {
        setPreviewError(null);
        return;
      }
      
      const validation = validateFormula(value);
      if (!validation.isValid) {
        setPreviewError(validation.error ?? 'Fórmula inválida');
      } else {
        setPreviewError(null);
      }
    }, [value, showPreview]);

    // Handle keyboard shortcuts
    const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
      if (e.key === 'Enter' && !disabled && value.trim()) {
        e.preventDefault();
        onSubmit();
      }
    };

    // Insert math symbol at cursor position
    const insertSymbol = (symbol: string) => {
      const before = value.slice(0, cursorPosition);
      const after = value.slice(cursorPosition);
      const newValue = before + symbol + after;

      onChange(newValue);

      // Move cursor after inserted symbol
      setTimeout(() => {
        const newCursorPos = cursorPosition + symbol.length;
        setCursorPosition(newCursorPos);

        // Focus input and set cursor position
        if (inputRef?.current) {
          inputRef.current.focus();
          inputRef.current.setSelectionRange(newCursorPos, newCursorPos);
        }
      }, 0);
    };

    // Track cursor position
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      onChange(e.target.value);
      setCursorPosition(e.target.selectionStart ?? 0);
    };

    const handleInputClick = (e: React.MouseEvent<HTMLInputElement>) => {
      setCursorPosition(e.currentTarget.selectionStart ?? 0);
    };

    const handleInputSelect = (e: React.SyntheticEvent<HTMLInputElement>) => {
      const target = e.target as HTMLInputElement;
      setCursorPosition(target.selectionStart ?? 0);
    };

    // Clear input
    const handleClear = () => {
      onChange('');
      setCursorPosition(0);
      if (inputRef?.current) {
        inputRef.current.focus();
      }
    };

    return (
      <div ref={ref} className={cn('space-y-4', className)}>
        {/* Label */}
        {label && (
          <Label htmlFor="answer-input" className="text-base font-medium">
            {label}
          </Label>
        )}

        {/* Live Preview */}
        {showPreview && value.length > 0 && (
          <div className="bg-muted/50 rounded-lg p-4 border min-h-[60px] flex items-center justify-center">
            <div className="text-center">
              <p className="text-xs text-muted-foreground mb-2">Preview:</p>
              {/* FIX: Render condicional simple sin llamadas a función */}
              {previewError ? (
                <div className="text-destructive flex items-center gap-2 text-sm">
                  <AlertTriangle className="h-4 w-4" />
                  <span>{previewError}</span>
                </div>
              ) : value ? (
                <MathFormula formula={value} displayMode={false} />
              ) : (
                <span className="text-sm text-muted-foreground">Fórmula bloqueada por seguridad</span>
              )}
            </div>
          </div>
        )}

        {/* Input Field */}
        <div className="relative">
          <Input
            ref={inputRef}
            id="answer-input"
            type="text"
            value={value}
            onChange={handleInputChange}
            onKeyDown={handleKeyDown}
            onClick={handleInputClick}
            onSelect={handleInputSelect}
            placeholder={placeholder}
            disabled={disabled}
            className={cn(
              'pr-24 font-mono text-lg',
              error && 'border-destructive focus:border-destructive',
              isCorrect && 'border-green-500 focus:border-green-500',
              isIncorrect && 'border-red-500 focus:border-red-500'
            )}
            aria-invalid={!!error}
            aria-describedby={error ? 'answer-error' : undefined}
          />

          {/* Action Buttons */}
          <div className="absolute right-2 top-1/2 -translate-y-1/2 flex items-center gap-1">
            {value.length > 0 && !disabled && (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={handleClear}
                className="h-7 w-7 p-0"
                aria-label="Clear input"
              >
                <X className="h-4 w-4" />
              </Button>
            )}

            {showValidation && isCorrect && (
              <div className="h-7 w-7 rounded-full bg-green-500 flex items-center justify-center">
                <Check className="h-4 w-4 text-white" />
              </div>
            )}

            {showValidation && isIncorrect && (
              <div className="h-7 w-7 rounded-full bg-red-500 flex items-center justify-center">
                <X className="h-4 w-4 text-white" />
              </div>
            )}

            {!disabled && (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={onSubmit}
                disabled={!value || value.length === 0}
                className="h-7 w-7 p-0"
                aria-label="Submit answer"
              >
                <ChevronRight className="h-4 w-4" />
              </Button>
            )}
          </div>
        </div>

        {/* Error Message */}
        {error && (
          <p id="answer-error" className="text-sm text-destructive" role="alert">
            {error}
          </p>
        )}

        {/* Math Symbols Toolbar */}
        {showSymbols && !disabled && (
          <div className="space-y-2">
            <p className="text-xs text-muted-foreground font-medium">
              Quick insert:
            </p>
            <div className="flex flex-wrap gap-1.5">
              {MATH_SYMBOLS.map((symbol) => (
                <Button
                  key={symbol.value}
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={() => insertSymbol(symbol.value)}
                  className="h-8 min-w-[2.5rem] font-mono text-sm"
                  aria-label={`Insert ${symbol.label}`}
                >
                  {symbol.label}
                </Button>
              ))}
            </div>
          </div>
        )}

        {/* Help Text */}
        <p className="text-xs text-muted-foreground">
          Use LaTeX syntax for mathematical expressions. Press Enter to submit.
        </p>
      </div>
    );
  }
);

AnswerInput.displayName = 'AnswerInput';
