import { Bell, BellOff } from 'lucide-react';
import { useState } from 'react';
import type { ReactNode } from 'react';

import { Button } from '@/components/ui/button';
import { useNotificationPermission } from '@/hooks/use-notification-permission';
import { cn } from '@/lib/utils';

/**
 * Gate izin notifikasi browser (blocking).
 *
 * Membungkus konten aplikasi. Selama izin belum diberikan, konten ditutup
 * overlay penuh dan user diwajibkan mengizinkan notifikasi sebelum bisa lanjut.
 * Notifikasi dipakai agar aplikasi berjalan lancar (update task realtime),
 * sehingga izinnya bersifat wajib — tidak ada opsi "lewati".
 *
 * Perilaku per status:
 *
 * - `granted`     : gate transparan, konten tampil normal.
 * - `default`     : overlay + tombol "Aktifkan notifikasi" untuk memicu prompt OS.
 * - `denied`      : overlay + panduan unblock manual + tombol "Cek ulang izin".
 * - `unsupported` : gate transparan (tidak ada yang bisa dipaksa di browser ini).
 */
export function NotificationPermissionGate({
    children,
}: {
    children: ReactNode;
}) {
    const { permission, requestPermission } = useNotificationPermission();

    // Diizinkan atau browser tak mendukung → jangan halangi akses.
    if (permission === 'granted' || permission === 'unsupported') {
        return <>{children}</>;
    }

    return (
        <>
            {children}
            <NotificationPermissionOverlay
                permission={permission}
                requestPermission={requestPermission}
            />
        </>
    );
}

function NotificationPermissionOverlay({
    permission,
    requestPermission,
}: {
    permission: NotificationPermission;
    requestPermission: () => Promise<unknown>;
}) {
    const [isRequesting, setIsRequesting] = useState(false);
    const isDenied = permission === 'denied';

    const handleEnable = async () => {
        setIsRequesting(true);

        try {
            // Saat `denied`, requestPermission tidak akan memunculkan prompt lagi;
            // hook tetap mem-broadcast status terbaru sehingga UI ikut ter-refresh
            // jika user sudah unblock manual di pengaturan browser.
            await requestPermission();
        } finally {
            setIsRequesting(false);
        }
    };

    return (
        <div
            role="dialog"
            aria-modal="true"
            aria-labelledby="notif-gate-title"
            className={cn(
                'fixed inset-0 z-50 flex items-center justify-center',
                'bg-background/80 p-4 backdrop-blur-sm',
            )}
        >
            <div className="w-full max-w-md rounded-xl border bg-card p-6 text-card-foreground shadow-lg">
                <div
                    className={cn(
                        'mx-auto flex size-12 items-center justify-center rounded-full',
                        isDenied
                            ? 'bg-destructive/10 text-destructive'
                            : 'bg-primary/10 text-primary',
                    )}
                >
                    {isDenied ? (
                        <BellOff className="size-6" />
                    ) : (
                        <Bell className="size-6" />
                    )}
                </div>

                <h2
                    id="notif-gate-title"
                    className="mt-4 text-center text-lg font-semibold"
                >
                    {isDenied
                        ? 'Notifications blocked'
                        : 'Enable notifications first'}
                </h2>

                <div className="mt-2 text-center text-sm text-muted-foreground">
                    {isDenied ? (
                        <p>
                            Notifications are blocked for this site, but they
                            are required for the app to work properly. Open the
                            site settings in your browser (the lock icon next to
                            the address bar), change the{' '}
                            <span className="font-medium text-foreground">
                                Notifications
                            </span>{' '}
                            permission to{' '}
                            <span className="font-medium text-foreground">
                                Allow
                            </span>
                            , then press the button below to continue.
                        </p>
                    ) : (
                        <p>
                            This app uses notifications to deliver task updates
                            in real time. Allow notifications to start using the
                            app.
                        </p>
                    )}
                </div>

                <div className="mt-6">
                    <Button
                        className="w-full"
                        onClick={handleEnable}
                        disabled={isRequesting}
                    >
                        {isDenied
                            ? 'Re-check permission'
                            : 'Enable notifications'}
                    </Button>
                </div>
            </div>
        </div>
    );
}
