'use client';

import { Suspense } from 'react';
import { motion } from 'framer-motion';
import { RotateCcw, Home, Loader2, Sparkles } from 'lucide-react';
import Link from 'next/link';
import { useParams, useSearchParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { ScoreCard } from '@/components/cards/score-card';
import { submissionApi } from '@/services/api/submission';

export default function SubmissionResultPage() {
  return (
    <Suspense fallback={<div className="flex items-center justify-center py-20"><Loader2 className="h-6 w-6 animate-spin text-muted-foreground" /></div>}>
      <SubmissionResultContent />
    </Suspense>
  );
}

function getScoreEmoji(score: number) {
  if (score >= 90) return '🌟';
  if (score >= 75) return '👏';
  if (score >= 60) return '💪';
  return '📖';
}

function SubmissionResultContent() {
  const params = useParams();
  const searchParams = useSearchParams();
  const submissionId = params.id as string;
  const verseId = searchParams.get('verseId') ?? '';

  const { data: result, isLoading, isError } = useQuery({
    queryKey: ['submission-result', submissionId],
    queryFn: () => submissionApi.generateMockResult(submissionId, verseId),
    enabled: !!submissionId,
  });

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-24 text-center">
        <motion.div
          animate={{ scale: [1, 1.1, 1] }}
          transition={{ duration: 1.4, repeat: Infinity }}
          className="flex h-16 w-16 items-center justify-center rounded-full bg-primary/10 mb-5"
        >
          <Sparkles className="h-7 w-7 text-primary" />
        </motion.div>
        <p className="font-heading text-lg font-semibold">Menganalisis bacaan Anda...</p>
        <p className="mt-1 text-sm text-muted-foreground max-w-xs">
          AI sedang memeriksa kemiripan, kelancaran, dan pelafalan hafalan Anda.
        </p>
      </div>
    );
  }

  if (isError || !result) {
    return (
      <div className="flex flex-col items-center justify-center py-24 text-center">
        <p className="text-sm text-muted-foreground">Gagal memuat hasil latihan.</p>
        <Button asChild variant="outline" className="mt-4 rounded-xl">
          <Link href="/dashboard">Ke Dashboard</Link>
        </Button>
      </div>
    );
  }

  const { scores, feedback, isNewRecord } = result;

  return (
    <>
      <title>Hasil Latihan | Nadhom Smart</title>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        className="space-y-5 py-4"
      >
        {/* Overall Score */}
        <motion.div
          initial={{ scale: 0.8, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ delay: 0.2, type: 'spring' }}
          className="text-center"
        >
          <p className="text-5xl mb-2">{getScoreEmoji(scores.overall)}</p>
          <div className="inline-flex items-baseline gap-1">
            <span className="font-heading text-5xl font-bold text-primary">
              {scores.overall}
            </span>
            <span className="text-lg text-muted-foreground">/100</span>
          </div>
          <p className="text-sm font-medium text-muted-foreground mt-1">Skor Keseluruhan</p>
          {isNewRecord && (
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
              className="mt-2 inline-flex items-center gap-1.5 rounded-full bg-secondary/10 px-3 py-1"
            >
              <span className="text-sm">🏆</span>
              <span className="text-xs font-semibold text-secondary">Rekor Baru!</span>
            </motion.div>
          )}
        </motion.div>

        {/* Score Breakdown */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.3 }}
          className="grid grid-cols-1 gap-3"
        >
          <ScoreCard label="Kemiripan" score={scores.similarity} />
          <ScoreCard label="Kelancaran" score={scores.fluency} />
          <ScoreCard label="Pengucapan" score={scores.pronunciation} />
        </motion.div>

        {/* AI Feedback */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.4 }}
        >
          <Card className="border-border/50">
            <CardContent className="py-4 px-5">
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">
                Catatan AI
              </p>
              <p className="text-sm text-card-foreground leading-relaxed">
                {feedback}
              </p>
            </CardContent>
          </Card>
        </motion.div>

        {/* Actions */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.5 }}
          className="flex gap-3"
        >
          <Button variant="outline" className="flex-1 rounded-xl gap-2" asChild>
            <Link href={verseId ? `/submit?verseId=${verseId}` : '/verses'}>
              <RotateCcw className="h-4 w-4" />
              Latihan Lagi
            </Link>
          </Button>
          <Button className="flex-1 rounded-xl gap-2 gradient-primary border-0 text-white" asChild>
            <Link href="/dashboard">
              <Home className="h-4 w-4" />
              Dashboard
            </Link>
          </Button>
        </motion.div>
      </motion.div>
    </>
  );
}
