"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { splitPayment } from "@/app/admin/projects/project-actions";

interface Props {
  paymentId: string;
  projectId: string;
  currentAmount: number;
}

export function SplitPaymentForm({ paymentId, projectId, currentAmount }: Props) {
  const [open, setOpen] = useState(false);
  const [firstAmount, setFirstAmount] = useState("");
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  const first = parseFloat(firstAmount) || 0;
  const second = parseFloat((currentAmount - first).toFixed(2));
  const isValid = first > 0 && first < currentAmount;

  function handleOpen() {
    setFirstAmount((currentAmount / 2).toFixed(2));
    setOpen(true);
  }

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!isValid) return;
    startTransition(async () => {
      await splitPayment(paymentId, projectId, first.toFixed(2));
      setOpen(false);
      setFirstAmount("");
      router.refresh();
    });
  }

  if (!open) {
    return (
      <Button type="button" size="sm" variant="ghost" className="text-xs h-7 px-2" onClick={handleOpen}>
        Dividi
      </Button>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="mt-3 pt-3 border-t border-gray-100">
      <p className="text-xs text-gray-500 mb-2">Imposta il primo importo — il resto diventa la seconda rata:</p>
      <div className="flex items-start gap-2">
        <div className="flex-1 space-y-1">
          <Input
            type="number"
            step="0.01"
            min="0.01"
            max={(currentAmount - 0.01).toFixed(2)}
            value={firstAmount}
            onChange={(e) => setFirstAmount(e.target.value)}
            className="h-8 text-sm"
            required
          />
          {isValid && (
            <p className="text-xs text-[#71717a]">
              Rata 1: € {first.toLocaleString("it-IT", { minimumFractionDigits: 2 })} &nbsp;|&nbsp;
              Rata 2: € {second.toLocaleString("it-IT", { minimumFractionDigits: 2 })}
            </p>
          )}
          {firstAmount && !isValid && (
            <p className="text-xs text-red-500">
              Inserisci un importo tra 0,01 e {(currentAmount - 0.01).toLocaleString("it-IT", { minimumFractionDigits: 2 })}
            </p>
          )}
        </div>
        <Button type="submit" size="sm" className="h-8" disabled={!isValid || isPending}>
          {isPending ? "…" : "Conferma"}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="ghost"
          className="h-8"
          onClick={() => { setOpen(false); setFirstAmount(""); }}
        >
          Annulla
        </Button>
      </div>
    </form>
  );
}