import { Head, Link, router, usePage } from '@inertiajs/react';
import { CheckCheck } from 'lucide-react';
import NotificationController from '@/actions/App/Http/Controllers/Admin/NotificationController';
import NotificationSettingsController from '@/actions/App/Http/Controllers/Settings/NotificationSettingsController';
import Heading from '@/components/heading';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Label } from '@/components/ui/label';
import { cn, formatDate } from '@/lib/utils';
import type { Paginated } from '@/types';

type NotificationItem = {
    id: string;
    data: {
        message: string;
        url: string;
        [key: string]: unknown;
    };
    read_at: string | null;
    created_at: string | null;
};

type PageProps = {
    notifications: Paginated<NotificationItem>;
    notifyByEmail: boolean;
};

export default function NotificationSettings() {
    const { notifications, notifyByEmail } = usePage<PageProps>().props;
    const unreadCount = notifications.data.filter(
        (n) => n.read_at === null,
    ).length;

    function toggleEmailPreference(checked: boolean) {
        router.put(
            NotificationSettingsController.updatePreferences.url(),
            { notify_by_email: checked },
            { preserveScroll: true },
        );
    }

    function openNotification(notification: NotificationItem) {
        router.post(
            NotificationController.markAsRead.url(notification.id),
            {},
            {
                preserveScroll: true,
                onFinish: () => {
                    router.visit(notification.data.url);
                },
            },
        );
    }

    function markAllAsRead() {
        router.post(
            NotificationController.markAllAsRead.url(),
            {},
            { preserveScroll: true },
        );
    }

    return (
        <>
            <Head title="Notifications" />

            <div className="space-y-6">
                <Heading
                    variant="small"
                    title="Notifications"
                    description="Consultez votre historique et gérez vos préférences de réception"
                />

                <div className="flex items-start gap-3 rounded-lg border p-4">
                    <Checkbox
                        id="notify_by_email"
                        checked={notifyByEmail}
                        onCheckedChange={(checked) =>
                            toggleEmailPreference(checked === true)
                        }
                    />
                    <div className="grid gap-1">
                        <Label htmlFor="notify_by_email" className="font-medium">
                            Recevoir aussi les notifications par e-mail
                        </Label>
                        <p className="text-sm text-muted-foreground">
                            Les notifications restent toujours visibles dans
                            l’application, quel que soit ce réglage.
                        </p>
                    </div>
                </div>

                <div className="space-y-3">
                    <div className="flex items-center justify-between">
                        <p className="text-sm text-muted-foreground">
                            {notifications.total} notification
                            {notifications.total > 1 ? 's' : ''}
                            {unreadCount > 0 &&
                                ` · ${unreadCount} non lue${unreadCount > 1 ? 's' : ''}`}
                        </p>
                        {unreadCount > 0 && (
                            <Button
                                variant="outline"
                                size="sm"
                                onClick={markAllAsRead}
                            >
                                <CheckCheck />
                                Tout marquer comme lu
                            </Button>
                        )}
                    </div>

                    {notifications.data.length === 0 ? (
                        <p className="rounded-lg border border-dashed p-6 text-center text-sm text-muted-foreground">
                            Aucune notification pour le moment.
                        </p>
                    ) : (
                        <div className="divide-y rounded-lg border">
                            {notifications.data.map((notification) => (
                                <button
                                    key={notification.id}
                                    type="button"
                                    onClick={() =>
                                        openNotification(notification)
                                    }
                                    className={cn(
                                        'flex w-full flex-col items-start gap-1 px-4 py-3 text-left transition-colors hover:bg-muted/50',
                                        notification.read_at === null &&
                                            'bg-muted/30',
                                    )}
                                >
                                    <span
                                        className={cn(
                                            'text-sm',
                                            notification.read_at === null
                                                ? 'font-medium'
                                                : 'text-muted-foreground',
                                        )}
                                    >
                                        {notification.data.message}
                                    </span>
                                    {notification.created_at && (
                                        <span className="text-xs text-muted-foreground">
                                            {formatDate(
                                                notification.created_at,
                                            )}
                                        </span>
                                    )}
                                </button>
                            ))}
                        </div>
                    )}

                    {notifications.last_page > 1 && (
                        <div className="flex flex-wrap items-center gap-1">
                            {notifications.links.map((link, index) => (
                                <Button
                                    key={index}
                                    variant={
                                        link.active ? 'default' : 'outline'
                                    }
                                    size="sm"
                                    disabled={link.url === null}
                                    asChild={link.url !== null}
                                >
                                    {link.url !== null ? (
                                        <Link
                                            href={link.url}
                                            preserveScroll
                                            dangerouslySetInnerHTML={{
                                                __html: link.label,
                                            }}
                                        />
                                    ) : (
                                        <span
                                            dangerouslySetInnerHTML={{
                                                __html: link.label,
                                            }}
                                        />
                                    )}
                                </Button>
                            ))}
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}
