import { useEffect, useState } from "react";
import { View, Text, TextInput, Pressable } from "react-native";
import { useLocalSearchParams } from "expo-router";
import { api } from "../../../../lib/api";
import DepositChooser from "../../../../components/DepositChooser";

export default function DepositScreen() {
  const { id } = useLocalSearchParams<{ 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("");

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

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

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

  if (!booking) return <View style={{ padding: 16 }}><Text>Loading…</Text></View>;

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

  return (
    <View style={{ padding: 16, gap: 10 }}>
      <Text style={{ fontSize: 18, fontWeight: "700" }}>Pay Deposit</Text>
      <Text>Price: P{price.toFixed(2)}</Text>
      <Text>Deadline: {new Date(booking.depositDeadlineAt).toLocaleString()}</Text>

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

      <TextInput value={method} onChangeText={(t)=>setMethod(t as any)}
        placeholder="ORANGE_MONEY | MYZAKA | CARD"
        style={{ borderWidth: 1, borderRadius: 10, padding: 12 }} />

      <TextInput value={payerPhone} onChangeText={setPayerPhone}
        placeholder="+2677xxxxxxx"
        style={{ borderWidth: 1, borderRadius: 10, padding: 12 }} />

      <Pressable onPress={pay} style={{ backgroundColor: "black", padding: 12, borderRadius: 10 }}>
        <Text style={{ color: "white", textAlign: "center" }}>Pay</Text>
      </Pressable>

      {!!msg && <Text style={{ opacity: 0.8 }}>{msg}</Text>}
    </View>
  );
}
