import { useState } from 'preact/hooks';
import {
  MindforgeApiService,
  type FlashcardDifficulty,
  type FlashcardLibraryDetails,
} from '../services/MindforgeApiService';
import { FileTreeComponent } from './FileTreeComponent';
import { Button } from './Button';
import './FlashcardComponent.css';

const minAmount = 10;
const maxAmount = 50;

function difficultyLabel(difficulty: string) {
  return difficulty === 'Medium' ? 'Médio' : 'Fácil';
}

export function FlashcardComponent() {
  const [selectedPaths, setSelectedPaths] = useState<string[]>([]);
  const [amount, setAmount] = useState<number>(20);
  const [difficulty, setDifficulty] = useState<FlashcardDifficulty>('Easy');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [generatedLibraries, setGeneratedLibraries] = useState<FlashcardLibraryDetails[]>([]);

  const handleGenerate = async () => {
    if (selectedPaths.length === 0) {
      setError('Selecione pelo menos um arquivo do repositório para gerar os flashcards.');
      return;
    }

    setLoading(true);
    setError(null);

    try {
      const response = await MindforgeApiService.generateFlashcards({
        filePaths: selectedPaths,
        amount,
        difficulty,
      });

      setGeneratedLibraries(response.libraries);
    } catch (err: any) {
      setError(err?.message || 'Ocorreu um erro ao gerar os flashcards.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flashcard-container">
      <h2 className="flashcard-title">Gerador de Flashcards</h2>
      <p className="flashcard-subtitle">Selecione os arquivos do repositório para gerar bibliotecas de flashcards.</p>

      <div className="flashcard-form">
        <div className="input-group">
          <label>Arquivos do Repositório</label>
          <FileTreeComponent selectedPaths={selectedPaths} onSelectionChange={setSelectedPaths} />
          {selectedPaths.length > 0 && (
            <div className="selection-meta">
              {selectedPaths.length === 1 ? '1 arquivo selecionado' : `${selectedPaths.length} arquivos selecionados`}
            </div>
          )}
        </div>

        <div className="input-group">
          <label>Quantidade por arquivo ({minAmount} - {maxAmount})</label>
          <div className="slider-wrapper">
            <input
              type="range"
              className="slider-input"
              min={minAmount}
              max={maxAmount}
              value={amount}
              onInput={(e) => setAmount(parseInt((e.target as HTMLInputElement).value, 10))}
            />
            <span className="amount-display">{amount}</span>
          </div>
        </div>

        <div className="input-group">
          <label>Dificuldade</label>
          <div className="radio-group">
            <div className="radio-item">
              <input
                type="radio"
                id="difficulty-easy"
                name="difficulty"
                value="Easy"
                checked={difficulty === 'Easy'}
                onChange={() => setDifficulty('Easy')}
              />
              <label htmlFor="difficulty-easy" className="radio-label" title="Perguntas mais diretas e objetivas">
                Fácil
              </label>
            </div>
            <div className="radio-item">
              <input
                type="radio"
                id="difficulty-medium"
                name="difficulty"
                value="Medium"
                checked={difficulty === 'Medium'}
                onChange={() => setDifficulty('Medium')}
              />
              <label htmlFor="difficulty-medium" className="radio-label" title="Perguntas de nível intermediário">
                Médio
              </label>
            </div>
          </div>
        </div>

        <Button variant="primary" onClick={handleGenerate} disabled={loading} style={{ marginTop: '0.5rem' }}>
          {loading ? 'Gerando...' : 'Gerar Bibliotecas de Flashcards'}
        </Button>

        {error && <div className="flashcard-error">{error}</div>}
      </div>

      {loading && (
        <div class="loading-indicator">
          <span class="loading-dot"></span>
          <span>Gerando os flashcards com IA e salvando no banco. Aguarde...</span>
        </div>
      )}

      {generatedLibraries.length > 0 && (
        <div className="flashcard-result-panel">
          <h3>Bibliotecas Geradas</h3>
          <div className="flashcard-result-list">
            {generatedLibraries.map((library) => (
              <article key={library.id} className="flashcard-result-item">
                <div className="flashcard-result-header">
                  <strong>{library.fileName}</strong>
                  <span>{library.cardCount} cartões</span>
                </div>
                <div className="flashcard-result-meta">
                  <span>Matéria: {library.subject}</span>
                  <span>Dificuldade: {difficultyLabel(library.difficulty)}</span>
                </div>
              </article>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
