import { useEffect, useMemo, useState } from 'preact/hooks';
import {
  MindforgeApiService,
  type FlashcardCard,
  type FlashcardRagCard,
  type FlashcardRagDashboardResponse,
  type FlashcardRagStatus,
} from '../services/MindforgeApiService';
import { Button } from './Button';
import './SpacedReviewComponent.css';

interface RagStatusOption {
  status: FlashcardRagStatus;
  label: string;
}

const STATUS_OPTIONS: RagStatusOption[] = [
  { status: 'Red', label: 'Vermelho' },
  { status: 'Amber', label: 'Amarelo' },
  { status: 'Green', label: 'Verde' },
  { status: 'Grey', label: 'Cinza' },
];

const STATUS_PRIORITY: Record<FlashcardRagStatus, number> = {
  Red: 0,
  Amber: 1,
  Green: 2,
  Grey: 3,
};

function buildGroupKey(subject: string, subSubject: string) {
  return `${subject}::${subSubject}`;
}

function shuffleCards(cards: FlashcardCard[]) {
  const shuffled = [...cards];

  for (let i = shuffled.length - 1; i > 0; i--) {
    const randomIndex = Math.floor(Math.random() * (i + 1));
    [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[i]];
  }

  return shuffled;
}

function formatPercentage(value: number) {
  return `${value.toFixed(2).replace('.', ',')}%`;
}

function summaryText(activeCount: number, greenPercentage: number, attentionPercentage: number) {
  if (activeCount === 0) {
    return 'Sem revisoes avaliaveis';
  }

  return `Verde ${formatPercentage(greenPercentage)} | Atencao ${formatPercentage(attentionPercentage)}`;
}

function formatPerformance(rate: number) {
  return `${Math.round(rate * 100)}%`;
}

function orderCardsForSession(cards: FlashcardCard[], ragByCardId: Map<number, FlashcardRagCard>) {
  const buckets: FlashcardCard[][] = [[], [], [], []];

  cards.forEach((card) => {
    const ragCard = ragByCardId.get(card.id);
    const status = ragCard?.ragStatus || 'Grey';
    buckets[STATUS_PRIORITY[status]].push(card);
  });

  return buckets.flatMap((bucket) => shuffleCards(bucket));
}

