"use client";
import { useEffect, useState } from "react";
import { api } from "@/lib/api";
import DepositChooser from "@/components/DepositChooser";

export default function DepositPage({ params }: { params: { id: string } }) {
  const [booking, setBooking] = useState<any>(null);
  const [amount, setAmount] = useState<number>(0);
  const [method, setMethod] = useState<"ORANGE_MONEY"|"MYZAKA"|"CARD">("ORANGE_MONEY");
  const [payerPhone, setPayerPhone] = useState("+267");
  const [msg, setMsg] = useState<string>("");

  async function load() {
    const b = await api<any>(`/bookings/${params.id}`, { auth: true });
    setBooking(b);
    setAmount(Number(b.recommendedDepositAmount ?? 0));
  }

  useEffect(() => { load(); }, [params.id]);

  async function pay() {
    setMsg("Initiating payment...");
    const res = await api<any>("/payments/deposit/initiate", {
      method: "POST",
      body: JSON.stringify({ bookingId: params.id, amount, method, payerPhone }),
      auth: true,
    });
    setMsg(`Payment started: intent ${res.intentId}. Simulate webhook to confirm.`);
  }

  if (!booking) return <div>Loading booking…</div>;

  const price = Number(booking.priceAmount);
  const recommended = Number(booking.recommendedDepositAmount);
  const min = Number(booking.minDepositAmount);
  const max = Number(booking.maxDepositAmount);

  return (
    <div className="max-w-xl grid gap-3">
      <h1 className="text-xl font-semibold">Pay Deposit</h1>

      <div className="border rounded p-3 text-sm">
        <div><b>Booking:</b> {booking.id}</div>
        <div><b>Status:</b> {booking.status}</div>
        <div><b>Price:</b> P{price.toFixed(2)}</div>
        <div><b>Deadline:</b> {new Date(booking.depositDeadlineAt).toLocaleString()}</div>
      </div>

      <DepositChooser price={price} recommended={recommended} min={min} max={max} onChange={setAmount} />

      <div className="border rounded p-3 grid gap-2">
        <label className="text-sm">Payment Method</label>
        <select className="border rounded p-2" value={method} onChange={(e)=>setMethod(e.target.value as any)}>
          <option value="ORANGE_MONEY">Orange Money</option>
          <option value="MYZAKA">MyZaka</option>
          <option value="CARD">Card</option>
        </select>

        <label className="text-sm">Payer Phone (for mobile money)</label>
        <input className="border rounded p-2" value={payerPhone} onChange={(e)=>setPayerPhone(e.target.value)} />

        <button className="bg-black text-white rounded p-2" onClick={pay}>Pay Deposit</button>
        {msg && <div className="text-sm opacity-80">{msg}</div>}
      </div>
    </div>
  );
}
