import { useEffect, useRef, useState } from 'react';
import { Bell, Loader2, Mail, Moon, Package, Shield } from 'lucide-react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { getNotificationPreferences, updateNotificationPreferences } from '@/client';
import {getApiErrorMessage} from '@/lib/api-error';

export function SettingsPreferences() {
    const queryClient = useQueryClient();
    const isInitialized = useRef(false);

    const [emailEnabled, setEmailEnabled] = useState(true);
    const [inAppEnabled, setInAppEnabled] = useState(true);
    const [digestMode, setDigestMode] = useState('immediate');
    const [dndEnabled, setDndEnabled] = useState(false);
    const [dndStartHour, setDndStartHour] = useState('22');
    const [dndStartMinute, setDndStartMinute] = useState('00');
    const [dndEndHour, setDndEndHour] = useState('08');
    const [dndEndMinute, setDndEndMinute] = useState('00');
    const [marketingEnabled, setMarketingEnabled] = useState(false);
    const [securityEnabled, setSecurityEnabled] = useState(true);
    const [productEnabled, setProductEnabled] = useState(true);

    // Fetch notification preferences
    const { data: preferences, isLoading } = useQuery({
        queryKey: ['notificationPreferences'],
        queryFn: async () => {
            const resp = await getNotificationPreferences();
            return resp.data?.data ?? null;
        },
    });

    useEffect(() => {
        if (preferences && !isInitialized.current) {
            setEmailEnabled(preferences.email_enabled ?? true);
            setInAppEnabled(preferences.in_app_enabled ?? true);
            setDigestMode(preferences.digest_mode || 'immediate');
            setDndEnabled(preferences.dnd_enabled ?? false);
            setMarketingEnabled(preferences.marketing_enabled ?? false);
            setSecurityEnabled(preferences.security_enabled ?? true);
            setProductEnabled(preferences.product_enabled ?? true);

            if (preferences.dnd_start_minute !== null && preferences.dnd_start_minute !== undefined) {
                const startHour = Math.floor(preferences.dnd_start_minute / 60);
                const startMin = preferences.dnd_start_minute % 60;
                setDndStartHour(startHour.toString().padStart(2, '0'));
                setDndStartMinute(startMin.toString().padStart(2, '0'));
            }

            if (preferences.dnd_end_minute !== null && preferences.dnd_end_minute !== undefined) {
                const endHour = Math.floor(preferences.dnd_end_minute / 60);
                const endMin = preferences.dnd_end_minute % 60;
                setDndEndHour(endHour.toString().padStart(2, '0'));
                setDndEndMinute(endMin.toString().padStart(2, '0'));
            }

            isInitialized.current = true;
        }
    }, [preferences]);

    const updatePreferencesMutation = useMutation({
        mutationFn: async () => {
            const dndStart = dndEnabled ? Number.parseInt(dndStartHour) * 60 + Number.parseInt(dndStartMinute) : null;
            const dndEnd = dndEnabled ? Number.parseInt(dndEndHour) * 60 + Number.parseInt(dndEndMinute) : null;

            await updateNotificationPreferences({
                body: {
                    email_enabled: emailEnabled,
                    in_app_enabled: inAppEnabled,
                    digest_mode: digestMode,
                    dnd_enabled: dndEnabled,
                    dnd_start_minute: dndStart,
                    dnd_end_minute: dndEnd,
                    marketing_enabled: marketingEnabled,
                    security_enabled: securityEnabled,
                    product_enabled: productEnabled,
                },
            });
        },
        onSuccess: () => {
            toast.success('Notification preferences updated successfully');
            queryClient.invalidateQueries({ queryKey: ['notificationPreferences'] });
        },
        onError: (err: unknown) => {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            toast.error(getApiErrorMessage(err, 'Failed to update notification preferences'));
        },
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        updatePreferencesMutation.mutate();
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center p-8">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
        );
    }

    return (
        <div className="flex-1 lg:max-w-4xl space-y-6 p-4 md:p-8 pt-6">
            <div className="space-y-0.5">
                <h2 className="text-2xl font-bold tracking-tight">Preferences</h2>
                <p className="text-muted-foreground">Manage your personal preferences and notification settings.</p>
            </div>
            <Separator className="my-6" />

            <form onSubmit={handleSubmit} className="space-y-6">
                <Card>
                    <CardHeader>
                        <CardTitle>Notification Channels</CardTitle>
                        <CardDescription>Choose how you want to receive notifications.</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="flex items-center justify-between">
                            <div className="space-y-0.5">
                                <div className="flex items-center gap-2">
                                    <Mail className="h-4 w-4 text-muted-foreground" />
                                    <Label htmlFor="email-enabled" className="cursor-pointer">
                                        Email Notifications
                                    </Label>
                                </div>
                                <p className="text-sm text-muted-foreground">Receive notifications via email</p>
                            </div>
                            <Switch id="email-enabled" checked={emailEnabled} onCheckedChange={setEmailEnabled} />
                        </div>

                        <div className="flex items-center justify-between">
                            <div className="space-y-0.5">
                                <div className="flex items-center gap-2">
                                    <Bell className="h-4 w-4 text-muted-foreground" />
                                    <Label htmlFor="in-app-enabled" className="cursor-pointer">
                                        In-App Notifications
                                    </Label>
                                </div>
                                <p className="text-sm text-muted-foreground">Show notifications within the application</p>
                            </div>
                            <Switch id="in-app-enabled" checked={inAppEnabled} onCheckedChange={setInAppEnabled} />
                        </div>
                    </CardContent>
                </Card>

                {/* Do Not Disturb */}
                <Card>
                    <CardHeader>
                        <CardTitle>Do Not Disturb</CardTitle>
                        <CardDescription>Set quiet hours when you don't want to be disturbed.</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="flex items-center justify-between">
                            <div className="space-y-0.5">
                                <div className="flex items-center gap-2">
                                    <Moon className="h-4 w-4 text-muted-foreground" />
                                    <Label htmlFor="dnd-enabled" className="cursor-pointer">
                                        Enable Do Not Disturb
                                    </Label>
                                </div>
                                <p className="text-sm text-muted-foreground">Mute notifications during specific hours</p>
                            </div>
                            <Switch id="dnd-enabled" checked={dndEnabled} onCheckedChange={setDndEnabled} />
                        </div>

                        {dndEnabled && (
                            <>
                                <Separator />
                                <div className="grid grid-cols-2 gap-4">
                                    <div className="space-y-2">
                                        <Label>Start Time</Label>
                                        <div className="flex gap-2">
                                            <Input
                                                type="number"
                                                min="0"
                                                max="23"
                                                value={dndStartHour}
                                                onChange={(e) => setDndStartHour(e.target.value)}
                                                className="w-20"
                                                placeholder="HH"
                                            />
                                            <span className="flex items-center">:</span>
                                            <Input
                                                type="number"
                                                min="0"
                                                max="59"
                                                value={dndStartMinute}
                                                onChange={(e) => setDndStartMinute(e.target.value)}
                                                className="w-20"
                                                placeholder="MM"
                                            />
                                        </div>
                                    </div>
                                    <div className="space-y-2">
                                        <Label>End Time</Label>
                                        <div className="flex gap-2">
                                            <Input
                                                type="number"
                                                min="0"
                                                max="23"
                                                value={dndEndHour}
                                                onChange={(e) => setDndEndHour(e.target.value)}
                                                className="w-20"
                                                placeholder="HH"
                                            />
                                            <span className="flex items-center">:</span>
                                            <Input
                                                type="number"
                                                min="0"
                                                max="59"
                                                value={dndEndMinute}
                                                onChange={(e) => setDndEndMinute(e.target.value)}
                                                className="w-20"
                                                placeholder="MM"
                                            />
                                        </div>
                                    </div>
                                </div>
                            </>
                        )}
                    </CardContent>
                </Card>

                {/* Notification Categories */}
                <Card>
                    <CardHeader>
                        <CardTitle>Notification Categories</CardTitle>
                        <CardDescription>Choose which types of notifications you want to receive.</CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6">
                        <div className="flex items-center justify-between">
                            <div className="space-y-0.5">
                                <div className="flex items-center gap-2">
                                    <Shield className="h-4 w-4 text-muted-foreground" />
                                    <Label htmlFor="security-enabled" className="cursor-pointer">
                                        Security Alerts
                                    </Label>
                                </div>
                                <p className="text-sm text-muted-foreground">Important security updates and alerts</p>
                            </div>
                            <Switch id="security-enabled" checked={securityEnabled} onCheckedChange={setSecurityEnabled} />
                        </div>

                        <div className="flex items-center justify-between">
                            <div className="space-y-0.5">
                                <div className="flex items-center gap-2">
                                    <Package className="h-4 w-4 text-muted-foreground" />
                                    <Label htmlFor="product-enabled" className="cursor-pointer">
                                        Product Updates
                                    </Label>
                                </div>
                                <p className="text-sm text-muted-foreground">New features and product announcements</p>
                            </div>
                            <Switch id="product-enabled" checked={productEnabled} onCheckedChange={setProductEnabled} />
                        </div>

                        <div className="flex items-center justify-between">
                            <div className="space-y-0.5">
                                <Label htmlFor="marketing-enabled" className="cursor-pointer">
                                    Marketing & Promotions
                                </Label>
                                <p className="text-sm text-muted-foreground">Tips, offers, and promotional content</p>
                            </div>
                            <Switch id="marketing-enabled" checked={marketingEnabled} onCheckedChange={setMarketingEnabled} />
                        </div>
                    </CardContent>
                </Card>

                {/* Action Buttons */}
                <div className="flex justify-end gap-2">
                    <Button
                        type="button"
                        variant="outline"
                        onClick={() => {
                            if (preferences) {
                                setEmailEnabled(preferences.email_enabled ?? true);
                                setInAppEnabled(preferences.in_app_enabled ?? true);
                                setDigestMode(preferences.digest_mode || 'immediate');
                                setDndEnabled(preferences.dnd_enabled ?? false);
                                setMarketingEnabled(preferences.marketing_enabled ?? false);
                                setSecurityEnabled(preferences.security_enabled ?? true);
                                setProductEnabled(preferences.product_enabled ?? true);
                            }
                        }}
                        disabled={updatePreferencesMutation.isPending}
                    >
                        Reset
                    </Button>
                    <Button type="submit" disabled={updatePreferencesMutation.isPending}>
                        {updatePreferencesMutation.isPending ? (
                            <>
                                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                Saving...
                            </>
                        ) : (
                            'Save Changes'
                        )}
                    </Button>
                </div>
            </form>
        </div>
    );
}
