import { NotebookPen } from "lucide-react";
import { useState } from "react";
import LoadingButton from "~/components/custom_ui/loading-button";
import { Button } from "~/components/ui/button";
import {
	Popover,
	PopoverContent,
	PopoverDescription,
	PopoverHeader,
	PopoverTitle,
	PopoverTrigger,
} from "~/components/ui/popover";
import { Textarea } from "~/components/ui/textarea";
import type { UsersId } from "~/schemas/public/Users";

export const NotePopover = ({
	userId,
	note,
	mutate,
	isPending,
}: {
	userId: UsersId;
	note: string | null;
	mutate: (data: { id: UsersId; data: { note: string | null } }) => void;
	isPending: boolean;
}) => {
	const [newNote, setNewNote] = useState<string | null>(note);

	return (
		<Popover>
			<PopoverTrigger asChild>
				<div className="relative inline-flex">
					<Button className="inline-flex" size="sm" variant="orange">
						<NotebookPen className="size-4" />
					</Button>
					{note && note.trim().length > 0 && (
						<span className="absolute top-0 right-0 -mt-1 -mr-1 flex size-3">
							<span className="relative inline-flex size-3 rounded-full bg-green-500"></span>
						</span>
					)}
				</div>
			</PopoverTrigger>
			<PopoverContent
				align="start"
				className="max-h-[50vh] w-[80vw] overflow-y-auto sm:max-h-full sm:w-lg"
			>
				<PopoverHeader>
					<PopoverTitle>Annunci Inseriti</PopoverTitle>
					<PopoverDescription className="sr-only">Desc</PopoverDescription>
				</PopoverHeader>
				<div className="flex w-full flex-col gap-4">
					<Textarea
						className="min-h-64"
						id="note"
						onChange={(e) => setNewNote(e.target.value)}
						placeholder=""
						value={newNote || ""}
					/>
					<LoadingButton
						disabled={newNote === note}
						loading={isPending}
						onClick={() => mutate({ id: userId, data: { note: newNote } })}
						variant="success"
					>
						Salva
					</LoadingButton>
				</div>
			</PopoverContent>
		</Popover>
	);
};
