import React, { useEffect, useState } from 'react';
import { Image, StyleSheet, Alert } from 'react-native';
import { ThemedView } from '@/components/ThemedView';
import { ThemedText } from '@/components/ThemedText';
import { getUserData } from '@/components/services/securestorage/UserData';
import Button from '@/components/buttons/Button';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';

type Partner = {
  id: number;
  appleId: string;
  appleEmail: string;
  fullName: string;
  pfpURL: string;
  pushToken: string;
  createdAt: Date;
};

type Relationship = {
  id: number;
  title: string;
  status: 'pending' | 'accepted' | 'rejected';
  relationshipStartDate: Date;
  createdAt: Date;
};

type RelationshipStatus = {
  relationship: Relationship | null;
  partner: Partner | null;
};

type UserData = {
  fullName: string;
  appleEmail: string;
  appleId: string;
  pfpURL: string;
};

type RelationshipProps = {
  profilePictureUrl: string | null;
};

const Relationships: React.FC<RelationshipProps> = ({ profilePictureUrl }) => {
  const scheme = useColorScheme() ?? 'light';
  const [status, setStatus] = useState<RelationshipStatus | null>(null);
  const [userData, setUserData] = useState<UserData | null>(null);
  const [loading, setLoading] = useState(true);

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

  useEffect(() => {
    if (profilePictureUrl && userData) {
      setUserData(prevData => prevData ? {...prevData, pfpURL: profilePictureUrl} : null);
    }
  }, [profilePictureUrl]);

  const fetchRelationshipStatus = async () => {
    try {
      const userDataFromStorage: UserData = await getUserData();
      if (!userDataFromStorage || !userDataFromStorage.appleId) {
        throw new Error('User data not found');
      }
      setUserData(userDataFromStorage);

      const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/relationships/checkStatusByAppleId?appleId=${userDataFromStorage.appleId}`, {
        headers: {
          'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
        },
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to fetch relationship status');
      }

      const data = await response.json();
      setStatus(data);
    } catch (error) {
      console.error('Error fetching relationship status:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <ThemedText>Loading...</ThemedText>;
  }

  if (!status || !status.relationship?.id) {
    return (
      <ThemedView style={styles.container}>
        <Button width={220} height={60} onPress={() => {/* Implement request functionality */}}>
          <ThemedText
            style={[
              styles.buttonText,
              {color: Colors[scheme].background}
            ]}
          >
            Request Relationship
          </ThemedText>
        </Button>
      </ThemedView>
    );
  }

  return (
    <ThemedView style={styles.container}>
      <ThemedText style={styles.title}>{status?.relationship?.title}</ThemedText>
      <ThemedView style={styles.profileContainer}>
        {userData && (
          <ThemedView style={styles.profileWrapper}>
            <Image
              source={{ uri: `${process.env.EXPO_PUBLIC_URL}${userData.pfpURL}` }}
              style={styles.profilePicture}
            />
            <ThemedText style={styles.name}>{userData.fullName.split(' ')[0]}</ThemedText>
          </ThemedView>
        )}
        {status?.partner && (
          <ThemedView style={styles.profileWrapper}>
            <Image
              source={{ uri: `${process.env.EXPO_PUBLIC_URL}${status.partner.pfpURL}` }}
              style={styles.profilePicture}
            />
            <ThemedText style={styles.name}>{status.partner.fullName.split(' ')[0]}</ThemedText>
          </ThemedView>
        )}
      </ThemedView>
    </ThemedView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
  },
  profileContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 20,
  },
  profileWrapper: {
    alignItems: 'center',
    marginHorizontal: 10,
  },
  profilePicture: {
    width: 100,
    height: 100,
    borderRadius: 50,
    marginBottom: 10,
  },
  name: {
    fontSize: 12,
    fontWeight: 'bold',
  },
  buttonText: {
    fontSize: 16,
  },
});

export default Relationships;
