'use client';

import { useState, useEffect } from 'react';
import { useParams } from 'next/navigation';
import { motion } from 'framer-motion';
import { Bookmark, BookmarkCheck, ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import { AudioPlayer } from '@/components/audio/audio-player';
import { PracticeRecorderSheet } from '@/components/practice/practice-recorder-sheet';
import { PracticeHistory } from '@/components/practice/practice-history';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { verseApi } from '@/services/api/verse';
import { practiceApi } from '@/services/api/practice';
import { submissionApi } from '@/services/api/submission';
import { SubmissionList } from './submission-list';

export default function VerseDetailPage() {
  const params = useParams();
  const verseId = params.id as string;
  const queryClient = useQueryClient();

  const { data: verse, isLoading } = useQuery({
    queryKey: ['verse', verseId],
    queryFn: () => verseApi.getVerse(verseId),
    enabled: !!verseId,
  });

  const handlePracticeSubmit = async ({ audio, durationSeconds }: { audio: File; durationSeconds: number }) => {
    await practiceApi.createPractice({ verseId, audio, durationSeconds });
    toast.success('Latihan terkirim! AI sedang menganalisis bacaan Anda.');
    queryClient.invalidateQueries({ queryKey: ['my-practices', verseId] });
  };

  const handleSetoranSubmit = async ({ audio, durationSeconds }: { audio: File; durationSeconds: number }) => {
    await submissionApi.createSubmission({ verseId, audio, durationSeconds });
    toast.success('Setoran terkirim! Menunggu review guru.');
    queryClient.invalidateQueries({ queryKey: ['my-submissions', verseId] });
  };

  const [isBookmarked, setIsBookmarked] = useState(false);

  useEffect(() => {
    if (verse?.isBookmarked !== undefined) {
      setIsBookmarked(verse.isBookmarked);
    }
  }, [verse]);

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-20 text-muted-foreground">
        <Loader2 className="h-8 w-8 animate-spin mb-4" />
        <p>Memuat detail nadhom...</p>
      </div>
    );
  }

  if (!verse) {
    return (
      <div className="text-center py-20">
        <p className="text-muted-foreground">Nadhom tidak ditemukan.</p>
        <Button variant="outline" asChild className="mt-4 rounded-xl">
          <Link href="/verses">Kembali ke Daftar Nadhom</Link>
        </Button>
      </div>
    );
  }

  return (
    <>
      <title>{`Nadhom #${verse.number} | Nadhom Smart`}</title>
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        className="space-y-5"
      >
        {/* Header */}
        <div className="flex items-center justify-between">
          <div>
            <Badge variant="secondary" className="mb-1 rounded-lg text-[10px]">
              {verse.chapter?.title || verse.chapter?.name || `Bab ${verse.chapterId}`}
            </Badge>
            <h2 className="font-heading text-lg font-bold">
              Nadhom #{verse.number}
            </h2>
          </div>
          <Button
            variant="ghost"
            size="icon"
            className="rounded-full hover:bg-secondary/20"
            onClick={() => setIsBookmarked(!isBookmarked)}
            aria-label={isBookmarked ? 'Remove bookmark' : 'Add bookmark'}
          >
            {isBookmarked ? (
              <BookmarkCheck className="h-5 w-5 text-secondary fill-secondary" />
            ) : (
              <Bookmark className="h-5 w-5 text-muted-foreground" />
            )}
          </Button>
        </div>

        <Tabs defaultValue="nadhom">
          <TabsList className="w-full">
            <TabsTrigger value="nadhom">Nadhom</TabsTrigger>
            <TabsTrigger value="latihan">Latihan</TabsTrigger>
            <TabsTrigger value="setoran">Setoran</TabsTrigger>
          </TabsList>

          {/* Nadhom tab: reading content */}
          <TabsContent value="nadhom" className="space-y-5 mt-4">
            {/* Arabic Text */}
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
            >
              <Card className="border-border/50 overflow-hidden">
                <div className="h-1 gradient-primary" />
                <CardContent className="py-8 px-6">
                  <p className="arabic-text text-2xl md:text-3xl leading-[2.5] text-card-foreground">
                    {verse.arabicText.split('\n').map((line, i) => (
                      <span key={i}>
                        {line}
                        {i < verse.arabicText.split('\n').length - 1 && <br />}
                      </span>
                    ))}
                  </p>
                </CardContent>
              </Card>
            </motion.div>

            {/* Latin Transliteration */}
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <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">
                    Transliterasi
                  </p>
                  <p className="text-sm italic text-card-foreground leading-relaxed">
                    {verse.latinText.split('\n').map((line, i) => (
                      <span key={i}>
                        {line}
                        {i < verse.latinText.split('\n').length - 1 && <br />}
                      </span>
                    ))}
                  </p>
                </CardContent>
              </Card>
            </motion.div>

            {/* Latin Pesantren (if available) */}
            {verse.latinPesantren && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.25 }}
              >
                <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">
                      Pegon / Latin Pesantren
                    </p>
                    <p className="text-sm text-card-foreground leading-relaxed">
                      {verse.latinPesantren.split('\n').map((line, i) => (
                        <span key={i}>
                          {line}
                          {i < verse.latinPesantren!.split('\n').length - 1 && <br />}
                        </span>
                      ))}
                    </p>
                  </CardContent>
                </Card>
              </motion.div>
            )}

            {/* Translation */}
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <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">
                    Terjemah
                  </p>
                  <p className="text-sm text-card-foreground leading-relaxed">
                    {verse.translation.split('\n').map((line, i) => (
                      <span key={i}>
                        {line}
                        {i < verse.translation.split('\n').length - 1 && <br />}
                      </span>
                    ))}
                  </p>
                </CardContent>
              </Card>
            </motion.div>

            {/* Audio Player */}
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
            >
              <AudioPlayer
                src={verse.masterAudio?.url || '/audio/placeholder.mp3'}
                title="Audio Master"
                showDownload
              />
            </motion.div>

            {/* Prev/Next Navigation */}
            <motion.div
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.5 }}
              className="flex items-center gap-3"
            >
              <Button
                variant="outline"
                className="flex-1 rounded-xl gap-2"
                asChild={!!verse.previousId}
                disabled={!verse.previousId}
              >
                {verse.previousId ? (
                  <Link href={`/verses/${verse.previousId}`}>
                    <ChevronLeft className="h-4 w-4" />
                    Sebelumnya
                  </Link>
                ) : (
                  <>
                    <ChevronLeft className="h-4 w-4" />
                    Sebelumnya
                  </>
                )}
              </Button>
              <Button
                variant="outline"
                className="flex-1 rounded-xl gap-2"
                asChild={!!verse.nextId}
                disabled={!verse.nextId}
              >
                {verse.nextId ? (
                  <Link href={`/verses/${verse.nextId}`}>
                    Selanjutnya
                    <ChevronRight className="h-4 w-4" />
                  </Link>
                ) : (
                  <>
                    Selanjutnya
                    <ChevronRight className="h-4 w-4" />
                  </>
                )}
              </Button>
            </motion.div>
          </TabsContent>

          {/* Latihan tab: recording + immediate AI result */}
          <TabsContent value="latihan" className="mt-4 pb-24">
            <PracticeHistory verseId={verseId} />
            <PracticeRecorderSheet
              verseId={verseId}
              verseLabel={`Latihan Nadhom Bait ke-${verse.number}`}
              triggerLabel="Latihan Baru"
              title="Latihan Membaca"
              description="Rekam bacaan Anda, AI akan langsung menilai setelah selesai."
              submitLabel="Kirim Latihan"
              onSubmit={handlePracticeSubmit}
            />
          </TabsContent>

          {/* Setoran tab: submission history */}
          <TabsContent value="setoran" className="mt-4 pb-24">
            <SubmissionList verseId={verseId} />
            <PracticeRecorderSheet
              verseId={verseId}
              verseLabel={`Setoran Nadhom Bait ke-${verse.number}`}
              triggerLabel="Setor Hafalan"
              title="Setor Hafalan"
              description="Rekam bacaan Anda untuk direview oleh guru."
              submitLabel="Kirim Setoran"
              onSubmit={handleSetoranSubmit}
            />
          </TabsContent>
        </Tabs>
      </motion.div>
    </>
  );
}
