"use client"

import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { Button } from "@/components/ui/button"
import { toast } from "@/components/ui/use-toast"
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from "@/components/ui/popover"

import { Calendar } from "@/components/ui/calendar"
import { CalendarIcon } from "@radix-ui/react-icons"
import { cn } from "@/lib/utils"
import { format } from "date-fns"
import {
	Form,
	FormItem,
	FormLabel,
	FormField,
	FormControl,
	FormDescription,
	FormMessage
} from "@/components/ui/form"
import {
	Select,
	SelectContent,
	SelectItem,
	SelectTrigger,
	SelectValue,
} from "@/components/ui/select"
import { useState } from "react"

export const formSchema = z.object({
	storyId: z.coerce.number(),
	pubId: z.coerce.number(),
	submitted: z.date().transform((date) => date.toString()),
	responded: z.date().transform((date) => date.toString()).optional(),
	responseId: z.coerce.number()
})
	.refine(object => {
		const submitted = new Date(object.submitted)
		const responded = object.responded ? new Date(object.responded) : null
		return responded >= submitted || responded === null
	},
		{
			path: ["responded"],
			message: "'Responded' must be a later date than 'submitted'"
		})
	.refine(object => {
		if (object.responded) {
			//there is a 'responded' date and the response is not 'pending'
			return object.responseId !== 7
		}
		if (!object.responded) {
			//there is not a 'responded' date and the response is pending
			return object.responseId === 7
		}
	},
		{
			path: ["responseId"],
			message: "A pending response cannot have a date, and a non-pending response must have a date"
		}
	)


export default function SubmissionForm({ stories, pubs, responses, createSub, defaults }) {
	const form = useForm<z.infer<typeof formSchema>>({
		resolver: zodResolver(formSchema),
		defaultValues: {
			responseId: responses[0].id,
			...defaults
		}
	})
	const [isSubCalendarOpen, setIsSubCalendarOpen] = useState(false);
	const [isRespCalendarOpen, setIsRespCalendarOpen] = useState(false);
	const storiesSelectItems = stories.map(e => (
		<SelectItem value={e.id.toString()} key={e.title}>
			{e.title}
		</SelectItem>
	))
	const pubsSelectItems = pubs.map(e => (
		<SelectItem value={e.id}>
			{e.title}
		</SelectItem>
	))

	const reponsesSelectItems = responses.map(e => (
		<SelectItem value={e.id}>
			{e.response}
		</SelectItem>
	))


	// 2. Define a submit handler.
	function onSubmit(values: z.infer<typeof formSchema>) {
		// Do something with the form values.
		// ✅ This will be type-safe and validated.
		toast({
			title: "You submitted the following values:",
			description: (
				<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
					<code className="text-white">{JSON.stringify(values, null, 2)}</code>
				</pre>
			),
		})
		createSub(values)
		console.log(values)
	}

	function onErrors(errors) {
		toast({
			title: "You have errors",
			description: (
				<pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
					<code className="text-white">{JSON.stringify(errors, null, 2)}</code>
				</pre>
			),
		})
		console.log(JSON.stringify(errors))
	}

	return (
		<Form {...form}>
			<form id="subform" onSubmit={form.handleSubmit(onSubmit, onErrors)} className="space-y-8">
				<FormField
					control={form.control}
					name="storyId"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Story</FormLabel>
							<Select onValueChange={field.onChange} defaultValue={field.value}>
								<FormControl>
									<SelectTrigger>
										<SelectValue placeholder="Select something">
											<p>{stories?.find(e => e.id === Number(field.value))?.title ?? null}</p>
										</SelectValue>
									</SelectTrigger>
								</FormControl>
								<SelectContent>
									{storiesSelectItems}
								</SelectContent>
							</Select>
							<FormDescription>The piece you submitted</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>
				<FormField
					control={form.control}
					name="pubId"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Publication</FormLabel>
							<Select onValueChange={field.onChange} defaultValue={field.value}>
								<FormControl>
									<SelectTrigger>
										<SelectValue placeholder="Select something">
											<p>{pubs?.find(e => e.id === Number(field.value))?.title ?? null}</p>
										</SelectValue>
									</SelectTrigger>
								</FormControl>
								<SelectContent>
									{pubsSelectItems}
								</SelectContent>
							</Select>
							<FormDescription>The market you sent it to</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>

				<FormField
					control={form.control}
					name="submitted"
					render={({ field }) => (
						<FormItem className="flex flex-col">
							<FormLabel>Date of submission</FormLabel>
							<Popover modal={true} open={isSubCalendarOpen} onOpenChange={setIsSubCalendarOpen}>
								<PopoverTrigger asChild>
									<FormControl>
										<Button
											variant={"outline"}
											className={cn(
												"w-[240px] pl-3 text-left font-normal",
												!field.value && "text-muted-foreground"
											)}
										>
											{field.value ? (
												format(field.value, "PPP")
											) : (
												<span>Pick a 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={(e) => { field.onChange(e); setIsSubCalendarOpen(false); }}
										disabled={(date) =>
											date > new Date() || date < new Date("1900-01-01")
										}
										initialFocus
									/>
								</PopoverContent>
							</Popover>
							<FormDescription>
								The date you sent it
							</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>

				<FormField
					control={form.control}
					name="responded"
					render={({ field }) => (
						<FormItem className="flex flex-col">
							<FormLabel>Date of response</FormLabel>
							<Popover modal={true} open={isRespCalendarOpen} onOpenChange={setIsRespCalendarOpen}>
								<PopoverTrigger asChild>
									<FormControl>
										<Button
											variant={"outline"}
											className={cn(
												"w-[240px] pl-3 text-left font-normal",
												!field.value && "text-muted-foreground"
											)}
										>
											{field.value ? (
												format(field.value, "PPP")
											) : (
												<span>Pick a 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={(e) => { field.onChange(e); setIsRespCalendarOpen(false); }}
										disabled={(date) =>
											date > new Date() || date < new Date("1900-01-01")
										}
										initialFocus
									/>
								</PopoverContent>
							</Popover>
							<FormDescription>
								The date they wrote back
							</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>


				<FormField
					control={form.control}
					name="responseId"
					render={({ field }) => (
						<FormItem>
							<FormLabel>Response</FormLabel>
							<Select onValueChange={field.onChange} defaultValue={field.value}>
								<FormControl>
									<SelectTrigger>
										<SelectValue>
											<p>{responses?.find(e => e.id === Number(field.value))?.response ?? null}</p>
										</SelectValue>
									</SelectTrigger>
								</FormControl>
								<SelectContent>
									{reponsesSelectItems}
								</SelectContent>
							</Select>
							<FormDescription>The market you sent it to</FormDescription>
							<FormMessage />
						</FormItem>
					)}
				/>

			</form>
		</Form>
	)
}
