import { useEffect, useState } from "react";
import { ScrollView, Text, Alert } from "react-native";
import { api } from "../../lib/api";
import OfferCard from "../../components/OfferCard";

export default function ProviderOffers() {
  const [offers, setOffers] = useState<any[]>([]);
  const [err, setErr] = useState<string | null>(null);

  async function load() {
    try {
      const res = await api<any[]>("/provider/offers", { auth: true });
      setOffers(res);
      setErr(null);
    } catch (e: any) {
      setErr(e.message);
    }
  }

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

  async function accept(offerId: string) {
    try {
      const res = await api<any>(`/provider/offers/${offerId}/accept`, {
        method: "POST",
        body: JSON.stringify({ providerNote: "" }),
        auth: true,
      });
      Alert.alert("Accepted", `Booking ${res.bookingId} awaiting deposit`);
      load();
    } catch (e: any) {
      Alert.alert("Error", e.message);
    }
  }

  async function decline(offerId: string) {
    try {
      await api<any>(`/provider/offers/${offerId}/decline`, {
        method: "POST",
        body: JSON.stringify({ reason: "Busy" }),
        auth: true,
      });
      load();
    } catch (e: any) {
      Alert.alert("Error", e.message);
    }
  }

  return (
    <ScrollView contentContainerStyle={{ padding: 16, gap: 10 }}>
      <Text style={{ fontSize: 18, fontWeight: "700" }}>Incoming Offers</Text>
      {err && <Text style={{ color: "red" }}>{err}</Text>}
      {offers.map(o => (
        <OfferCard key={o.id} offer={o} onAccept={()=>accept(o.id)} onDecline={()=>decline(o.id)} />
      ))}
      {!offers.length && <Text style={{ opacity: 0.7 }}>No offers right now.</Text>}
    </ScrollView>
  );
}
