'use client';

import * as React from 'react';
import { FileUpload } from './FileUpload';
import { AudioInfo } from './AudioInfo';
import { Waveform } from './Waveform';
import { PlaybackControls } from './PlaybackControls';
import { useAudioPlayer } from '@/lib/hooks/useAudioPlayer';
import { useToast } from '@/components/ui/Toast';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/Card';
import { Loader2 } from 'lucide-react';

export function AudioEditor() {
  const {
    loadFile,
    clearFile,
    play,
    pause,
    stop,
    seek,
    setVolume,
    isPlaying,
    isPaused,
    currentTime,
    duration,
    volume,
    audioBuffer,
    fileName,
    isLoading,
    error,
    currentTimeFormatted,
    durationFormatted,
  } = useAudioPlayer();

  const { addToast } = useToast();

  const handleFileSelect = async (file: File) => {
    try {
      await loadFile(file);
      addToast({
        title: 'File loaded',
        description: `Successfully loaded ${file.name}`,
        variant: 'success',
        duration: 3000,
      });
    } catch (err) {
      addToast({
        title: 'Error loading file',
        description: err instanceof Error ? err.message : 'Unknown error',
        variant: 'error',
        duration: 5000,
      });
    }
  };

  const handleClear = () => {
    clearFile();
    addToast({
      title: 'Audio cleared',
      description: 'Audio file has been removed',
      variant: 'info',
      duration: 2000,
    });
  };

  // Show error toast
  React.useEffect(() => {
    if (error) {
      addToast({
        title: 'Error',
        description: error,
        variant: 'error',
        duration: 5000,
      });
    }
  }, [error, addToast]);

  return (
    <div className="space-y-6">
      {/* File Upload or Audio Info */}
      {!audioBuffer ? (
        <FileUpload onFileSelect={handleFileSelect} />
      ) : (
        <AudioInfo
          fileName={fileName || 'Unknown'}
          audioBuffer={audioBuffer}
          onClear={handleClear}
        />
      )}

      {/* Loading State */}
      {isLoading && (
        <Card>
          <CardContent className="p-8">
            <div className="flex flex-col items-center justify-center gap-3">
              <Loader2 className="h-8 w-8 animate-spin text-primary" />
              <p className="text-sm text-muted-foreground">Loading audio file...</p>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Waveform and Controls */}
      {audioBuffer && !isLoading && (
        <>
          {/* Waveform */}
          <Card>
            <CardHeader>
              <CardTitle>Waveform</CardTitle>
            </CardHeader>
            <CardContent>
              <Waveform
                audioBuffer={audioBuffer}
                currentTime={currentTime}
                duration={duration}
                onSeek={seek}
                height={150}
              />
            </CardContent>
          </Card>

          {/* Playback Controls */}
          <Card>
            <CardHeader>
              <CardTitle>Playback</CardTitle>
            </CardHeader>
            <CardContent>
              <PlaybackControls
                isPlaying={isPlaying}
                isPaused={isPaused}
                currentTime={currentTime}
                duration={duration}
                volume={volume}
                onPlay={play}
                onPause={pause}
                onStop={stop}
                onSeek={seek}
                onVolumeChange={setVolume}
                currentTimeFormatted={currentTimeFormatted}
                durationFormatted={durationFormatted}
              />
            </CardContent>
          </Card>
        </>
      )}
    </div>
  );
}
