import { WOO_MERGE_TAGS } from '@/woocommerce/elements/data-field/constants/merge-tags';
import { Button } from '@pdfdraft/ui/components/button';
import {
	Command,
	CommandEmpty,
	CommandGroup,
	CommandInput,
	CommandItem,
	CommandList,
} from '@pdfdraft/ui/components/command';
import {
	Popover,
	PopoverContent,
	PopoverTrigger,
} from '@pdfdraft/ui/components/popover';
import { ScrollAreaPrimitive } from '@pdfdraft/ui/components/scroll-area';
import { ChevronDown } from '@pdfdraft/ui/icons';
import { cn } from '@pdfdraft/ui/lib/utils';
import { __ } from '@wordpress/i18n';
import { Fragment, useEffect, useRef, useState } from 'react';
// import {useDisclosure} from '@pdfdraft/core/hooks/use-disclosure'

type MergeTagSelectProps = {
	mergeTag?: string;
	onMergeTagChange?: (mergeTag: string) => void;
	defaultOpen?: boolean;
};

export function MergeTagSelect(props: MergeTagSelectProps) {
	const [local, setLocal] = useState(props.mergeTag);
	const hasTag = Boolean(local);
	const popoverTriggerRef = useRef<HTMLButtonElement>(null);

	useEffect(() => {
		if (props.mergeTag) {
			setLocal(props.mergeTag);
		}
	}, [props.mergeTag]);
	return (
		<Popover defaultOpen={!hasTag ? true : false} modal={false}>
			<PopoverTrigger asChild ref={popoverTriggerRef}>
				<Button
					variant="ghost"
					role="combobox"
					className="border-input ring-offset-background placeholder:text-muted-foreground flex h-[38px] w-[200px] min-w-[200px] items-center justify-between whitespace-nowrap rounded border bg-transparent px-3 py-2 text-sm shadow-none focus:outline-none focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1"
				>
					<span
						data-empty={!hasTag}
						className={cn(
							'pointer-events-none truncate font-mono text-sm font-normal data-[empty=true]:text-[#979797]',
							// currentFontFamily &&
							// 	FontLoader.familyToCSSClass(currentFontFamily),
						)}
					>
						{hasTag ? local : __('Select dynamic data', 'pdfdraft-pdf-invoices-for-woocommerce')}
					</span>
					<ChevronDown size={12} className="!size-3 shrink-0 opacity-50" />
				</Button>
			</PopoverTrigger>
			<PopoverContent
				className="z-[10000] w-[344px] rounded border-none p-0 shadow-[0px_6px_24px_0px_rgba(10,10,10,0.08)]"
				align="start"
				side="bottom"
				sideOffset={15}
				alignOffset={-8}
				onCloseAutoFocus={(e) => e.preventDefault()}
			>
				<Command>
					<CommandInput placeholder={__('Search...')} />
					<CommandList>
						<CommandEmpty>
							{__(
								'Sorry, we couldn’t find any results. Try searching something related.',
								'pdfdraft-pdf-invoices-for-woocommerce',
							)}
						</CommandEmpty>
						<ScrollAreaPrimitive.Root className="relative h-52 overflow-hidden">
							<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
								{WOO_MERGE_TAGS.map((item) => (
									<Fragment key={item.key}>
										<CommandGroup
											className="p-2 [&_[cmdk-group-heading]]:mb-1 [&_[cmdk-group-heading]]:rounded-[3px] [&_[cmdk-group-heading]]:bg-[#f7f7f7] [&_[cmdk-group-heading]]:px-4 [&_[cmdk-group-heading]]:py-[10px] [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-[#383838]"
											heading={item.groupLabel}
										>
											{item.fields.map((field) => (
												<CommandItem
													key={field.tag}
													value={field.tag}
													onSelect={() => {
														setLocal(field.tag);
														props.onMergeTagChange?.(field.tag);
														popoverTriggerRef?.current?.click();
													}}
													className="px-4 py-[10px] text-sm text-[#383838] data-[selected=true]:bg-[#f7f7f7]"
												>
													<div className="flex w-full flex-col gap-0.5 text-left">
														<span className="text-sm font-medium text-[#383838]">
															{field.label}
														</span>
														<span className="font-mono text-xs text-[#979797]">
															{field.tag}
														</span>
													</div>
												</CommandItem>
											))}
										</CommandGroup>
									</Fragment>
								))}
							</ScrollAreaPrimitive.Viewport>
							<ScrollAreaPrimitive.Scrollbar className="flex h-full w-2.5 touch-none select-none border-l border-l-transparent p-[1px] transition-colors">
								<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-[#575757]" />
							</ScrollAreaPrimitive.Scrollbar>
							<ScrollAreaPrimitive.Corner />
						</ScrollAreaPrimitive.Root>
					</CommandList>
				</Command>
			</PopoverContent>
		</Popover>
	);
}
