import { FormField, FormItem, FormLabel, FormMessage, FormControl } from "@/components/ui/form"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Checkbox } from "@/components/ui/checkbox"
import { cn } from "@/lib/utils"
import GenreCheckbox from "./genreCheckbox"

export default function GenrePicker({ genres, form }) {
	return (
		<Popover modal={true}>
			<FormField
				control={form.control}
				name="genres"
				render={({ field }) => (
					<FormItem className="flex flex-col">
						<FormLabel className="h-5">Genres</FormLabel>
						<PopoverTrigger asChild>
							<Button
								variant={"outline"}
								className={cn(
									"min-w-fit max-w-full w-fit pl-3 text-left font-normal flex-wrap gap-y-1 h-fit min-h-10",
									!field.value && "text-muted-foreground"
								)}
							>
								{field.value.length !== 0 ? (
									field.value.map((e, i) => (<Badge key={i}>{genres.find(f => e === f.id).name}</Badge>))
								) : (
									<p>Select</p>
								)}
							</Button>
						</PopoverTrigger>



						<PopoverContent align="start">
							{genres.map((item) => (
								< FormField
									key={item.id}
									control={form.control}
									name="genres"
									render={({ field }) => {
										return (
											<FormItem
												key={item.id}
												className="flex flex-row items-start space-x-3 space-y-0"
											>
												<FormControl>
													<Checkbox
														checked={field.value?.includes(item.id)}
														onCheckedChange={(checked) => {
															return checked
																? field.onChange([...field.value, item.id])
																: field.onChange(
																	field.value?.filter(
																		(value) => value !== item.id
																	)
																)
														}}
													/>
												</FormControl>
												<FormLabel className="text-sm font-normal">
													{item.name}
												</FormLabel>
											</FormItem>
										)
									}}
								/>
							))}
							<Button variant="link" className="p-0" onClick={() => form.setValue("genres", [])}>Clear</Button>
						</PopoverContent>
						<FormMessage />
					</FormItem>
				)}
			/>
		</Popover>
	)
}





