"use client"

import * as React from "react"
import { CalendarIcon } from "lucide-react"
import { format } from "date-fns"
import { zodResolver } from "@hookform/resolvers/zod"
import * as z from "zod"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Calendar } from "@/components/ui/calendar"
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Checkbox } from "@/components/ui/checkbox"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { useForm } from "react-hook-form"
import {
	CalendarEventExternal,
} from "@schedule-x/calendar";
import ICalendarEvent from "@/interfaces/ICalendarEvent"

export const eventFormSchema = z.object({
	title: z.string().min(1, "Titre requis"),
	startDate: z.date({
		required_error: "Date de début requise",
	}),
	startTime: z.string(),
	endDate: z.date({
		required_error: "Date finale requise",
	}),
	endTime: z.string(),
	fullDay: z.boolean().default(false),
	frequency: z.enum(["unique", "quotidien", "hebdomadaire", "mensuel"]),
	frequencyEndDate: z.date().optional(),
	isVisible: z.boolean().default(true),
})

export type EventFormValues = z.infer<typeof eventFormSchema>

const frequencies = [
	{ label: "Unique", value: "unique" },
	{ label: "Quotidien", value: "quotidien" },
	{ label: "Hebdomadaire", value: "hebdomadaire" },
	{ label: "Mensuel", value: "mensuel" },
]

const isCalendarEventExternal = (event: CalendarEventExternal | Omit<CalendarEventExternal, "id">): event is CalendarEventExternal => {
  return (event as CalendarEventExternal).id !== undefined;
};

export const EventForm: React.FC<
	{
		event: ICalendarEvent | Omit<ICalendarEvent, "id">;
		onSubmitEvent: (eventFormValues: EventFormValues) => void;
	}
> = ({
	event,
	onSubmitEvent,
}) => {
		
		const form =  useForm<EventFormValues>({
			resolver: zodResolver(eventFormSchema),
			defaultValues: {
				title:		event.title ? event.title : "",
				startDate:	new Date(), // event.start),
				startTime:	`${new Date(event.start).getHours()}:${new Date(event.start).getMinutes()}`,
				endDate:    new Date(), // event.end),
				endTime:	`${new Date(event.end).getHours()}:${new Date(event.end).getMinutes()}`,
				fullDay:	event.fullday,
				frequency:	"unique",
				isVisible:  event.isVisible,
			},
		}) 	

		const frequency = form.watch("frequency")

		async function onSubmit(data: EventFormValues) {
			try {
				const validatedData = eventFormSchema.parse(data)
				onSubmitEvent(validatedData)
			} catch (error) {
				console.error("On submit error : ", error)
			}
		}

		return (
			<Form {...form}>
				<form onSubmit={form.handleSubmit(onSubmit)} className="w-full max-w-md space-y-4">
					<FormField
						control={form.control}
						name="title"
						render={({ field }) => (
							<FormItem>
								<FormLabel>Titre</FormLabel>
								<FormControl>
									<Input placeholder="Ajouter un titre" {...field} />
								</FormControl>
								<FormMessage />
							</FormItem>
						)}
					/>

					<div className="grid grid-cols-[1fr,auto,1fr] items-end gap-2">
						<FormField
							control={form.control}
							name="startDate"
							render={({ field }) => (
								<FormItem className="flex flex-col">
									<FormLabel>Début</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 ? format(field.value, "yyyy-mm-dd hh:mm") : <span>Choisis une date</span>}
													<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
												</Button>
											</FormControl>
										</PopoverTrigger>
										<PopoverContent className="w-auto p-0" align="start">
											<Calendar mode="single" selected={field.value} onSelect={field.onChange} initialFocus />
										</PopoverContent>
									</Popover>
									<FormMessage />
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="startTime"
							render={({ field }) => (
								<FormItem>
									<FormControl>
										<Input type="time" {...field} className="w-[120px]" />
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>

						<span className="invisible">Until</span>

						<FormField
							control={form.control}
							name="endDate"
							render={({ field }) => (
								<FormItem className="flex flex-col">
									<FormLabel>Fin</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 ? format(field.value,  "yyyy-mm-dd hh:mm") : <span>Choisis une date</span>}
													<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
												</Button>
											</FormControl>
										</PopoverTrigger>
										<PopoverContent className="w-auto p-0" align="start">
											<Calendar mode="single" selected={field.value} onSelect={field.onChange} initialFocus />
										</PopoverContent>
									</Popover>
									<FormMessage />
								</FormItem>
							)}
						/>

						<FormField
							control={form.control}
							name="endTime"
							render={({ field }) => (
								<FormItem>
									<FormControl>
										<Input type="time" {...field} className="w-[120px]" />
									</FormControl>
									<FormMessage />
								</FormItem>
							)}
						/>
					</div>

					<FormField
						control={form.control}
						name="fullDay"
						render={({ field }) => (
							<FormItem className="flex flex-row items-start space-x-3 space-y-0">
								<FormControl>
									<Checkbox checked={field.value} onCheckedChange={field.onChange} />
								</FormControl>
								<FormLabel>Journée complète</FormLabel>
								<FormMessage />
							</FormItem>
						)}
					/>

					<div className="flex gap-4 items-end">
						<FormField
							control={form.control}
							name="frequency"
							render={({ field }) => (
								<FormItem className="flex-1">
									<FormLabel>Fréquence</FormLabel>
									<Select onValueChange={field.onChange} defaultValue={field.value}>
										<FormControl>
											<SelectTrigger>
												<SelectValue placeholder="Selectionner Fréquence" />
											</SelectTrigger>
										</FormControl>
										<SelectContent>
											{frequencies.map((frequency) => (
												<SelectItem key={frequency.value} value={frequency.value}>
													{frequency.label}
												</SelectItem>
											))}
										</SelectContent>
									</Select>
									<FormMessage />
								</FormItem>
							)}
						/>

						{frequency !== "unique" && (
							<FormField
								control={form.control}
								name="frequencyEndDate"
								render={({ field }) => (
									<FormItem className="flex-1">
										<FormLabel>Jusqu'au</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 ? format(field.value, "MM/dd/yyyy") : <span>Choisis une date</span>}
														<CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
													</Button>
												</FormControl>
											</PopoverTrigger>
											<PopoverContent className="w-auto p-0" align="start">
												<Calendar mode="single" selected={field.value} onSelect={field.onChange} initialFocus />
											</PopoverContent>
										</Popover>
										<FormMessage />
									</FormItem>
								)}
							/>
						)}
					</div>

					<FormField
						control={form.control}
						name="isVisible"
						render={({ field }) => (
							<FormItem className="flex-1">
								<FormLabel className="align-sub">Evènement visible ?</FormLabel>
								<FormControl>
									<Checkbox className="m-3 align-top justify-center"
										checked={field.value}
										onCheckedChange={field.onChange}
									/>
								</FormControl>
								<FormMessage />
							</FormItem>
						)}
					/>
					<div className="flex justify-end space-x-2">
						<Button variant="outline" type="button">
							Abandonner
						</Button>
						<Button type="submit" className="bg-[#6B4EFF] hover:bg-[#5B3FEF]">
							Sauvegarder
						</Button>
					</div>
				</form>
			</Form>
		)
	}


