'use client';

import { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Trash2, Upload, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
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';

interface VerseRecorderProps {
  verseId: string;
  verseLabel?: string;
  submitLabel?: string;
  onSubmit: (params: { audio: File; durationSeconds: number }) => Promise<void>;
}

export function VerseRecorder({ verseId, verseLabel, submitLabel = 'Selesai & Lihat Hasil', onSubmit }: VerseRecorderProps) {
  const {
    state: recorderState,
    error,
    startRecording,
    stopRecording,
    resetRecording,
  } = useAudioRecorder({ maxDuration: 120 });

  const { audioUrl, duration, waveformData } = useRecorderStore();
  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);

  const formatDuration = (seconds: number) => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const handleUpload = async () => {
    if (!verseId || !audioUrl) {
      toast.error('Tidak ada rekaman atau ID nadhom');
      return;
    }

    try {
      setIsUploading(true);

      // Convert blob URL back to Blob/File for submission
      const response = await fetch(audioUrl);
      const audioBlob = await response.blob();
      const audioFile = new File([audioBlob], 'recording.webm', { type: audioBlob.type });

      // Add a listener for the upload progress event
      const progressListener = ((e: CustomEvent<{ progress: number }>) => {
        setUploadProgress(e.detail.progress);
      }) as EventListener;
      window.addEventListener('upload-progress', progressListener);

      await onSubmit({ audio: audioFile, durationSeconds: duration });

      window.removeEventListener('upload-progress', progressListener);
    } catch (err: unknown) {
      console.error(err);
      const message =
        err && typeof err === 'object' && 'response' in err
          ? (err as { response?: { data?: { message?: string } } }).response?.data?.message
          : undefined;
      toast.error(message || 'Gagal mengirim latihan');
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="flex flex-col items-center py-4 space-y-6">
      {verseLabel && (
        <Card className="w-full border-border/50">
          <CardContent className="py-4 px-5 text-center">
            <p className="text-sm font-medium text-foreground">{verseLabel}</p>
          </CardContent>
        </Card>
      )}

      {/* Waveform */}
      <AnimatePresence>
        {(recorderState === 'recording' || recorderState === 'stopped') && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            exit={{ opacity: 0, height: 0 }}
            className="w-full"
          >
            <Card className="border-border/50">
              <CardContent className="py-4">
                <Waveform
                  data={waveformData}
                  isRecording={recorderState === 'recording'}
                />
              </CardContent>
            </Card>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Duration */}
      {recorderState === 'recording' && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          className="flex items-center gap-2"
        >
          <div className="h-2.5 w-2.5 rounded-full bg-destructive animate-recording-pulse" />
          <span className="font-mono text-lg font-semibold text-destructive">
            {formatDuration(duration)}
          </span>
        </motion.div>
      )}

      {/* Record Button */}
      <RecorderButton
        state={recorderState}
        onStart={startRecording}
        onStop={stopRecording}
        disabled={isUploading}
      />

      {/* Error */}
      {error && (
        <p className="text-sm text-destructive text-center max-w-xs">{error}</p>
      )}

      {/* Playback & Actions */}
      <AnimatePresence>
        {recorderState === 'stopped' && audioUrl && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: 20 }}
            className="w-full space-y-4"
          >
            <AudioPlayer src={audioUrl} title="Rekaman Anda" />

            {/* Upload progress */}
            {isUploading && (
              <div className="space-y-2">
                <div className="flex justify-between text-xs text-muted-foreground">
                  <span>Mengirim...</span>
                  <span>{uploadProgress}%</span>
                </div>
                <Progress value={uploadProgress} className="h-2" />
              </div>
            )}

            <div className="flex gap-3">
              <Button
                variant="outline"
                className="flex-1 rounded-xl gap-2"
                onClick={resetRecording}
                disabled={isUploading}
              >
                <Trash2 className="h-4 w-4" />
                Hapus
              </Button>
              <Button
                className="flex-1 rounded-xl gap-2 gradient-primary border-0 text-white"
                onClick={handleUpload}
                disabled={isUploading}
              >
                {isUploading ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Upload className="h-4 w-4" />
                )}
                {submitLabel}
              </Button>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