export function SpacedReviewComponent() {
  const [dashboard, setDashboard] = useState<FlashcardRagDashboardResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedStatuses, setSelectedStatuses] = useState<FlashcardRagStatus[]>(['Red', 'Amber']);
  const [selectedGroupKeys, setSelectedGroupKeys] = useState<string[]>([]);
  const [startingSession, setStartingSession] = useState(false);
  const [sessionCards, setSessionCards] = useState<FlashcardCard[]>([]);
  const [sessionSourceCards, setSessionSourceCards] = useState<FlashcardRagCard[]>([]);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [showAnswer, setShowAnswer] = useState(false);
  const [submittingAnswer, setSubmittingAnswer] = useState(false);

  const loadDashboard = async (preserveSelection: boolean) => {
    setLoading(true);
    setError(null);

    try {
      const response = await MindforgeApiService.getFlashcardRagStatus();
      setDashboard(response);

      const allGroupKeys = response.subjects.flatMap((subjectGroup) =>
        subjectGroup.subSubjects.map((subSubjectGroup) =>
          buildGroupKey(subjectGroup.subject, subSubjectGroup.subSubject)),
      );

      setSelectedGroupKeys((current) => {
        if (!preserveSelection || current.length === 0) {
          return allGroupKeys;
        }

        const available = new Set(allGroupKeys);
        const kept = current.filter((key) => available.has(key));
        return kept.length > 0 ? kept : allGroupKeys;
      });
    } catch (err: any) {
      setError(err?.message || 'Falha ao carregar status de revisao espacada.');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    let cancelled = false;

    async function runLoad() {
      if (cancelled) {
        return;
      }
      await loadDashboard(false);
    }

    runLoad();
    return () => {
      cancelled = true;
    };
  }, []);

  const ragCards = useMemo(() => {
    if (!dashboard) {
      return [];
    }

    return dashboard.subjects.flatMap((subjectGroup) =>
      subjectGroup.subSubjects.flatMap((subSubjectGroup) => subSubjectGroup.cards));
  }, [dashboard]);

  const selectedRagCards = useMemo(() => {
    const selectedGroups = new Set(selectedGroupKeys);
    const selectedStatusSet = new Set(selectedStatuses);

    return ragCards.filter((card) =>
      selectedGroups.has(buildGroupKey(card.subject, card.subSubject))
      && selectedStatusSet.has(card.ragStatus));
  }, [ragCards, selectedGroupKeys, selectedStatuses]);

  const sessionSourceById = useMemo(() => {
    return new Map(sessionSourceCards.map((card) => [card.cardId, card]));
  }, [sessionSourceCards]);

  const currentCard = sessionCards[currentIndex];
  const currentCardMetadata = currentCard ? sessionSourceById.get(currentCard.id) : undefined;

  const progressPercent = sessionCards.length > 0
    ? ((currentIndex + 1) / sessionCards.length) * 100
    : 0;

  const toggleStatus = (status: FlashcardRagStatus) => {
    if (selectedStatuses.includes(status)) {
      setSelectedStatuses(selectedStatuses.filter((value) => value !== status));
      return;
    }

    setSelectedStatuses([...selectedStatuses, status]);
  };

  const toggleGroup = (groupKey: string) => {
    if (selectedGroupKeys.includes(groupKey)) {
      setSelectedGroupKeys(selectedGroupKeys.filter((key) => key !== groupKey));
      return;
    }

    setSelectedGroupKeys([...selectedGroupKeys, groupKey]);
  };

  const startSession = async () => {
    if (selectedStatuses.length === 0) {
      setError('Selecione ao menos um status para iniciar a revisao.');
      return;
    }

    if (selectedGroupKeys.length === 0) {
      setError('Selecione ao menos uma submateria para iniciar a revisao.');
      return;
    }

    if (selectedRagCards.length === 0) {
      setError('Nenhum card encontrado com os filtros selecionados.');
      return;
    }

    setStartingSession(true);
    setError(null);

    try {
      const ragByCardId = new Map(selectedRagCards.map((card) => [card.cardId, card]));
      const libraryIds = Array.from(new Set(selectedRagCards.map((card) => card.libraryId)));
      const response = await MindforgeApiService.createFlashcardReviewSession({ libraryIds });
      const selectedCardIds = new Set(selectedRagCards.map((card) => card.cardId));
      const filteredCards = response.cards.filter((card) => selectedCardIds.has(card.id));
      const orderedCards = orderCardsForSession(filteredCards, ragByCardId);

      if (orderedCards.length === 0) {
        setError('Os filtros selecionados nao retornaram cards para revisar.');
        return;
      }

      setSessionSourceCards(selectedRagCards);
      setSessionCards(orderedCards);
      setCurrentIndex(0);
      setShowAnswer(false);
    } catch (err: any) {
      setError(err?.message || 'Falha ao iniciar revisao espacada.');
    } finally {
      setStartingSession(false);
    }
  };

  const endSession = () => {
    setSessionCards([]);
    setSessionSourceCards([]);
    setCurrentIndex(0);
    setShowAnswer(false);
    setSubmittingAnswer(false);
    void loadDashboard(true);
  };

  const goToPrevious = () => {
    if (currentIndex === 0) {
      return;
    }
    setCurrentIndex(currentIndex - 1);
    setShowAnswer(false);
  };

  const registerAnswer = async (correct: boolean) => {
    if (!currentCard) {
      return;
    }

    setSubmittingAnswer(true);
    setError(null);

    try {
      await MindforgeApiService.recordFlashcardReviewAnswer({
        cardId: currentCard.id,
        correct,
      });

      if (currentIndex >= sessionCards.length - 1) {
        endSession();
        return;
      }

      setCurrentIndex(currentIndex + 1);
      setShowAnswer(false);
    } catch (err: any) {
      setError(err?.message || 'Falha ao registrar resposta da revisao.');
    } finally {
      setSubmittingAnswer(false);
    }
  };

  return (
    <div className="spaced-review-container">
      <h2 className="title spaced-review-title">Revisao espacada</h2>
      <p className="subtitle">Acompanhe o status RAG dos cards por materia e submateria.</p>

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

      {sessionCards.length === 0 && (
        <div className="spaced-review-panel">
          {loading && <p className="spaced-review-state">Carregando painel de revisao...</p>}
          {!loading && (!dashboard || dashboard.subjects.length === 0) && (
            <p className="spaced-review-state">Nenhum flashcard encontrado para revisar.</p>
          )}

          {!loading && dashboard && dashboard.subjects.length > 0 && (
            <>
              <div className="spaced-review-filters">
                {STATUS_OPTIONS.map((option) => (
                  <label key={option.status} className="spaced-review-filter">
                    <input
                      type="checkbox"
                      checked={selectedStatuses.includes(option.status)}
                      onChange={() => toggleStatus(option.status)}
                    />
                    <span>{option.label}</span>
                  </label>
                ))}
              </div>

              <div className="spaced-review-subjects">
                {dashboard.subjects.map((subjectGroup) => (
                  <section key={subjectGroup.subject} className="spaced-review-subject">
                    <header className="spaced-review-subject-header">
                      <h3>{subjectGroup.subject}</h3>
                      <p>{summaryText(
                        subjectGroup.summary.activeCount,
                        subjectGroup.summary.greenPercentage,
                        subjectGroup.summary.attentionPercentage,
                      )}</p>
                      <small>
                        Verde: {subjectGroup.summary.greenCount} | Amarelo: {subjectGroup.summary.amberCount}
                        {' '}
                        | Vermelho: {subjectGroup.summary.redCount} | Cinza: {subjectGroup.summary.greyCount}
                      </small>
                    </header>

                    <div className="spaced-review-subsubject-list">
                      {subjectGroup.subSubjects.map((subSubjectGroup) => {
                        const groupKey = buildGroupKey(subjectGroup.subject, subSubjectGroup.subSubject);
                        const checked = selectedGroupKeys.includes(groupKey);

                        return (
                          <label key={groupKey} className="spaced-review-subsubject-item">
                            <input
                              type="checkbox"
                              checked={checked}
                              onChange={() => toggleGroup(groupKey)}
                            />
                            <div className="spaced-review-subsubject-texts">
                              <strong>{subSubjectGroup.subSubject}</strong>
                              <span>{summaryText(
                                subSubjectGroup.summary.activeCount,
                                subSubjectGroup.summary.greenPercentage,
                                subSubjectGroup.summary.attentionPercentage,
                              )}</span>
                              <small>
                                Cards: {subSubjectGroup.cards.length} | Cinza: {subSubjectGroup.summary.greyCount}
                              </small>
                            </div>
                          </label>
                        );
                      })}
                    </div>
                  </section>
                ))}
              </div>
            </>
          )}

          <div className="spaced-review-footer">
            <p>
              Cards selecionados: <strong>{selectedRagCards.length}</strong>
            </p>
            <Button
              variant="primary"
              disabled={startingSession || selectedRagCards.length === 0}
              onClick={startSession}
            >
              {startingSession ? 'Iniciando...' : 'Iniciar Revisao Espacada'}
            </Button>
          </div>
        </div>
      )}

      {sessionCards.length > 0 && currentCard && (
        <div className="spaced-review-session-panel">
          <div className="spaced-review-progress">
            <span>{currentIndex + 1} / {sessionCards.length}</span>
            <div className="spaced-review-progress-bar">
              <div className="spaced-review-progress-fill" style={{ width: `${progressPercent}%` }} />
            </div>
          </div>

          <article className="spaced-review-card">
            <header>
              <small>
                {currentCardMetadata?.fileName || 'Arquivo'} - {currentCardMetadata?.subject || 'Geral'} - {currentCardMetadata?.subSubject || 'Geral'}
              </small>
            </header>

            <h3>Frente</h3>
            <p>{currentCard.front}</p>

            {showAnswer && (
              <>
                <h3>Verso</h3>
                <p>{currentCard.back}</p>
                <div className="spaced-review-card-meta">
                  <span>Desempenho: {currentCardMetadata ? formatPerformance(currentCardMetadata.performanceRate) : '-'}</span>
                  <span>Status: {currentCardMetadata?.ragStatus || 'Grey'}</span>
                </div>
              </>
            )}
          </article>

          <div className="spaced-review-session-actions">
            <Button variant="secondary" onClick={goToPrevious} disabled={currentIndex === 0 || submittingAnswer}>
              Anterior
            </Button>

            {!showAnswer && (
              <Button variant="primary" onClick={() => setShowAnswer(true)}>
                Revelar Resposta
              </Button>
            )}

            {showAnswer && (
              <>
                <Button variant="primary" onClick={() => registerAnswer(true)} disabled={submittingAnswer}>
                  Acertei
                </Button>
                <Button variant="secondary" onClick={() => registerAnswer(false)} disabled={submittingAnswer}>
                  Errei
                </Button>
              </>
            )}

            <Button variant="secondary" onClick={endSession}>
              Encerrar Sessao
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}
