import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, Button, ScrollView } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import axios from 'axios';
import { useTailwind } from 'tailwind-rn';

function SwitDetailScreen({ route, navigation, userId }) {
  const [swit, setSwit] = useState(null);
  const [newComment, setNewComment] = useState('');
  const { switId } = route.params;
  const [username, setUsername] = useState('');
  const [errorMessage, setErrorMessage] = useState(null); // Add this state for error message
  const [uId, setUId] = useState(''); // Add this state for error message

  const tailwind = useTailwind();

  async function fetchUserData() {
    try {
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')
      const userId = await AsyncStorage.getItem('userID');
      setUId(userId);
      const token = await AsyncStorage.getItem('token');  
      const response = await fetch(`${apiUrl}/api/v1/app/user/data/${userId}`, {
        headers: { 'Authorization': token },
      });
  
      if (!response.ok) {
        throw new Error(`Failed to fetch user data: ${response.status} ${await response.text()}`);
      }
  
      const user = await response.json();
      setUsername(user.username);
    } catch (error) {
      console.error('Error:', error);
      setErrorMessage(error.message);
    }
  }

  const fetchSwit = async () => {
    const token = await AsyncStorage.getItem('token');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')

    const response = await axios.get(`${apiUrl}/api/v1/app/swit/swits/${switId}`, {
      headers: { 'Authorization': token },
    });
    console.warn(response.data)
    setSwit(response.data);
    console.warn(swit.comments)
  };

  const postComment = async () => {
    const token = await AsyncStorage.getItem('token');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')

    await axios.post(`${apiUrl}/api/v1/app/swit/swits/${switId}/comments`, {
      text: newComment,
      username: username
    }, {
      headers: { 'Authorization': token },
    });
    setNewComment('');
    fetchSwit();
  };

  const likeComment = async (commentId) => {
    const token = await AsyncStorage.getItem('token');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')

    await axios.post(`${apiUrl}/api/v1/app/swit/swits/${switId}/comments/${commentId}/like`, {}, {
      headers: { 'Authorization': token },
    });
    fetchSwit();
  };
  
  const unlikeComment = async (commentId) => {
    const token = await AsyncStorage.getItem('token');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')
    await axios.post(`${apiUrl}/api/v1/app/swit/swits/${switId}/comments/${commentId}/unlike`, {}, {
      headers: { 'Authorization': token },
    });
    fetchSwit();
  };

  const deleteComment = async (commentId) => {
    const token = await AsyncStorage.getItem('token');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')

    await axios.delete(`${apiUrl}/api/v1/app/swit/swits/${switId}/comments/${commentId}`, {
      headers: { 'Authorization': token },
    });
    fetchSwit();
  };
  
  

  async function deleteSwit() {
    try {
      const token = await AsyncStorage.getItem('token');
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')

      const response = await fetch(`${apiUrl}/api/v1/app/swit/swits/${switId}`, {
        method: 'DELETE',
        headers: { 'Authorization': token },
      });
  
      if (!response.ok) {
        throw new Error(`Failed to delete swit: ${response.status} ${await response.text()}`);
      }
  
      // Redirect to the home screen after deleting
      navigation.goBack();
    } catch (error) {
      console.error('Error:', error);
      setErrorMessage(error.message);
    }
  }
  

  useEffect(() => {
    fetchSwit();
    fetchUserData();
  }, []);

  if (!swit) {
    return <Text>Loading...</Text>;
  }

  return (
    <View>
      {errorMessage ? <Text style={tailwind('text-red-500 mb-2 text-center')}>{errorMessage}</Text> : null}
      <Text>{swit.text}</Text>
      <ScrollView>
  {swit.comments.map((comment, index) => (
    <>
      <Text key={index}>{comment.username}: {comment.text}</Text>
      <Button title="Like" onPress={() => likeComment(comment._id)} />
      <Button title="Unlike" onPress={() => unlikeComment(comment._id)} />
      {uId === comment.user && <Button title="Delete" onPress={() => deleteComment(comment._id)} />}

    </>
  ))}
</ScrollView>

      <TextInput
        value={newComment}
        onChangeText={text => setNewComment(text)}
        placeholder="Write a comment..."
      />
      <Button title="Post comment" onPress={postComment} />
      {swit.user === userId && <Button title="Delete" onPress={deleteSwit} />}
    </View>
  );
}

export default SwitDetailScreen;
