import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Loader2, Sun, Moon } from "lucide-react";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";

export function RoutineSettingsCard() {
    const { t } = useTranslation();
    const { toast } = useToast();
    const queryClient = useQueryClient();

    const [morningEnabled, setMorningEnabled] = useState(true);
    const [morningTime, setMorningTime] = useState("09:00");
    const [eveningEnabled, setEveningEnabled] = useState(true);
    const [eveningTime, setEveningTime] = useState("22:00");

    const { data: settings, isLoading } = useQuery<Record<string, string>>({
        queryKey: ['/api/admin/settings'],
        queryFn: async () => {
            const res = await apiRequest("GET", "/api/admin/settings");
            if (!res.ok) throw new Error("Failed to fetch settings");
            return res.json();
        }
    });

    useEffect(() => {
        if (settings) {
            setMorningEnabled(settings.morning_routine_enabled !== "false");
            setMorningTime(settings.morning_routine_time || "09:00");
            setEveningEnabled(settings.evening_routine_enabled !== "false");
            setEveningTime(settings.evening_routine_time || "22:00");
        }
    }, [settings]);

    const mutation = useMutation({
        mutationFn: async () => {
            const updates = {
                morning_routine_enabled: String(morningEnabled),
                morning_routine_time: morningTime,
                evening_routine_enabled: String(eveningEnabled),
                evening_routine_time: eveningTime,
            };

            // We send individual updates or a bulk update?
            // The backend /api/admin/settings usually accepts a map of KVs to update.
            // Checking AdminSettings.tsx might verify this, but typically we post to specific keys or bulk object.
            // Assuming GET returns object, POST probably takes object.
            // If server routes handle bulk update.
            // If not, we loop.
            // Checking AiSettingsCard logic: it calls `/api/admin/settings` with JSON body.
            // Assuming generic handler supports partial updates.

            const res = await apiRequest("POST", "/api/admin/settings", updates);
            if (!res.ok) throw new Error(await res.text());
            return res.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['/api/admin/settings'] });
            toast({ title: t('settings.routines.saved', 'Routine settings saved') });
        },
        onError: (err: Error) => {
            toast({
                title: t('settings.routines.error', 'Failed to save settings'),
                description: err.message,
                variant: "destructive"
            });
        }
    });

    return (
        <Card>
            <CardHeader>
                <CardTitle>{t('settings.routines.title', 'Routine Configuration')}</CardTitle>
                <CardDescription>
                    {t('settings.routines.description', 'Configure global morning and evening routine schedules.')}
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
                {/* Morning Routine */}
                <div className="flex flex-col gap-4 border-b pb-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <Sun className="h-5 w-5 text-orange-500" />
                            <Label htmlFor="morning_enabled" className="text-base font-medium">
                                {t('settings.routines.morningLabel', 'Morning Routine')}
                            </Label>
                        </div>
                        <Switch
                            id="morning_enabled"
                            checked={morningEnabled}
                            onCheckedChange={setMorningEnabled}
                            disabled={isLoading}
                        />
                    </div>

                    {morningEnabled && (
                        <div className="pl-7">
                            <Label htmlFor="morning_time" className="mb-2 block text-sm text-muted-foreground">{t('settings.routines.time', 'Start Time')}</Label>
                            <Input
                                id="morning_time"
                                type="time"
                                value={morningTime}
                                onChange={(e) => setMorningTime(e.target.value)}
                                className="w-32"
                            />
                        </div>
                    )}
                </div>

                {/* Evening Routine */}
                <div className="flex flex-col gap-4">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <Moon className="h-5 w-5 text-indigo-500" />
                            <Label htmlFor="evening_enabled" className="text-base font-medium">
                                {t('settings.routines.eveningLabel', 'Evening Routine')}
                            </Label>
                        </div>
                        <Switch
                            id="evening_enabled"
                            checked={eveningEnabled}
                            onCheckedChange={setEveningEnabled}
                            disabled={isLoading}
                        />
                    </div>

                    {eveningEnabled && (
                        <div className="pl-7">
                            <Label htmlFor="evening_time" className="mb-2 block text-sm text-muted-foreground">{t('settings.routines.time', 'Start Time')}</Label>
                            <Input
                                id="evening_time"
                                type="time"
                                value={eveningTime}
                                onChange={(e) => setEveningTime(e.target.value)}
                                className="w-32"
                            />
                        </div>
                    )}
                </div>

                <div className="pt-4 flex justify-end">
                    <Button onClick={() => mutation.mutate()} disabled={isLoading || mutation.isPending}>
                        {mutation.isPending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                        {t('settings.routines.save', 'Save Routines')}
                    </Button>
                </div>
            </CardContent>
        </Card>
    );
}
