import React, { useEffect, useState } from 'react';
import { View, StyleSheet, TextInput, Text, ScrollView, FlatList, Pressable } from 'react-native';
import BootstrapModal from '@/components/BootstrapModal';
import { Appbar, Menu, Avatar, useTheme, Button } from 'react-native-paper';
import Icon from 'react-native-vector-icons/MaterialIcons';
import dpuser from "@/assets/images/userdp.png";

/** Some Temp Bullshits */
const dummyUserDataName = [
  {
    id: 1,
    name: "AzmanHadi@PSK",
    user_img: "https://t4.ftcdn.net/jpg/03/64/21/11/360_F_364211147_1qgLVxv1Tcq0Ohz3FawUfrtONzz8nq3e.jpg"
  },
  {
    id: 2,
    name: "NorMelati@PSK",
    user_img: "https://www.shutterstock.com/image-photo/head-shot-portrait-millennial-beautiful-260nw-1893951241.jpg"
  },
  {
    id: 3,
    name: "RazuanKhan@PSK",
    user_img: "https://plus.unsplash.com/premium_photo-1689568126014-06fea9d5d341?fm=jpg&q=60&w=3000&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxzZWFyY2h8MXx8cHJvZmlsZXxlbnwwfHwwfHx8MA%3D%3D"
  }
]

const Notification = () => {
  const { colors, fonts } = useTheme();
  const [menuVisible, setMenuVisible] = useState(false);
  const [inputContent, setInputContent] = useState("");
  const [pickedUser, setPickedUser] = useState(null);
  const [userNameSearch, setUserNameSearch] = useState('');
  const [visible, setVisible] = useState(false);
  const [nameSuggestion, setNameSuggestion] = useState([])


  const preTextClick = (pretext) => {
    setInputContent(pretext)
  }

  const handleOnSearchUser = (e) => {

    const value = e.target.value;
    setUserNameSearch(value)

  }

  useEffect(() => {

    if (userNameSearch.length > 0) {

      let filteredData = dummyUserDataName.filter(
        ({ name }) => name.toLowerCase().includes(userNameSearch?.toLowerCase())
      )
      setNameSuggestion(filteredData);
    } else {
      setNameSuggestion([]);
    }

  }, [userNameSearch])

  const renderUser = ({ item }) => (
    <Pressable onPress={() => { 
      setPickedUser(item);
      setNameSuggestion([]);
      setUserNameSearch("");
     }}>
      <View style={styles.nameItem} >
        <Avatar.Image size={25} source={item.user_img}></Avatar.Image>
        <Text style={styles.nameText}>{item.name}</Text>
      </View>
    </Pressable>
  );

  const renderUserBadge = (pickedUser) => {
    return (
      <View style={{ flexDirection: "row", backgroundColor: "#396868", padding: 5, borderRadius: 20, paddingRight: 10 }}>
        <Avatar.Image size={35} source={pickedUser?.user_img}></Avatar.Image>
        <Text style={{ marginTop: "auto", marginBottom: "auto", marginLeft: 10, fontWeight: "500", color: "#FFF", marginRight: 5 }}>{pickedUser?.name}</Text>
        <Pressable onPress={()=>{setPickedUser(null)}}>
          <Icon name="cancel" size={25} color={"#FFF"} style={{ marginTop: "auto", marginBottom: "auto" }} />
        </Pressable>
      </View>
    )
  }

  return (
    <View style={[styles.container, { backgroundColor: colors.background }]}>

      <BootstrapModal visible={visible} setVisible={setVisible} />

      <Appbar.Header>

        <Avatar.Image size={50} source={dpuser}></Avatar.Image>

        <View style={styles.titleContainer}>
          <Appbar.Content title="Send Notification" titleStyle={[fonts.titleLarge, styles.title]} />
        </View>

        {/* Menu Component */}
        <Menu
          visible={menuVisible}
          onDismiss={() => setMenuVisible(false)}
          anchor={
            <Appbar.Action icon="dots-vertical" onPress={() => setMenuVisible(true)} />
          }
        >
          <Menu.Item onPress={() => console.log('Profile Clicked')} title="Profile" />
          <Menu.Item onPress={() => console.log('Settings Clicked')} title="Settings" />
          <Menu.Item onPress={() => console.log('Logout Clicked')} title="Logout" />
        </Menu>
      </Appbar.Header>

      <View style={{ flex: 1, marginTop: 20 }}>
        <View style={{ flexDirection: "row", gap: 20, marginBottom: 20 }}>
          <Text style={[fonts.titleMedium, { fontWeight: "bold", marginTop: "auto", marginBottom: "auto" }]}>To :</Text>

          {pickedUser ? renderUserBadge(pickedUser) : <View style={{ flex: 1 }}>
            <TextInput
              value={userNameSearch}
              onChange={(e) => {
                handleOnSearchUser(e)
              }}
              style={styles.userSearchInput}
            />
            {(nameSuggestion.length > 0) && <View style={styles.nameListContainer}>
              <FlatList
                data={nameSuggestion}
                renderItem={renderUser}
                keyExtractor={(item) => `${item?.id}`}
                contentContainerStyle={styles.listContent}
              />
            </View>}
          </View>}
        </View>
        <TextInput
          style={styles.textArea}
          value={inputContent}
          onChangeText={setInputContent}
          multiline={true} // Enables multi-line input
          numberOfLines={8} // Sets an initial number of visible lines
        />
        <Text style={[fonts.titleLarge, { fontWeight: "bold", marginBottom: 20 }]}>Select Pretext</Text>
        <View style={{ flex: 1 }}>
          {[
            "Request to Work From Home",
            "Request for late Check In",
            "Request for early Check Out",
            "Notify for Annual Leave",
            "Notify for Emergency Leave"
          ].map(text => <Text onPress={() => { preTextClick(text) }} style={[fonts.titleMedium, { marginBottom: 20, fontWeight: "bold", color: colors.secondary }]} >{text}</Text>)}
        </View>
      </View>

    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    width: '100%',
  },
  textArea: {
    height: 220,
    borderColor: "#ccc",
    borderWidth: 1,
    padding: 10,
    borderRadius: 8,
    textAlignVertical: "top", // Makes text start from the top-left
    backgroundColor: "#fff",
    marginBottom: 20
  },
  badge: {
    backgroundColor: "#BB5C3F",
    color: "#FFF",
    borderRadius: 100,
    paddingVertical: 4,
    paddingHorizontal: 6,
    fontSize: 10,
    fontWeight: "400",
    verticalAlign: "middle",
    marginStart: 5
  },
  userSearchInput: {
    flex: 1,
    paddingHorizontal: 20,
    borderBottomColor: "rgba(0,0,0,0.2)",
    borderBottomWidth: 1,
    marginEnd: 20
  },
  nameListContainer: {
    position: "absolute",
    top: 25,
    left: 0,
    backgroundColor: "#FFF",
    width: "100%",
    paddingHorizontal: 10,
    borderWidth: 2,
    borderColor: "#CFCFCF"
  },
  listContent: {
    paddingBottom: 10,
  },
  nameItem: {
    paddingVertical: 6,
    flex: 1,
    flexDirection: "row"
  },
  nameText: {
    marginLeft: 10,
    fontSize: 16,
    color: '#555',
  },
  titleContainer: {
    flex: 1,
    alignItems: 'center',
  },
  title: {
    fontWeight: 'bold',
  },
  icon: {
    padding: 10,
    position: "absolute",
    right: 10,
    color: "#D9D9D9"
  }
});

export default Notification;
