import { Locale } from "date-fns";
import { enUS } from "date-fns/locale/en-US";
import { kk } from "date-fns/locale/kk";
import { ru } from "date-fns/locale/ru";
import { ChevronDownIcon } from "lucide-react";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { formatTime } from "@/services/time.service";
import { Button, Input } from "@/shared";

import { Calendar, Popover, PopoverContent, PopoverTrigger } from "./Shadcn";

interface Props {
	name: string;
	value: Date;
	onChange: (name: string, value: Date) => void;
}

export function DateTimePicker({ name, value, onChange }: Props) {
	const { i18n } = useTranslation("translation");
	const [locale, setLocale] = useState(getLocale(i18n.language));
	const [open, setOpen] = useState(false);

	useEffect(() => {
		setLocale(getLocale(i18n.language));
	}, [i18n.language]);

	function getLocale(language: string): Locale {
		switch (language) {
			case "ru":
				return ru;
			case "kk":
				return kk;
			default:
				return enUS;
		}
	}

	return (
		<div className="flex gap-3 items-center">
			<div className="flex flex-col gap-3">
				<Popover open={open} onOpenChange={setOpen}>
					<PopoverTrigger asChild>
						<Button
							variant="outline"
							id="date"
							className="w-32 justify-between font-normal"
						>
							{value ? value.toLocaleDateString() : "Select date"}
							<ChevronDownIcon />
						</Button>
					</PopoverTrigger>
					<PopoverContent
						className="w-auto overflow-hidden p-0"
						align="start"
					>
						<Calendar
							mode="single"
							selected={value}
							captionLayout="dropdown"
							onSelect={(date) => {
								onChange(name, date || new Date());
								setOpen(false);
							}}
							locale={locale}
						/>
					</PopoverContent>
				</Popover>
			</div>
			<div className="flex flex-col gap-3">
				<Input
					type="time"
					id="time"
					step="1"
					value={formatTime(value)}
					onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
						onChange(
							name,
							new Date(
								value.setHours(
									Number(e.target.value.split(":")[0]),
									Number(e.target.value.split(":")[1]),
									Number(e.target.value.split(":")[2]),
								),
							),
						);
					}}
					className="bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"
				/>
			</div>
		</div>
	);
}
