import React, { useContext, useEffect, useState } from "react";
import { Image, View, StyleSheet, Text, TouchableOpacity } from "react-native";
import { Drawer } from "expo-router/drawer";
import {
  DrawerContentScrollView,
  DrawerItemList,
} from "@react-navigation/drawer";
import { LinearGradient } from "expo-linear-gradient";
import { Ionicons, MaterialIcons, FontAwesome } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/native";
import UserContext from "../../contexts/UserContext";
import axios from "axios";

const CustomDrawerContent = (props) => {
  const { user } = useContext(UserContext);
  const navigation = useNavigation();
  const { setUser } = useContext(UserContext);
  const [profileImage, setProfileImage] = useState(null);

  const handleLogout = () => {
    setUser(null);
    navigation.navigate("index");
  };

  useEffect(() => {
    const fetchProfileImage = async () => {
      try {
        const response = await axios.post(
          "https://kiamabackend.mathenoid.com/api/profileImage",
          { username: user }
        );
        if (response.data.success && response.data.profileImageUrl) {
          setProfileImage(
            "https://kiamabackend.mathenoid.com" + response.data.profileImageUrl
          );
        }
      } catch (error) {
        console.error("Error fetching profile image:", error);
      }
    };

    if (user) {
      fetchProfileImage();
    }
  }, [user]);

  return (
    <LinearGradient
      colors={["#fff", "#69c37b", "#69c37b"]}
      style={styles.gradientContainer}
    >
      <DrawerContentScrollView {...props} showsVerticalScrollIndicator={false}>
        <View style={styles.imageContainer}>
          <Image source={{ uri: profileImage }} style={styles.topImage} />
          <Text style={styles.titleText}>Welcome {user}</Text>
        </View>
        <DrawerItemList
          {...props}
          labelStyle={styles.drawerLabel}
          activeTintColor="#69c37b"
          inactiveTintColor="#333"
        />
        <TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
          <Text style={styles.logoutText}>Logout</Text>
        </TouchableOpacity>
      </DrawerContentScrollView>
    </LinearGradient>
  );
};

export default function DrawerLayout() {
  const { userRole } = useContext(UserContext);

  return (
    <Drawer
      drawerContent={(props) => <CustomDrawerContent {...props} />}
      screenOptions={{
        headerShown: true,
        headerStyle: {
          backgroundColor: "#69c37b",
        },
        headerTintColor: "#fff",
        headerTitleStyle: {
          fontSize: 20,
          fontFamily: "outfit",
        },
      }}
    >
      <Drawer.Screen
        name="index"
        options={{
          drawerLabel: "Home",
          title: "Dashboard",
          drawerIcon: ({ color, size }) => (
            <Ionicons name="home-outline" color={color} size={size} />
          ),
          drawerLabelStyle: styles.drawerLabelStyle,
        }}
      />
      <Drawer.Screen
        name="Profile"
        options={{
          drawerLabel: "Profile",
          title: "User Profile",
          drawerIcon: ({ color, size }) => (
            <Ionicons name="person-outline" color={color} size={size} />
          ),
          drawerLabelStyle: styles.drawerLabelStyle,
        }}
      />
      <Drawer.Screen
        name="AddSong"
        options={{
          drawerLabel: "Add Song",
          title: "Add Song",
          drawerIcon: ({ color, size }) => (
            <Ionicons name="add-circle-outline" color={color} size={size} />
          ),
          drawerLabelStyle: styles.drawerLabelStyle,
        }}
      />
      <Drawer.Screen
        name="Songs"
        options={{
          drawerLabel: "Songs",
          title: "Songs",
          drawerIcon: ({ color, size }) => (
            <Ionicons name="musical-notes-outline" color={color} size={size} />
          ),
          drawerLabelStyle: styles.drawerLabelStyle,
        }}
      />

      <Drawer.Screen
        name="ManageMembers"
        options={{
          drawerLabel: "Manage Members",
          title: "Manage Members",
          drawerIcon: ({ color, size }) => (
            <Ionicons name="people" color={color} size={size} />
          ),
          drawerLabelStyle: styles.drawerLabelStyle,
          drawerItemStyle: { display: userRole === "admin" ? "flex" : "none" },
        }}
      />
    </Drawer>
  );
}

const styles = StyleSheet.create({
  gradientContainer: {
    flex: 1,
    height: "100%",
  },
  imageContainer: {
    alignItems: "center",
    padding: 20,
  },
  topImage: {
    width: 100,
    height: 100,
    borderRadius: 100,
  },
  titleText: {
    fontSize: 22,
    fontFamily: "outfit-medium",
    color: "#333",
    marginTop: 10,
  },
  drawerLabel: {
    fontSize: 18,
    fontFamily: "outfit",
    color: "#333",
  },
  logoutButton: {
    elevation: 1,
    padding: 10,
    backgroundColor: "#69c37b",
    alignItems: "center",
    borderRadius: 20,
    width: "60%",
    marginTop: 10,
    marginBottom: 20,
    marginLeft: 20,
    fontFamily: "outfit-bold",
  },
  logoutText: {
    color: "#333",
    fontSize: 18,
    fontWeight: "bold",
  },
  drawerLabelStyle: {
    fontSize: 15,
    fontFamily: "outfit",
  },
});
