'use client';

import { Button } from '@/components/ui/button';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem } from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { Workspace } from '@prisma/client';
import { CommandList } from 'cmdk';
import { Check, ChevronsUpDown } from 'lucide-react';
import { usePathname, useRouter } from 'next/navigation';
import React from 'react';

export default function WorkspaceNavigation({ workspaces }: { workspaces: Pick<Workspace, 'id' | 'name' | 'slug'>[] }) {
	const pathname = usePathname();

	const [open, setOpen] = React.useState<boolean>(false);
	const [value, setValue] = React.useState<Pick<Workspace, 'id'> | null>(findSelectedWorkspace());

	const router = useRouter();

	function onWorkspaceSelectionChange(workspace: Pick<Workspace, 'id'>) {
		router.push(`/${workspaces.find((w) => w.id === workspace.id)?.slug}/${pathname.split('/')[2]}`);

		// router.push(`/${workspaces.find((w) => w.id === workspace.id)?.slug}`);
	}

	function findSelectedWorkspace(): Pick<Workspace, 'id'> | null {
		const workspace = pathname.split('/')[1];
		if (!workspace) return null;
		const w = workspaces.find((w) => w.slug === workspace);
		if (!w) return null;
		return { id: w.id };
	}

	return (
		<Popover open={open} onOpenChange={setOpen}>
			<PopoverTrigger asChild>
				<Button variant="outline" role="combobox" aria-expanded={open} className="w-[200px] justify-between">
					{value ? workspaces.find((workspace) => workspace.id === value.id)?.name : 'Select workspace...'}
					<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
				</Button>
			</PopoverTrigger>
			<PopoverContent className="w-[200px] p-0">
				<Command>
					<CommandInput placeholder="Search workspace..." />
					<CommandList>
						<CommandEmpty>
							<Button variant="ghost" className="">
								Create a Workspace
							</Button>
						</CommandEmpty>
						<CommandGroup>
							{workspaces.map((workspace) => (
								<CommandItem
									key={workspace.id}
									value={workspace.id}
									keywords={[workspace.name, workspace.slug]}
									onSelect={(currentValue) => {
										setValue({ id: currentValue });
										onWorkspaceSelectionChange({ id: currentValue });
										setOpen(false);
									}}
								>
									<Check className={cn('mr-2 h-4 w-4', value?.id === workspace.id ? 'opacity-100' : 'opacity-0')} />
									{workspace.name}
								</CommandItem>
							))}
						</CommandGroup>
					</CommandList>
				</Command>
			</PopoverContent>
		</Popover>
	);
}
