import { Database, RotateCcw, Trophy } from 'lucide-react';

import { getSafetyQuizFeedback } from '@/business/safety-quiz/selectors';
import { Button } from '@/components/ui/button';
import { StatePanel } from '@/components/ui/state-panel';
import { getOptionalErrorMessage } from '@/shared/errors/errorMessages';
import type { SafetyQuiz } from '@/shared/types/app';

interface SafetyQuizCompletePanelProps {
  readonly quiz: SafetyQuiz;
  readonly score: number;
  readonly answers: readonly number[];
  readonly isSaving: boolean;
  readonly saveError: unknown;
  readonly onReset: () => void;
}

export function SafetyQuizCompletePanel({
  quiz,
  score,
  answers,
  isSaving,
  saveError,
  onReset,
}: SafetyQuizCompletePanelProps) {
  const saveErrorMessage = getOptionalErrorMessage(saveError);

  return (
    <div className="bg-slate-800/40 backdrop-blur-sm rounded-2xl border border-slate-700/40 p-6 text-center">
      <div className="w-20 h-20 rounded-2xl bg-gradient-to-br from-emerald-500 to-emerald-600 flex items-center justify-center mx-auto mb-4 shadow-xl shadow-emerald-500/20">
        <Trophy size={36} className="text-white" />
      </div>
      <h3 className="text-xl font-bold text-white mb-2">Quiz Complete!</h3>
      {isSaving && (
        <StatePanel tone="sky" alignment="center" loading className="border-0 bg-transparent py-2">
          Saving results...
        </StatePanel>
      )}
      {!isSaving && !saveError && (
        <p className="text-xs text-emerald-400 flex items-center justify-center gap-1 mb-2">
          <Database size={12} />
          Results saved to backend
        </p>
      )}
      {saveErrorMessage && <p className="text-xs text-red-400 mb-2">{saveErrorMessage}</p>}
      <p className="text-4xl font-bold bg-gradient-to-r from-emerald-400 to-blue-400 bg-clip-text text-transparent mb-2">
        {score}/{quiz.questions.length}
      </p>
      <p className="text-sm text-slate-400 mb-6">
        {getSafetyQuizFeedback(score, quiz.questions.length)}
      </p>
      <div className="text-left space-y-3 mb-6">
        {quiz.questions.map((question, index) => (
          <div
            key={question.id}
            className={`p-3 rounded-xl border ${answers[index] === question.correctIndex ? 'bg-emerald-500/10 border-emerald-500/20' : 'bg-red-500/10 border-red-500/20'}`}
          >
            <p className="text-sm font-medium text-slate-200">{index + 1}. {question.question}</p>
            <p className="text-xs text-slate-400 mt-1">{question.explanation}</p>
          </div>
        ))}
      </div>
      <Button
        type="button"
        onClick={onReset}
        leadingIcon={<RotateCcw size={14} />}
        className="flex items-center gap-2 mx-auto px-5 py-2.5 bg-blue-500/15 text-blue-400 rounded-xl font-medium text-sm hover:bg-blue-500/25 border border-blue-500/20"
      >
        Retake Quiz
      </Button>
    </div>
  );
}
