'use client';

import { useState, useCallback } from 'react';
import { useAudioRecorder, formatDuration, formatDurationKorean } from '@/hooks/useAudioRecorder';

interface AudioRecorderButtonProps {
    /** 녹음 완료 후 콜백 — Blob, 시작시각, 길이(초) 전달 */
    onRecordingComplete: (blob: Blob, startTime: string, durationSeconds: number) => Promise<void>;
    /** 대상 문서가 데일리 노트인지 */
    isDailyNote: boolean;
}

/**
 * 상담 녹음 플로팅 버튼
 * 
 * 데일리 노트에서만 표시. 녹음 시작 → 진행 표시 → 종료 후 자동 업로드.
 */
export default function AudioRecorderButton({ onRecordingComplete, isDailyNote }: AudioRecorderButtonProps) {
    const {
        state,
        startRecording,
        pauseRecording,
        resumeRecording,
        stopRecording,
        elapsedSeconds,
        startTime,
        error,
    } = useAudioRecorder();

    const [isUploading, setIsUploading] = useState(false);

    // 데일리 노트가 아니면 렌더링하지 않음
    if (!isDailyNote) return null;

    const handleStart = async () => {
        await startRecording();
    };

    const handleStop = async () => {
        const blob = await stopRecording();
        if (!blob || !startTime) return;

        setIsUploading(true);
        try {
            await onRecordingComplete(blob, startTime, elapsedSeconds);
        } catch (err) {
            console.error('Recording upload failed:', err);
        } finally {
            setIsUploading(false);
        }
    };

    // 에러 상태
    if (error) {
        return (
            <div className="fixed bottom-6 right-6 z-50 bg-red-50 border border-red-200 rounded-2xl shadow-lg px-4 py-3 flex items-center gap-3 max-w-sm">
                <span className="text-red-500 text-lg">⚠️</span>
                <span className="text-red-700 text-sm">{error}</span>
                <button
                    onClick={() => window.location.reload()}
                    className="ml-auto text-red-500 hover:text-red-700 text-xs font-medium"
                >
                    닫기
                </button>
            </div>
        );
    }

    // 업로드 중
    if (isUploading) {
        return (
            <div className="fixed bottom-6 right-6 z-50 bg-indigo-50 border border-indigo-200 rounded-2xl shadow-lg px-5 py-3 flex items-center gap-3">
                <svg className="animate-spin h-5 w-5 text-indigo-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span className="text-indigo-700 text-sm font-medium">녹음 저장 중...</span>
            </div>
        );
    }

    // 녹음 중 / 일시정지
    if (state === 'recording' || state === 'paused') {
        return (
            <div className="fixed bottom-6 right-6 z-50 bg-white border border-gray-200 rounded-2xl shadow-xl px-4 py-3 flex items-center gap-3">
                {/* 녹음 상태 표시 */}
                <div className="flex items-center gap-2">
                    <span className={`inline-block w-3 h-3 rounded-full ${state === 'recording' ? 'bg-red-500 animate-pulse' : 'bg-yellow-500'}`}></span>
                    <span className="text-gray-800 font-mono text-sm font-medium min-w-[60px]">
                        {formatDuration(elapsedSeconds)}
                    </span>
                    <span className="text-gray-400 text-xs">
                        {state === 'recording' ? '녹음 중' : '일시정지'}
                    </span>
                </div>

                {/* 일시정지 / 이어서 */}
                {state === 'recording' ? (
                    <button
                        onClick={pauseRecording}
                        className="p-2 text-gray-500 hover:text-yellow-600 hover:bg-yellow-50 rounded-lg transition-colors"
                        title="일시정지"
                    >
                        <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                            <rect x="6" y="4" width="4" height="16" rx="1" />
                            <rect x="14" y="4" width="4" height="16" rx="1" />
                        </svg>
                    </button>
                ) : (
                    <button
                        onClick={resumeRecording}
                        className="p-2 text-gray-500 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors"
                        title="이어서 녹음"
                    >
                        <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M8 5v14l11-7z" />
                        </svg>
                    </button>
                )}

                {/* 중지 */}
                <button
                    onClick={handleStop}
                    className="p-2 text-gray-500 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                    title="녹음 종료"
                >
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                        <rect x="6" y="6" width="12" height="12" rx="2" />
                    </svg>
                </button>
            </div>
        );
    }

    // 기본 — 녹음 시작 버튼 (FAB)
    return (
        <button
            onClick={handleStart}
            className="fixed bottom-6 right-6 z-50 w-14 h-14 bg-gradient-to-br from-red-500 to-red-600 text-white rounded-full shadow-lg hover:shadow-xl hover:scale-105 transition-all flex items-center justify-center group"
            title="상담 녹음 시작"
        >
            <svg className="w-6 h-6 group-hover:scale-110 transition-transform" fill="currentColor" viewBox="0 0 24 24">
                <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z" />
                <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z" />
            </svg>
        </button>
    );
}
