"use client";

import { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { CategoryIcon } from "@/components/ui/category-icon";
import { ChevronsUpDown, Check, X } from "lucide-react";
import { cn } from "@/lib/utils";
import type { Category } from "@/lib/types";

interface CategoryComboboxProps {
  categories: Category[];
  value: string | null;
  onChange: (categoryId: string | null) => void;
  placeholder?: string;
  showBadge?: boolean;
  align?: "start" | "center" | "end";
  width?: string;
  buttonWidth?: string;
}

export function CategoryCombobox({
  categories,
  value,
  onChange,
  placeholder = "Sélectionner...",
  showBadge = false,
  align = "start",
  width = "w-[300px]",
  buttonWidth,
}: CategoryComboboxProps) {
  const [open, setOpen] = useState(false);

  // Organize categories by parent
  const { parentCategories, childrenByParent } = useMemo(() => {
    const parents = categories.filter((c) => c.parentId === null);
    const children: Record<string, Category[]> = {};

    categories
      .filter((c) => c.parentId !== null)
      .forEach((child) => {
        if (!children[child.parentId!]) {
          children[child.parentId!] = [];
        }
        children[child.parentId!].push(child);
      });

    return { parentCategories: parents, childrenByParent: children };
  }, [categories]);

  const selectedCategory = categories.find((c) => c.id === value);

  const handleSelect = (categoryId: string | null) => {
    onChange(categoryId);
    setOpen(false);
  };

  // Badge style trigger
  if (showBadge) {
    return (
      <Popover open={open} onOpenChange={setOpen} modal={true}>
        <PopoverTrigger asChild>
          <button className="flex items-center gap-1 hover:opacity-80">
            {selectedCategory ? (
              <Badge
                variant="secondary"
                className="gap-1 cursor-pointer"
                style={{
                  backgroundColor: `${selectedCategory.color}20`,
                  color: selectedCategory.color,
                }}
              >
                <CategoryIcon
                  icon={selectedCategory.icon}
                  color={selectedCategory.color}
                  size={12}
                />
                {selectedCategory.name}
              </Badge>
            ) : (
              <Badge
                variant="outline"
                className="text-muted-foreground cursor-pointer"
              >
                Non catégorisé
              </Badge>
            )}
          </button>
        </PopoverTrigger>
        <PopoverContent
          className={cn(width, "p-0")}
          align={align}
          onOpenAutoFocus={(e) => e.preventDefault()}
        >
          <Command value={value || ""}>
            <CommandInput placeholder="Rechercher une catégorie..." />
            <CommandList className="max-h-[250px]">
              <CommandEmpty>Aucune catégorie trouvée.</CommandEmpty>
              <CommandGroup>
                <CommandItem
                  value="__none__"
                  onSelect={() => handleSelect(null)}
                >
                  <X className="h-4 w-4 text-muted-foreground" />
                  <span className="text-muted-foreground">
                    Aucune catégorie
                  </span>
                  {value === null && (
                    <Check className="ml-auto h-4 w-4" />
                  )}
                </CommandItem>
              </CommandGroup>
              <CommandGroup>
                {parentCategories.map((parent) => (
                  <div key={parent.id}>
                    <CommandItem
                      value={parent.id}
                      onSelect={() => handleSelect(parent.id)}
                    >
                      <CategoryIcon
                        icon={parent.icon}
                        color={parent.color}
                        size={16}
                      />
                      <span className="font-medium">{parent.name}</span>
                      {value === parent.id && (
                        <Check className="ml-auto h-4 w-4" />
                      )}
                    </CommandItem>
                    {childrenByParent[parent.id]?.map((child) => (
                      <CommandItem
                        key={child.id}
                        value={child.id}
                        onSelect={() => handleSelect(child.id)}
                        className="pl-8"
                      >
                        <CategoryIcon
                          icon={child.icon}
                          color={child.color}
                          size={16}
                        />
                        <span>{child.name}</span>
                        {value === child.id && (
                          <Check className="ml-auto h-4 w-4" />
                        )}
                      </CommandItem>
                    ))}
                  </div>
                ))}
              </CommandGroup>
            </CommandList>
          </Command>
        </PopoverContent>
      </Popover>
    );
  }

  // Button style trigger (default)
  return (
    <Popover open={open} onOpenChange={setOpen} modal={true}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className={cn("justify-between", buttonWidth || "w-full")}
        >
          {selectedCategory ? (
            <div className="flex items-center gap-2">
              <CategoryIcon
                icon={selectedCategory.icon}
                color={selectedCategory.color}
                size={16}
              />
              <span>{selectedCategory.name}</span>
            </div>
          ) : (
            <span className="text-muted-foreground">{placeholder}</span>
          )}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className={cn(width, "p-0")}
        align={align}
        onOpenAutoFocus={(e) => e.preventDefault()}
      >
        <Command value={value || ""}>
          <CommandInput placeholder="Rechercher une catégorie..." />
          <CommandList className="max-h-[250px]">
            <CommandEmpty>Aucune catégorie trouvée.</CommandEmpty>
            <CommandGroup>
              <CommandItem value="__none__" onSelect={() => handleSelect(null)}>
                <X className="h-4 w-4 text-muted-foreground" />
                <span className="text-muted-foreground">Aucune catégorie</span>
                {value === null && (
                  <Check className="ml-auto h-4 w-4" />
                )}
              </CommandItem>
            </CommandGroup>
            <CommandGroup>
              {parentCategories.map((parent) => (
                <div key={parent.id}>
                  <CommandItem
                    value={parent.id}
                    onSelect={() => handleSelect(parent.id)}
                  >
                    <CategoryIcon
                      icon={parent.icon}
                      color={parent.color}
                      size={16}
                    />
                    <span className="font-medium">{parent.name}</span>
                    {value === parent.id && (
                      <Check className="ml-auto h-4 w-4" />
                    )}
                  </CommandItem>
                  {childrenByParent[parent.id]?.map((child) => (
                    <CommandItem
                      key={child.id}
                      value={child.id}
                      onSelect={() => handleSelect(child.id)}
                      className="pl-8"
                    >
                      <CategoryIcon
                        icon={child.icon}
                        color={child.color}
                        size={16}
                      />
                      <span>{child.name}</span>
                      {value === child.id && (
                        <Check className="ml-auto h-4 w-4" />
                      )}
                    </CommandItem>
                  ))}
                </div>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}
