import { useTranslation } from 'react-i18next';
import { useQuery } from '@tanstack/react-query';
import { Task } from '@shared/schema';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Bell, BellOff, Calendar, AlertCircle, CheckCircle2, Clock } from 'lucide-react';
import { useNotifications } from '@/hooks/use-notifications';
import { formatDistanceToNow, isPast, isToday, addDays, isBefore } from 'date-fns';
import { de, enUS } from 'date-fns/locale';
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";

export default function NotificationsPage() {
    const { t, i18n } = useTranslation();
    const { enabled, toggleEnabled, permission, requestPermission } = useNotifications({ poll: false }); // Don't double poll here

    const { data: tasks = [] } = useQuery<Task[]>({
        queryKey: ['/api/tasks'],
    });

    const now = new Date();

    // Derive notifications from tasks
    const notifications = tasks.flatMap(task => {
        if (!task.dueDate || task.status === 'done') return [];

        const dueDate = new Date(task.dueDate);
        const isOverdue = isBefore(dueDate, now);
        // Upcoming: due within next 24 hours
        const isUpcoming = !isOverdue && isBefore(dueDate, addDays(now, 1));

        if (!isOverdue && !isUpcoming) return [];

        return [{
            id: task.id,
            type: isOverdue ? 'overdue' : 'upcoming',
            task,
            timestamp: dueDate
        }];
    }).sort((a, b) => {
        // Sort: Overdue first, then by time
        if (a.type !== b.type) return a.type === 'overdue' ? -1 : 1;
        return a.timestamp.getTime() - b.timestamp.getTime();
    });

    return (
        <div className="space-y-6 max-w-4xl mx-auto">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-3xl font-bold tracking-tight">{t('notifications.title', 'Notifications')}</h1>
                    <p className="text-muted-foreground mt-2">
                        {t('notifications.description', 'Manage your alerts and view important updates.')}
                    </p>
                </div>
            </div>

            {/* Settings Card */}
            <Card>
                <CardHeader>
                    <div className="flex items-center gap-2">
                        <Bell className="h-5 w-5 text-primary" />
                        <CardTitle>{t('notifications.settings.title', 'Browser Notifications')}</CardTitle>
                    </div>
                </CardHeader>
                <CardContent>
                    <div className="flex items-center justify-between">
                        <div className="space-y-0.5">
                            <Label htmlFor="notifications-toggle" className="text-base">
                                {t('notifications.enableBrowser', 'Enable Push Notifications')}
                            </Label>
                            <p className="text-sm text-muted-foreground">
                                {permission === 'denied'
                                    ? <span className="text-red-500">{t('notifications.settings.denied', 'Permission denied. Please enable in browser settings.')}</span>
                                    : t('notifications.settings.description', 'Receive alerts for upcoming and overdue tasks.')}
                            </p>
                        </div>
                        <Switch
                            id="notifications-toggle"
                            checked={enabled}
                            onCheckedChange={toggleEnabled}
                            disabled={permission === 'denied'}
                        />
                    </div>
                    {permission === 'default' && (
                        <div className="mt-4">
                            <Button variant="outline" size="sm" onClick={requestPermission}>
                                {t('notifications.settings.request', 'Request Permission')}
                            </Button>
                        </div>
                    )}
                </CardContent>
            </Card>

            {/* Notification List */}
            <div className="space-y-4">
                <h2 className="text-xl font-semibold flex items-center gap-2">
                    <Clock className="h-5 w-5" />
                    {t('notifications.recent', 'Recent Alerts')}
                </h2>

                {notifications.length === 0 ? (
                    <div className="text-center py-12 border rounded-lg bg-muted/10 border-dashed">
                        <CheckCircle2 className="h-10 w-10 text-muted-foreground mx-auto mb-3 opacity-50" />
                        <p className="text-muted-foreground font-medium">{t('notifications.empty', 'All caught up! No urgent alerts.')}</p>
                    </div>
                ) : (
                    notifications.map((notif) => (
                        <Card key={notif.id} className={`border-l-4 ${notif.type === 'overdue' ? 'border-l-red-500 bg-red-50/10 dark:bg-red-900/10' : 'border-l-blue-500'}`}>
                            <CardContent className="p-4 flex items-start gap-4">
                                <div className={`p-2 rounded-full shrink-0 ${notif.type === 'overdue' ? 'bg-red-100 text-red-600 dark:bg-red-900/30 dark:text-red-400' : 'bg-blue-100 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400'}`}>
                                    {notif.type === 'overdue' ? <AlertCircle className="h-5 w-5" /> : <Calendar className="h-5 w-5" />}
                                </div>
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center justify-between gap-2">
                                        <h3 className="font-semibold truncate">{notif.task.title}</h3>
                                        <span className="text-xs text-muted-foreground whitespace-nowrap">
                                            {formatDistanceToNow(notif.timestamp, { addSuffix: true, locale: i18n.language === 'de' ? de : enUS })}
                                        </span>
                                    </div>
                                    <p className="text-sm text-muted-foreground mt-1">
                                        {notif.type === 'overdue'
                                            ? t('notifications.overdueBody', 'This task is overdue!')
                                            : t('notifications.upcomingBody', { time: formatDistanceToNow(notif.timestamp, { locale: i18n.language === 'de' ? de : enUS }) })
                                        }
                                    </p>
                                </div>
                            </CardContent>
                        </Card>
                    ))
                )}
            </div>
        </div>
    );
}
