import { useUploadStore } from '@/store/useUploadStore';
import {
    ArrowPathIcon,
    CheckCircleIcon,
    ChevronDownIcon,
    ChevronUpIcon,
    CloudArrowUpIcon,
    ExclamationCircleIcon,
    XMarkIcon,
} from '@heroicons/react/24/solid';

function formatSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
}

export function GlobalUploadWidget() {
    const {
        tasks,
        isMinimized,
        toggleMinimized,
        retryUpload,
        cancelUpload,
        dismissTask,
        clearCompleted,
    } = useUploadStore();

    if (tasks.length === 0) return null;

    const activeCount = tasks.filter((t) => t.status === 'uploading' || t.status === 'queued').length;
    const completedCount = tasks.filter((t) => t.status === 'completed').length;
    const errorCount = tasks.filter((t) => t.status === 'error').length;

    let headerTitle = 'Pengunggahan File';
    if (activeCount > 0) {
        headerTitle = `Mengunggah ${activeCount} file...`;
    } else if (errorCount > 0) {
        headerTitle = `${errorCount} file gagal diunggah`;
    } else if (completedCount > 0) {
        headerTitle = `${completedCount} file selesai diunggah`;
    }

    return (
        <div className="fixed bottom-4 left-3 right-3 sm:left-auto sm:right-4 z-50 w-auto sm:w-full sm:max-w-md rounded-2xl bg-white shadow-2xl border border-gray-200 overflow-hidden transition-all duration-200">
            {/* Widget Header */}
            <div
                onClick={toggleMinimized}
                className="flex items-center justify-between bg-sky-700 text-white px-3.5 sm:px-4 py-2.5 sm:py-3 cursor-pointer select-none"
            >
                <div className="flex items-center gap-2 sm:gap-2.5 min-w-0">
                    <CloudArrowUpIcon className="w-4 h-4 sm:w-5 sm:h-5 shrink-0 text-sky-200 animate-pulse" />
                    <div className="flex flex-col min-w-0">
                        <span className="text-xs sm:text-sm font-semibold truncate">{headerTitle}</span>
                        <span className="text-[10px] sm:text-[11px] text-sky-100">
                            {completedCount}/{tasks.length} selesai
                        </span>
                    </div>
                </div>
                <div className="flex items-center gap-1 sm:gap-1.5" onClick={(e) => e.stopPropagation()}>
                    {completedCount > 0 && !isMinimized && (
                        <button
                            type="button"
                            onClick={clearCompleted}
                            className="text-[10px] sm:text-[11px] font-medium bg-sky-600 hover:bg-sky-500 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-md text-sky-50 transition-colors shrink-0 whitespace-nowrap"
                        >
                            Bersihkan Selesai
                        </button>
                    )}
                    <button
                        type="button"
                        onClick={toggleMinimized}
                        className="p-1 text-sky-100 hover:text-white rounded-lg hover:bg-sky-600 transition-colors"
                        aria-label={isMinimized ? 'Buka detail upload' : 'Tutup detail upload'}
                    >
                        {isMinimized ? (
                            <ChevronUpIcon className="w-4 h-4 sm:w-5 sm:h-5" />
                        ) : (
                            <ChevronDownIcon className="w-4 h-4 sm:w-5 sm:h-5" />
                        )}
                    </button>
                </div>
            </div>

            {/* Widget Body (Stacked Task List) */}
            {!isMinimized && (
                <div className="max-h-60 sm:max-h-72 overflow-y-auto divide-y divide-gray-100 bg-gray-50/50 p-2 space-y-2">
                    {tasks.map((t) => (
                        <div
                            key={t.id}
                            className="bg-white rounded-xl border border-gray-200 p-3 shadow-2xs transition-all flex flex-col gap-2"
                        >
                            <div className="flex items-start justify-between gap-2 min-w-0">
                                <div className="min-w-0 flex-1">
                                    <p className="text-xs font-semibold text-gray-800 truncate" title={t.fileName}>
                                        {t.fileName}
                                    </p>
                                    <p className="text-[11px] text-gray-400">
                                        {formatSize(t.fileSize)}
                                    </p>
                                </div>

                                <div className="flex items-center gap-1 shrink-0">
                                    {t.status === 'completed' && (
                                        <CheckCircleIcon className="w-5 h-5 text-emerald-500" />
                                    )}
                                    {t.status === 'error' && (
                                        <button
                                            type="button"
                                            onClick={() => retryUpload(t.id)}
                                            className="inline-flex items-center gap-1 text-[11px] font-semibold text-sky-600 hover:text-sky-700 bg-sky-50 hover:bg-sky-100 px-2 py-1 rounded-md transition-colors"
                                            title="Coba unggah ulang"
                                        >
                                            <ArrowPathIcon className="w-3.5 h-3.5" />
                                            <span>Coba lagi</span>
                                        </button>
                                    )}
                                    <button
                                        type="button"
                                        onClick={() =>
                                            (t.status === 'uploading' || t.status === 'queued')
                                                ? cancelUpload(t.id)
                                                : dismissTask(t.id)
                                        }
                                        className="p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100"
                                        title={(t.status === 'uploading' || t.status === 'queued') ? 'Batal' : 'Hapus'}
                                    >
                                        <XMarkIcon className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>

                            {/* Status & Progress Bar */}
                            {t.status === 'queued' && (
                                <div className="flex items-center justify-between text-[11px] font-medium text-amber-600">
                                    <span>Mengantre...</span>
                                </div>
                            )}

                            {t.status === 'uploading' && (
                                <div className="space-y-1">
                                    <div className="flex items-center justify-between text-[11px] font-medium text-sky-700">
                                        <span>
                                            {t.progress >= 99 ? 'Memproses di server...' : 'Mengunggah...'}
                                        </span>
                                        <span>{t.progress}%</span>
                                    </div>
                                    <div className="h-1.5 w-full overflow-hidden rounded-full bg-sky-100">
                                        <div
                                            className="h-full rounded-full bg-sky-500 transition-[width] duration-150"
                                            style={{ width: `${t.progress}%` }}
                                        />
                                    </div>
                                </div>
                            )}

                            {t.status === 'error' && (
                                <div className="flex items-start gap-1.5 rounded-lg bg-rose-50 border border-rose-200 p-2 text-[11px] text-rose-700">
                                    <ExclamationCircleIcon className="w-4 h-4 text-rose-500 shrink-0 mt-0.5" />
                                    <span className="leading-tight">{t.errorMsg}</span>
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            )}
        </div>
    );
}
