'use client';

import React, { useRef, useState, useCallback, useMemo, useEffect } from 'react';
import { Mic2, Play, Pause, Upload } from 'lucide-react';
import { AppNodeData } from '../../types/node';
import { AudioVisualizer } from '../components/AudioVisualizer';
import { NodeLoadingOverlay, NodeLoadingAccent } from '../components/NodeLoadingOverlay';

interface AudioGeneratorRendererProps {
    data: AppNodeData;
    isWorking: boolean;
    update?: (data: Partial<AppNodeData>) => void;
    loadingAccent?: NodeLoadingAccent;
}

export const AudioGeneratorRenderer = ({ data, isWorking, update, loadingAccent = 'pink' }: AudioGeneratorRendererProps) => {
    const mediaRef = useRef<HTMLAudioElement>(null);
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [isPlayingAudio, setIsPlayingAudio] = useState(false);
    const [isDragOver, setIsDragOver] = useState(false);
    const [audioDuration, setAudioDuration] = useState<number | null>(null);

    useEffect(() => {
        setAudioDuration(null);
    }, [data.audioUri]);

    const formattedDuration = useMemo(() => {
        if (audioDuration === null || !Number.isFinite(audioDuration) || audioDuration <= 0) return null;
        const totalSeconds = Math.floor(audioDuration);
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = totalSeconds % 60;

        if (hours > 0) {
            return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }
        return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    }, [audioDuration]);

    const toggleAudio = (e: React.MouseEvent) => {
        e.stopPropagation();
        const audio = mediaRef.current;
        if (audio) {
            if (audio.paused) { 
                audio.play(); 
                setIsPlayingAudio(true); 
            } else { 
                audio.pause(); 
                setIsPlayingAudio(false); 
            }
        }
    };

    const handleFileSelect = useCallback((file: File) => {
        if (!update || !file.type.startsWith('audio/')) return;
        const reader = new FileReader();
        reader.onload = (e) => {
            const result = e.target?.result as string;
            update({ audioUri: result, status: 'SUCCESS' });
        };
        reader.readAsDataURL(file);
    }, [update]);

    const handleUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) handleFileSelect(file);
        e.target.value = '';
    }, [handleFileSelect]);

    const handleDragOver = useCallback((e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(true);
    }, []);

    const handleDragLeave = useCallback((e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
    }, []);

    const handleDrop = useCallback((e: React.DragEvent) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
        const file = e.dataTransfer.files?.[0];
        if (file && file.type.startsWith('audio/')) {
            handleFileSelect(file);
        }
    }, [handleFileSelect]);

    return (
        <div 
            className="w-full h-full p-6 flex flex-col justify-center items-center relative overflow-hidden group/audio"
            onDragOver={handleDragOver}
            onDragLeave={handleDragLeave}
            onDrop={handleDrop}
        >
            <div className="absolute inset-0 bg-gradient-to-br from-pink-500/10 to-purple-900/10 z-0"></div>
            
            {/* Drag overlay */}
            {isDragOver && (
                <div className="absolute inset-0 bg-pink-500/20 border-2 border-dashed border-pink-400 rounded-lg z-30 flex items-center justify-center backdrop-blur-sm">
                    <div className="flex flex-col items-center gap-2 text-pink-300">
                        <Upload size={32} />
                        <span className="text-xs font-bold">放下音频文件</span>
                    </div>
                </div>
            )}

            {data.audioUri ? (
                <div className="flex flex-col items-center gap-4 w-full z-10">
                    <audio 
                        ref={mediaRef} 
                        src={data.audioUri} 
                        onEnded={() => setIsPlayingAudio(false)} 
                        onPlay={() => setIsPlayingAudio(true)} 
                        onPause={() => setIsPlayingAudio(false)} 
                        onLoadedMetadata={(e) => setAudioDuration(e.currentTarget.duration || null)}
                        onDurationChange={(e) => {
                            const nextDuration = e.currentTarget.duration;
                            if (Number.isFinite(nextDuration) && nextDuration > 0) {
                                setAudioDuration(nextDuration);
                            }
                        }}
                        className="hidden" 
                    />
                    <div className="w-full px-4"><AudioVisualizer isPlaying={isPlayingAudio} /></div>
                    <div className="flex items-center gap-4">
                        <button 
                            onClick={toggleAudio} 
                            className="w-12 h-12 rounded-full bg-cyan-500/20 hover:bg-cyan-500/40 border border-cyan-500/50 flex items-center justify-center transition-all hover:scale-105"
                        >
                            {isPlayingAudio ? <Pause size={20} className="text-white" /> : <Play size={20} className="text-white ml-1" />}
                        </button>
                        {update && (
                            <button
                                onClick={(e) => { e.stopPropagation(); fileInputRef.current?.click(); }}
                                className="w-10 h-10 rounded-full bg-white/5 hover:bg-white/10 border border-white/10 flex items-center justify-center transition-all hover:scale-105"
                                title="替换音频"
                            >
                                <Upload size={16} className="text-muted-foreground" />
                            </button>
                        )}
                    </div>
                    {formattedDuration && (
                        <div className="text-[10px] text-muted-foreground tracking-wide">
                            时长 {formattedDuration}
                        </div>
                    )}
                    {update && (
                        <input type="file" ref={fileInputRef} className="hidden" accept="audio/*" onChange={handleUpload} />
                    )}
                </div>
            ) : (
                <div className="flex flex-col items-center gap-3 text-foreground z-10 select-none">
                    <div 
                        className="w-20 h-20 rounded-[28px] bg-white/5 border border-white/5 flex items-center justify-center cursor-pointer hover:bg-white/10 hover:scale-105 transition-all duration-300 shadow-inner"
                        onClick={() => !isWorking && update && fileInputRef.current?.click()}
                    >
                        <Mic2 size={32} className="text-muted-foreground opacity-50" />
                    </div>
                    <span className="text-[10px] font-bold uppercase tracking-widest">
                        {isWorking ? '生成中...' : (update ? '拖拽或上传' : '准备生成')}
                    </span>
                    {update && (
                        <input type="file" ref={fileInputRef} className="hidden" accept="audio/*" onChange={handleUpload} />
                    )}
                </div>
            )}
            {isWorking && <NodeLoadingOverlay message="生成中..." accent={loadingAccent} />}
        </div>
    );
};
