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

export default function RequestDetail() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const [data, setData] = useState<any>(null);
  const [err, setErr] = useState<string | null>(null);
  const router = useRouter();

  async function load() {
    try {
      const res = await api<any>(`/booking-requests/${id}`, { auth: true });
      setData(res);
      setErr(null);
    } catch (e: any) {
      setErr(e.message);
    }
  }

  useEffect(() => {
    load();
    const t = setInterval(load, 2500);
    return () => clearInterval(t);
  }, [id]);

  if (err) return <View style={{ padding: 16 }}><Text style={{ color: "red" }}>{err}</Text></View>;
  if (!data) return <View style={{ padding: 16 }}><Text>Loading…</Text></View>;

  return (
    <View style={{ padding: 16, gap: 10 }}>
      <Text style={{ fontSize: 18, fontWeight: "700" }}>Request</Text>
      <Text>Status: {data.status}</Text>
      <Text>Offers: {(data.offers ?? []).length}</Text>

      {(data.offers ?? []).map((o: any) => (
        <View key={o.id} style={{ borderWidth: 1, borderRadius: 10, padding: 10 }}>
          <Text>Provider: {o.providerId}</Text>
          <Text>State: {o.state}</Text>
          <Text>Expires: {new Date(o.expiresAt).toLocaleString()}</Text>
        </View>
      ))}

      {data.booking && (
        <Pressable
          style={{ backgroundColor: "black", padding: 12, borderRadius: 10 }}
          onPress={() => router.push(`/(client)/booking/${data.booking.id}/deposit`)}
        >
          <Text style={{ color: "white", textAlign: "center" }}>Pay Deposit</Text>
        </Pressable>
      )}
    </View>
  );
}
