'use client';

import { useState, useRef } from 'react';
import { CheckSquare2, Calendar, Circle, PlayCircle } from 'lucide-react';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { ToggleButton } from '@/components/ui/ToggleButton';

export interface AddFormOption {
  value: string;
  label: string;
  icon?: React.ReactNode;
  color?: string;
}

interface AddFormProps {
  onAdd: (text: string, option?: string) => Promise<void>;
  disabled?: boolean;
  placeholder?: string;
  options?: AddFormOption[];
  defaultOption?: string;
  className?: string;
}

export function DailyAddForm({
  onAdd,
  disabled = false,
  placeholder = 'Ajouter un élément...',
  options = [],
  defaultOption,
  className = '',
}: AddFormProps) {
  const [newItemText, setNewItemText] = useState('');
  const [selectedOption, setSelectedOption] = useState<string>(
    defaultOption || (options.length > 0 ? options[0].value : '')
  );
  const inputRef = useRef<HTMLInputElement>(null);

  const handleAddItem = () => {
    if (!newItemText.trim()) return;

    const text = newItemText.trim();

    // Vider et refocus IMMÉDIATEMENT pour l'UX optimiste
    setNewItemText('');
    inputRef.current?.focus();

    // Lancer l'ajout en arrière-plan (fire and forget)
    onAdd(text, selectedOption).catch((error) => {
      console.error("Erreur lors de l'ajout:", error);
      // En cas d'erreur, on pourrait restaurer le texte
      // setNewItemText(text);
    });
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      handleAddItem();
    }
  };

  const getPlaceholder = () => {
    if (placeholder !== 'Ajouter un élément...') return placeholder;

    if (options.length > 0) {
      const selectedOptionData = options.find(
        (opt) => opt.value === selectedOption
      );
      if (selectedOptionData) {
        return `Ajouter ${selectedOptionData.label.toLowerCase()}...`;
      }
    }

    return placeholder;
  };

  const getDefaultIcon = (value: string): React.ReactNode => {
    switch (value) {
      case 'task':
        return <CheckSquare2 size={14} />;
      case 'meeting':
        return <Calendar size={14} />;
      case 'event':
        return <PlayCircle size={14} />;
      default:
        return <Circle size={14} />;
    }
  };

  const getToggleVariant = (
    option: AddFormOption
  ): 'primary' | 'accent' | 'secondary' => {
    if (option.color) {
      switch (option.color.toLowerCase()) {
        case 'green':
        case 'blue':
          return 'primary';
        case 'yellow':
        case 'orange':
          return 'accent';
        default:
          return 'secondary';
      }
    }

    // Couleurs par défaut selon le type
    switch (option.value) {
      case 'task':
        return 'primary';
      case 'meeting':
        return 'primary';
      default:
        return 'secondary';
    }
  };

  return (
    <div className={`space-y-2 ${className}`}>
      {/* Sélecteur d'options */}
      {options.length > 0 && (
        <div className="flex gap-2">
          {options.map((option) => (
            <ToggleButton
              key={option.value}
              onClick={() => setSelectedOption(option.value)}
              variant={getToggleVariant(option)}
              size="sm"
              isActive={selectedOption === option.value}
              disabled={disabled}
              icon={option.icon ?? getDefaultIcon(option.value)}
            >
              <span className="text-xs">{option.label}</span>
            </ToggleButton>
          ))}
        </div>
      )}

      {/* Champ de saisie et bouton d'ajout */}
      <div className="flex gap-2">
        <Input
          ref={inputRef}
          type="text"
          placeholder={getPlaceholder()}
          value={newItemText}
          onChange={(e) => setNewItemText(e.target.value)}
          onKeyDown={handleKeyPress}
          disabled={disabled}
          className="flex-1 min-w-[300px]"
        />
        <Button
          onClick={handleAddItem}
          disabled={!newItemText.trim() || disabled}
          variant="primary"
          size="sm"
          className="min-w-[40px]"
        >
          +
        </Button>
      </div>
    </div>
  );
}
