"use client";
import React from "react";
import { Minus, Plus } from "lucide-react";
import { Button } from "./button";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";
import { useState, useMemo, useRef } from "react";

interface QuantityInputProps {
  value?: number;
  onValueChange?: (value: number) => void;
  min?: number;
  max?: number;
}

export const QuantityInput: React.FC<QuantityInputProps> = ({
  value: controlledValue,
  onValueChange,
  min = 1,
  max = Infinity,
}) => {
  const [internalValue, setInternalValue] = useState(1);
  const value = controlledValue !== undefined ? controlledValue : internalValue;
  const currentValueRef = useRef(value);
  
  // Update the ref when value changes
  React.useEffect(() => {
    currentValueRef.current = value;
  }, [value]);
  
  const setValue = (newValue: number) => {
    currentValueRef.current = newValue;
    if (controlledValue !== undefined && onValueChange) {
      onValueChange(newValue);
    } else {
      setInternalValue(newValue);
    }
  };

  const increaseQuantity = () => {
    const currentValue = currentValueRef.current;
    const newValue = Math.min(currentValue + 1, max);
    setValue(newValue);
  };
  
  const decreaseQuantity = () => {
    const currentValue = currentValueRef.current;
    const newValue = Math.max(currentValue - 1, min);
    setValue(newValue);
  };

  const options = useMemo(() => {
    const baseOptions = Array.from(
      { length: Math.min(10, max) },
      (_, i) => i + 1
    ).filter((n) => n >= min);

    if (value > 10 && value <= max && !baseOptions.includes(value)) {
      baseOptions.push(value);
    }

    return baseOptions.sort((a, b) => a - b);
  }, [min, max, value]);

  return (
    <TooltipProvider delayDuration={0}>
      <div className="flex items-center gap-2">
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              onClick={decreaseQuantity}
              variant="outline"
              size={"icon"}
              aria-label="Anzahl verringern"
              disabled={value <= min}
            >
              <Minus aria-hidden="true" />
            </Button>
          </TooltipTrigger>
          <TooltipContent side="top">Anzahl verringern</TooltipContent>
        </Tooltip>
        <Select
          onValueChange={(val) => setValue(Number(val))}
          value={String(value)}
        >
          <SelectTrigger
            className="w-16 text-center"
            data-testid="quantity-select"
          >
            <SelectValue placeholder={String(value)} />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              <SelectLabel>Anzahl</SelectLabel>
              {options.map((num) => (
                <SelectItem key={num} value={String(num)}>
                  {num}
                </SelectItem>
              ))}
            </SelectGroup>
          </SelectContent>
        </Select>
        <Tooltip>
          <TooltipTrigger asChild>
            <Button
              onClick={increaseQuantity}
              variant="outline"
              size={"icon"}
              aria-label="Anzahl erhöhen"
              disabled={value >= max}
            >
              <Plus aria-hidden="true" />
            </Button>
          </TooltipTrigger>
          <TooltipContent side="top">Anzahl erhöhen</TooltipContent>
        </Tooltip>
        <div className="sr-only" aria-live="polite" role="status">
          Anzahl auf {value} aktualisiert
        </div>
      </div>
    </TooltipProvider>
  );
};
