import React, { useEffect, useState } from 'react';
import { TamaguiProvider, Stack, Text, Button, ScrollView } from 'tamagui';

const PendingFriendRequestsScreen = () => {
  const [pendingRequests, setPendingRequests] = useState([]);
  const [error, setError] = useState('');

  const fetchPendingRequests = async () => {
    try {
      const yourAuthToken = localStorage.getItem("jwtToken");
      const response = await fetch("http://localhost:4000/friend-requests/pending", {
        method: "GET",
        headers: {
          "Authorization": `Bearer ${yourAuthToken}`,
        },
      });

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(errorText || "Failed to fetch friend requests");
      }

      const requests = await response.json();
      setPendingRequests(requests);
    } catch (err) {
      console.error("Error fetching pending friend requests:", err);
      setError("Failed to load friend requests.");
    }
  };

  const handleResponse = async (requestId, response) => {
    try {
      const yourAuthToken = localStorage.getItem("jwtToken");
      const res = await fetch("http://localhost:4000/friend-request/respond", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${yourAuthToken}`,
        },
        body: JSON.stringify({ requestId, response }),
      });

      if (!res.ok) {
        const errorText = await res.text();
        throw new Error(errorText || "Failed to process friend request");
      }

      // Update the UI after a successful response
      setPendingRequests((prevRequests) =>
        prevRequests.filter((request) => request.id !== requestId)
      );
    } catch (err) {
      console.error(`Error ${response}ing friend request:`, err);
      alert(`Failed to ${response} friend request.`);
    }
  };

  useEffect(() => {
    fetchPendingRequests();
  }, []);

  return (
    <TamaguiProvider>
      <Stack f={1} justifyContent="center" alignItems="center" padding="$4" space="$4">
        <Text fontSize="$6" fontWeight="bold">
          Pending Friend Requests
        </Text>

        {error ? (
          <Text color="red" fontSize="$2">
            {error}
          </Text>
        ) : (
          <ScrollView contentContainerStyle={{ padding: 10 }}>
            {pendingRequests.map((request) => (
              <Stack key={request.id} padding="$3" borderWidth={1} borderRadius="$4" borderColor="$borderColor" space="$2">
                <Text fontSize="$4">{request.sender.username}</Text>
                <Button
                  backgroundColor="green"
                  color="white"
                  onPress={() => handleResponse(request.id, "accepted")}
                >
                  Accept
                </Button>
                <Button
                  backgroundColor="red"
                  color="white"
                  onPress={() => handleResponse(request.id, "rejected")}
                >
                  Reject
                </Button>
              </Stack>
            ))}
          </ScrollView>
        )}
      </Stack>
    </TamaguiProvider>
  );
};

export default PendingFriendRequestsScreen;
