"use client";
import { useCurrency } from "@/hooks/useCurrency";
import { useTranslations } from "@/providers/TranslationProviders";
import { MinusIcon, PlusIcon } from "phosphor-react-native";
import { useEffect, useRef, useState } from "react";
import { Pressable, Text, TextInput, View } from "react-native";

interface QuantitySelectorProps {
  pricePerItem: number;
  quantity: number;
  onQuantityChange: (newQuantity: number) => void;
  min?: number;
  max?: number;
  focused?: boolean;
  showTotal?: boolean;
}

export default function QuantitySelector({
  pricePerItem,
  quantity = 1,
  onQuantityChange,
  min = 1,
  max = 1000000000000,
  focused = false,
  showTotal = true,
}: QuantitySelectorProps) {
  const { currency } = useCurrency();
  const [inputValue, setInputValue] = useState<string>(quantity.toString());
  const { tran, translateNumber } = useTranslations();

  // Sync input value with parent quantity
  useEffect(() => {
    setInputValue(quantity.toString());
  }, [quantity]);

  const handleIncrement = () => {
    if (quantity < max) onQuantityChange(quantity + 1);
  };

  const handleDecrement = () => {
    if (quantity > min) onQuantityChange(quantity - 1);
  };

  const handleInputChange = (value: string) => {
    // Allow empty value (erasable)
    if (value === "") {
      setInputValue("");
      return;
    }

    // Only allow numbers
    if (!/^\d+$/.test(value)) {
      return; // Prevent non-numeric input
    }

    const numValue = Number(value);

    // Prevent values greater than max
    if (numValue > max) {
      setInputValue(max.toString());
      onQuantityChange(max);
      return;
    }

    // Prevent values smaller than min (unless empty)
    if (numValue < min) {
      setInputValue(min.toString());
      onQuantityChange(min);
      return;
    }

    // Update for valid values
    setInputValue(value);
    onQuantityChange(numValue);
  };

  const handleBlur = () => {
    // If input is empty or invalid, reset to current quantity
    if (inputValue === "" || isNaN(Number(inputValue))) {
      setInputValue(quantity.toString());
    } else {
      // Ensure the value is within bounds on blur
      const numValue = Number(inputValue);
      const clampedValue = Math.max(min, Math.min(max, numValue));
      if (clampedValue !== numValue) {
        setInputValue(clampedValue.toString());
        onQuantityChange(clampedValue);
      }
    }
  };

  return (
    <View className="py-4">
      <View className="flex-row justify-center items-center gap-2">
        {/* Decrement Button */}
        <Pressable
          onPress={handleDecrement}
          className="size-12 border border-slate-200 rounded-lg flex items-center justify-center disabled:opacity-50 shrink-0"
          disabled={quantity <= min}
        >
          <MinusIcon />
        </Pressable>

        {/* Number Input */}
        <TextInput
          value={inputValue}
          onChangeText={handleInputChange}
          keyboardType="numeric"
          className="flex-1 text-center border border-slate-200 rounded-xl h-12"
        />

        {/* Increment Button */}
        <Pressable
          onPress={handleIncrement}
          className="size-12 border border-slate-200 rounded-lg flex items-center justify-center disabled:opacity-50 shrink-0"
          disabled={quantity >= max}
        >
          <PlusIcon />
        </Pressable>
      </View>

      {/* Estimated Total */}
      {showTotal && (
        <Text className="mt-2 text-sm font-manrope-medium pt-2 text-center">
          {tran("Est. total")}:{" "}
          <Text className="text-xl font-manrope-bold ml-1">
            {currency.symbol}
            {translateNumber(quantity * pricePerItem)}
          </Text>
        </Text>
      )}
    </View>
  );
}
