import { Shield } from 'lucide-react';

import type { SafetyQuizPage } from '@/business/safety-quiz/types';
import { ModuleHeader } from '@/components/ui/module-header';
import { StatePanel } from '@/components/ui/state-panel';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import { SafetyQuizCompliancePanel } from '@/components/safety-quiz/SafetyQuizCompliancePanel';
import { SafetyQuizCompletePanel } from '@/components/safety-quiz/SafetyQuizCompletePanel';
import { SafetyQuizContentEditorPanel } from '@/components/safety-quiz/SafetyQuizContentEditorPanel';
import { SafetyQuizFocusPanel } from '@/components/safety-quiz/SafetyQuizFocusPanel';
import { SafetyQuizIntroPanel } from '@/components/safety-quiz/SafetyQuizIntroPanel';
import { SafetyQuizQuestionPanel } from '@/components/safety-quiz/SafetyQuizQuestionPanel';
import { SafetyQuizRemindersPanel } from '@/components/safety-quiz/SafetyQuizRemindersPanel';

interface SafetyQuizViewProps {
  readonly page: SafetyQuizPage;
}

export function SafetyQuizView({ page }: SafetyQuizViewProps) {
  const quizConfigurationError = getSafetyQuizConfigurationError(page.quiz);

  return (
    <div className="space-y-6">
      <ModuleHeader
        title="Behavior Management"
        description="Weekly safety training, micro-quizzes, and compliance tracking"
        icon={Shield}
        iconClassName="bg-gradient-to-br from-blue-500 to-blue-600"
        iconShadowClassName="shadow-blue-500/30"
      />
      {!quizConfigurationError && page.quiz ? (
        <SafetyQuizFocusPanel weeklyFocus={page.quiz.weeklyFocus} />
      ) : null}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <SafetyQuizMainPanel page={page} />
        </div>
        <div className="space-y-4">
          <SafetyQuizSidebar page={page} hasConfigurationError={Boolean(quizConfigurationError)} />
          {page.canViewCompliance && (
            <SafetyQuizCompliancePanel
              rows={page.complianceRows}
              summary={page.completionSummary}
              isLoading={page.isComplianceLoading}
              error={page.complianceError}
            />
          )}
          {page.canManageQuizContent && <SafetyQuizContentEditorPanel />}
        </div>
      </div>
    </div>
  );
}

interface SafetyQuizSidebarProps {
  readonly page: SafetyQuizPage;
  readonly hasConfigurationError: boolean;
}

function SafetyQuizSidebar({ page, hasConfigurationError }: SafetyQuizSidebarProps) {
  if (page.isQuizLoading || page.quizError || !page.quiz || hasConfigurationError) {
    return null;
  }

  return (
    <SafetyQuizRemindersPanel reminders={page.quiz.keyReminders} />
  );
}

interface SafetyQuizMainPanelProps {
  readonly page: SafetyQuizPage;
}

function SafetyQuizMainPanel({ page }: SafetyQuizMainPanelProps) {
  const quizErrorMessage = getOptionalErrorMessage(page.quizError);
  const quiz = page.quiz;
  const quizConfigurationError = getSafetyQuizConfigurationError(quiz);
  const question = quiz?.questions[page.currentQuestionIndex] ?? null;

  if (page.isQuizLoading) {
    return (
      <StatePanel tone="sky" alignment="center" loading className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border-slate-700/40 py-16">
        Loading safety quiz...
      </StatePanel>
    );
  }

  if (quizErrorMessage) {
    return (
      <StatePanel tone="red" role="alert">
        {quizErrorMessage}
      </StatePanel>
    );
  }

  if (!quiz || quiz.questions.length === 0) {
    return (
      <StatePanel className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border-slate-700/40">
        No safety quiz is available for this week.
      </StatePanel>
    );
  }

  if (quizConfigurationError) {
    return (
      <StatePanel tone="red" role="alert">
        {quizConfigurationError}
      </StatePanel>
    );
  }

  if (page.stage === 'intro') {
    return (
      <SafetyQuizIntroPanel
        quiz={quiz}
        weekOf={page.weekOf}
        onStart={page.startQuiz}
      />
    );
  }

  if (page.stage === 'complete') {
    return (
      <SafetyQuizCompletePanel
        quiz={quiz}
        score={page.score}
        answers={page.answers}
        isSaving={page.isSavingResult}
        saveError={page.saveResultError}
        onReset={page.resetQuiz}
      />
    );
  }

  if (!question) {
    return (
      <StatePanel className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border-slate-700/40">
        Current quiz question is unavailable.
      </StatePanel>
    );
  }

  return (
    <SafetyQuizQuestionPanel
      question={question}
      questionIndex={page.currentQuestionIndex}
      questionCount={quiz.questions.length}
      score={page.score}
      selectedAnswer={page.selectedAnswer}
      showExplanation={page.showExplanation}
      onSelectAnswer={page.selectAnswer}
      onNextQuestion={() => {
        void page.goToNextQuestion();
      }}
    />
  );
}

function getSafetyQuizConfigurationError(quiz: SafetyQuizPage['quiz']): string | null {
  if (!quiz) {
    return null;
  }

  if (
    !quiz.weeklyFocus?.title
    || !quiz.weeklyFocus.description
    || !Array.isArray(quiz.keyReminders)
    || quiz.keyReminders.length === 0
  ) {
    return 'Safety quiz content is not fully configured.';
  }

  return null;
}
