"use client"

import { zodResolver } from "@hookform/resolvers/zod"
import { format } from "date-fns"
import { de, enUS } from "date-fns/locale"
import { CalendarIcon } from "lucide-react"
import { useForm } from "react-hook-form"
import { z } from "zod"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import {
    Form,
    FormControl,
    FormDescription,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { toast } from "sonner"
import { useRouter } from "next/navigation"

interface CreatePlanFormProps {
    dict: any;
    lang: string;
}

export function CreatePlanForm({ dict, lang }: CreatePlanFormProps) {
    const router = useRouter()

    const formSchema = z.object({
        title: z.string().min(2, {
            message: dict.titleError,
        }),
        dateRange: z.object({
            from: z.date(),
            to: z.date(),
        }),
        password: z.string().min(4, {
            message: dict.passwordError,
        }),
        feedingPerDay: z.coerce.number().min(1).max(10),
        feedingInterval: z.coerce.number().min(1).max(30),
        litterInterval: z.coerce.number().min(1).max(30),
        instructions: z.string().optional(),
    })

    type FormValues = z.infer<typeof formSchema>

    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema) as any,
        defaultValues: {
            title: "",
            password: "",
            instructions: "",
            feedingPerDay: 2,
            feedingInterval: 1,
            litterInterval: 2,
            dateRange: {
                from: undefined,
                to: undefined,
            }
        },
    })

    const dateLocale = lang === "de" ? de : enUS

    async function onSubmit(values: FormValues) {
        try {
            const response = await fetch("/api/plan", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    title: values.title,
                    startDate: values.dateRange.from,
                    endDate: values.dateRange.to,
                    password: values.password,
                    instructions: values.instructions,
                    feedingPerDay: values.feedingPerDay,
                    feedingInterval: values.feedingInterval,
                    litterInterval: values.litterInterval,
                }),
            })

            if (!response.ok) {
                throw new Error("Failed to create plan")
            }

            const data = await response.json()
            toast.success(dict.success)
            router.push(`/${lang}/dashboard/${data.planId}`)
        } catch (error) {
            toast.error(dict.error)
            console.error(error)
        }
    }

    return (
        <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
                <FormField
                    control={form.control}
                    name="title"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{dict.title}</FormLabel>
                            <FormControl>
                                <Input placeholder={dict.titlePlaceholder} {...field} />
                            </FormControl>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <FormField
                    control={form.control}
                    name="dateRange"
                    render={({ field }) => (
                        <FormItem className="flex flex-col">
                            <FormLabel>{dict.travelDates}</FormLabel>
                            <Popover>
                                <PopoverTrigger asChild>
                                    <FormControl>
                                        <Button
                                            variant={"outline"}
                                            className={cn(
                                                "w-full pl-3 text-left font-normal",
                                                !field.value && "text-muted-foreground"
                                            )}
                                        >
                                            {field.value?.from ? (
                                                field.value.to ? (
                                                    <>
                                                        {format(field.value.from, "PPP", { locale: dateLocale })} -{" "}
                                                        {format(field.value.to, "PPP", { locale: dateLocale })}
                                                    </>
                                                ) : (
                                                    format(field.value.from, "PPP", { locale: dateLocale })
                                                )
                                            ) : (
                                                <span>{dict.pickDateRange}</span>
                                            )}
                                            <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
                                        </Button>
                                    </FormControl>
                                </PopoverTrigger>
                                <PopoverContent className="w-auto p-0" align="start">
                                    <Calendar
                                        mode="range"
                                        selected={field.value}
                                        onSelect={field.onChange}
                                        disabled={(date) =>
                                            date < new Date(new Date().setHours(0, 0, 0, 0))
                                        }
                                        initialFocus
                                        locale={dateLocale}
                                    />
                                </PopoverContent>
                            </Popover>
                            <FormDescription>
                                {dict.dateRangeDesc}
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <FormField
                        control={form.control}
                        name="feedingInterval"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel className="min-h-[3.5rem] flex items-end pb-2">{dict.feedingInterval}</FormLabel>
                                <FormControl>
                                    <Input type="number" {...field} />
                                </FormControl>
                                <FormDescription className="min-h-[4rem]">{dict.feedingIntervalDesc}</FormDescription>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="feedingPerDay"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel className="min-h-[3.5rem] flex items-end pb-2">{dict.feedingPerDay}</FormLabel>
                                <FormControl>
                                    <Input type="number" {...field} />
                                </FormControl>
                                <FormDescription className="min-h-[4rem]">{dict.feedingDesc}</FormDescription>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="litterInterval"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel className="min-h-[3.5rem] flex items-end pb-2">{dict.litterInterval}</FormLabel>
                                <FormControl>
                                    <Input type="number" {...field} />
                                </FormControl>
                                <FormDescription className="min-h-[4rem]">{dict.litterDesc}</FormDescription>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                </div>

                <FormField
                    control={form.control}
                    name="password"
                    render={({ field }) => (
                        <FormItem>
                            <FormLabel>{dict.groupPassword}</FormLabel>
                            <FormControl>
                                <Input placeholder={dict.passwordPlaceholder} {...field} />
                            </FormControl>
                            <FormDescription>
                                {dict.passwordDesc}
                            </FormDescription>
                            <FormMessage />
                        </FormItem>
                    )}
                />
                <Button type="submit" className="w-full">{dict.submit}</Button>
            </form>
        </Form>
    )
}
