'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Timer, RotateCcw, BarChart3 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { RecorderButton } from '@/components/audio/recorder-button';
import { Waveform } from '@/components/audio/waveform';
import { AudioPlayer } from '@/components/audio/audio-player';
import { useAudioRecorder } from '@/hooks/use-audio-recorder';
import { useRecorderStore } from '@/stores/recorder-store';

const mockVerses = [
  { id: '1', number: 42, arabicText: 'كَلاَمُنَا لَفْظٌ مُفِيْدٌ كَاسْتَقِمْ ● وَاسْمٌ وَفِعْلٌ ثُمَّ حَرْفٌ الْكَلِمْ' },
  { id: '2', number: 87, arabicText: 'بِالْجَرِّ وَالتَّنْوِيْنِ وَالنِّدَا وَأَلْ ● وَمُسْنَدًا لِلاِسْمِ تَمْيِيْزٌ حَصَلْ' },
  { id: '3', number: 15, arabicText: 'وَأَسْتَعِيْنُ اللهَ فِيْ أَلْفِيَّهْ ● مَقَاصِدُ النَّحْوِ بِهَا مَحْوِيَّهْ' },
];

export default function MurojaahPage() {
  const [currentVerse, setCurrentVerse] = useState(mockVerses[0]);
  const [countdown, setCountdown] = useState(30);
  const [isCountdownActive, setIsCountdownActive] = useState(false);
  const [score, setScore] = useState<number | null>(null);
  const [totalSessions, setTotalSessions] = useState(0);

  const {
    state: recorderState,
    startRecording,
    stopRecording,
    resetRecording,
  } = useAudioRecorder({ maxDuration: 30 });
  const { audioUrl, waveformData, duration } = useRecorderStore();

  const nextVerse = useCallback(() => {
    const randomIndex = Math.floor(Math.random() * mockVerses.length);
    setCurrentVerse(mockVerses[randomIndex]);
    setCountdown(30);
    setScore(null);
    resetRecording();
  }, [resetRecording]);

  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (isCountdownActive && countdown > 0) {
      timer = setInterval(() => setCountdown((c) => c - 1), 1000);
    }
    if (countdown === 0) {
      setIsCountdownActive(false);
      if (recorderState === 'recording') stopRecording();
    }
    return () => clearInterval(timer);
  }, [isCountdownActive, countdown, recorderState, stopRecording]);

  const handleStart = () => {
    setIsCountdownActive(true);
    startRecording();
  };

  const handleSubmit = () => {
    // Simulate scoring
    const mockScore = Math.floor(Math.random() * 30) + 70;
    setScore(mockScore);
    setTotalSessions((s) => s + 1);
    setIsCountdownActive(false);
  };

  return (
    <>
      <title>Murojaah | Nadhom Smart</title>
      <div className="flex flex-col items-center py-4 space-y-6">
        {/* Stats bar */}
        <div className="w-full flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
            <BarChart3 className="h-4 w-4" />
            <span>Sesi: {totalSessions}</span>
          </div>
          <div className="flex items-center gap-2">
            <Timer className="h-4 w-4 text-primary" />
            <span className={`font-mono text-lg font-bold ${countdown <= 10 ? 'text-destructive' : 'text-primary'}`}>
              {countdown}s
            </span>
          </div>
        </div>

        {/* Verse Card */}
        <Card className="w-full border-border/50">
          <div className="h-1 gradient-gold" />
          <CardContent className="py-8 px-6">
            <p className="arabic-text text-xl md:text-2xl text-card-foreground leading-[2.5]">
              {currentVerse.arabicText}
            </p>
            <p className="text-center text-xs text-muted-foreground mt-3">
              Nadhom #{currentVerse.number}
            </p>
          </CardContent>
        </Card>

        {/* Waveform */}
        {(recorderState === 'recording' || recorderState === 'stopped') && (
          <Card className="w-full border-border/50">
            <CardContent className="py-3">
              <Waveform data={waveformData} isRecording={recorderState === 'recording'} />
            </CardContent>
          </Card>
        )}

        {/* Score */}
        <AnimatePresence>
          {score !== null && (
            <motion.div
              initial={{ scale: 0.5, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.5, opacity: 0 }}
              className="text-center"
            >
              <span className="font-heading text-4xl font-bold text-primary">{score}</span>
              <span className="text-lg text-muted-foreground">/100</span>
            </motion.div>
          )}
        </AnimatePresence>

        {/* Controls */}
        {score === null ? (
          <>
            <RecorderButton
              state={recorderState}
              onStart={handleStart}
              onStop={stopRecording}
            />
            {recorderState === 'stopped' && audioUrl && (
              <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="w-full space-y-3">
                <AudioPlayer src={audioUrl} compact />
                <Button onClick={handleSubmit} className="w-full rounded-xl gradient-primary border-0 text-white">
                  Kirim & Lihat Skor
                </Button>
              </motion.div>
            )}
          </>
        ) : (
          <Button onClick={nextVerse} className="rounded-xl gap-2 gradient-primary border-0 text-white">
            <RotateCcw className="h-4 w-4" />
            Nadhom Selanjutnya
          </Button>
        )}
      </div>
    </>
  );
}
