"use client";

import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Check, X } from "lucide-react";
import { useState } from "react";

interface PriceOverrideInputProps {
  value: string;
  onChange: (value: string) => void;
  calculatedTotal?: number;
}

export function PriceOverrideInput({ value, onChange, calculatedTotal }: PriceOverrideInputProps) {
  const [isTouched, setIsTouched] = useState(false);

  const numValue = parseFloat(value) || 0;
  const matches = calculatedTotal !== undefined && Math.abs(numValue - calculatedTotal) < 0.01;

  return (
    <div className="space-y-2">
      <Label htmlFor="total">Totale preventivo*</Label>
      <div className="relative">
        <Input
          id="total"
          type="number"
          step="0.01"
          min="0"
          placeholder="0.00"
          value={value}
          onChange={(e) => onChange(e.target.value)}
          onBlur={() => setIsTouched(true)}
          className="pr-10"
          required
        />
        {isTouched && value && (
          <div className="absolute right-3 top-1/2 -translate-y-1/2">
            {matches ? (
              <Check size={18} className="text-green-500" />
            ) : (
              <X size={18} className="text-red-500" />
            )}
          </div>
        )}
      </div>

      {calculatedTotal !== undefined && (
        <p className="text-xs text-gray-500">
          Prezzo calcolato: €{calculatedTotal.toLocaleString("it-IT", {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })}
        </p>
      )}

      {isTouched && value && !matches && (
        <p className="text-xs text-yellow-600">
          Attenzione: il valore inserito non corrisponde al totale calcolato (server verificherà)
        </p>
      )}
    </div>
  );
}
