import { useState, useEffect } from "react";

interface PriceSelectionProps {
  selectedPrice: number | null;
  onSelect: (price: number) => void;
}

export function PriceSelection({ selectedPrice, onSelect }: PriceSelectionProps) {
  const presets = [0.05, 0.1, 0.2, 0.5, 1.0];
  const [inputValue, setInputValue] = useState<string>("");
  const MIN_AMOUNT = 0.05;

  useEffect(() => {
    if (selectedPrice !== null) {
      setInputValue(selectedPrice.toString());
    }
  }, [selectedPrice]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setInputValue(value);
    const parsed = parseFloat(value);
    if (!isNaN(parsed) && parsed >= MIN_AMOUNT) {
      onSelect(parsed);
    }
  };

  const handlePresetClick = (value: number) => {
    onSelect(value);
    setInputValue(value.toString());
  };

  return (
    <div className="mb-6 space-y-2">
      <label className="block text-sm text-gray-300 font-mono mb-1">Select Currency</label>

      <select
        className="bg-[rgb(10,10,10)] border border-gray-700 text-[rgb(248,144,22)] font-mono px-2 py-1 rounded-lg w-full cursor-pointer"
      >
        <option>SOL</option>
      </select>
      <label className="block text-sm text-gray-300 font-mono mb-1">Enter Price (SOL)</label>
      <div className="flex items-center gap-2">
        <input
          type="number"
          step="0.01"
          value={inputValue}
          onChange={handleInputChange}
          className="bg-[rgb(10,10,10)] border border-gray-700 text-[rgb(248,144,22)] font-mono px-2 py-1 rounded-lg flex-1 appearance-none no-spinner"
          placeholder="e.g. 0.5"
        />
      </div>
      <div className="flex items-center gap-2">

        <div className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-[rgb(248,144,22)]">
          <svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </div>
      </div>

      <div className="flex gap-2 mt-2">
        {presets.map((price) => (
          <button
            key={price}
            onClick={() => handlePresetClick(price)}
            className={`px-3 py-1 rounded font-mono text-sm border transition 
              ${selectedPrice === price
                ? "bg-[rgb(248,144,22)] text-black font-bold border-white scale-105"
                : "bg-[rgb(10,10,10)] text-white border-gray-600 hover:bg-[rgb(30,30,30)] hover:scale-105"
              }`}
          >
            {price}
          </button>
        ))}
      </div>
    </div>
  );
}
