"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,
        }),
        instructions: z.string().optional(),
    })

    const form = useForm<z.infer<typeof formSchema>>({
        resolver: zodResolver(formSchema),
        defaultValues: {
            title: "",
            password: "",
            instructions: "",
        },
    })

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

    async function onSubmit(values: z.infer<typeof formSchema>) {
        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,
                }),
            })

            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>
                    )}
                />
                <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>
    )
}
