import React from "react";
import {
  View,
  Text,
  ImageBackground,
  TouchableOpacity,
  FlatList,
  ScrollView,
  TouchableWithoutFeedback,
  Keyboard,
  SafeAreaView,
  Image,
  StatusBar, // FEATURE: Import StatusBar để control status bar
  Platform,  // FEATURE: Check platform iOS/Android
} from "react-native";
import HeaderCus from "../home/header";
import R from "../../assets/R";
import I18n from "../../helper/i18/i18n";
import ItemGrid from "./item";
import styles from "./style";
import { useNavigation } from "@react-navigation/native";
import * as SCREENNAME from "../../routers/ScreenNames";

const HomeView = (props) => {
  const {
    menuDataStudy,
    menuDataIndividual,
    menuDataOnlineSer,
    selectedMenuItem,
    searchText,
    userProfile,
    onMenuItemPress,
    onSearchChange,
  } = props;

  // OPTIMIZE: Move icon reference outside render để tránh re-create
  const ArrowRightIcon = R.images.icArrowRight;
  const navigate = useNavigation();

  // PERFORMANCE: Memoized render function
  const renderMenuItem = React.useCallback(({ item }) => {
    return <ItemGrid item={item} onPress={() => onMenuItemPress(item)} />;
  }, [onMenuItemPress]);

  // UI/UX: Profile card component với null safety
  const renderProfileCard = () => (
    <View style={styles.profile_card}>
      <View style={styles.profile_left}>
        {/* FEATURE: Avatar với fallback */}
        <View style={styles.avatar}>
          {userProfile?.avatar ? (
            <Image
              source={{ uri: userProfile.avatar }}
              style={styles.avatar_image}
              resizeMode="cover"
            />
          ) : (
            <View style={styles.avatar_placeholder}>
              <Text style={styles.avatar_text}>
                {userProfile?.name?.charAt(0) || "U"}
              </Text>
            </View>
          )}
        </View>
        
        {/* FEATURE: User information với null safety */}
        <View style={styles.information}>
          <Text
            style={styles.text_card_info}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {userProfile?.name || "Không có tên"}
          </Text>
          <Text
            style={styles.text_card_info}
            numberOfLines={1}
            ellipsizeMode="tail"
          >
            {userProfile?.phone || "Không có SĐT"}
          </Text>
        </View>
      </View>

      {/* FEATURE: Profile button với better UX */}
      <TouchableOpacity 
        style={styles.profile_btn} 
        onPress={() => navigate.navigate(SCREENNAME.PROFILE)}
        activeOpacity={0.7}
      >
        <Text style={styles.btn_text}>Hồ sở cá nhân</Text>
        <ArrowRightIcon
          width={5}
          height={10}
          fill={R.colors.txtMain}
          style={styles.icon}
        />
      </TouchableOpacity>
    </View>
  );

  // FUNCTIONALITY: Render menu section với reusable logic
  const renderMenuSection = (title, data) => (
    <View style={styles.menu_container}>
      <Text style={styles.menu_title}>{title}</Text>
      <FlatList
        data={data}
        renderItem={renderMenuItem}
        numColumns={3}
        keyExtractor={(item) => item.id.toString()}
        scrollEnabled={false}
        columnWrapperStyle={styles.row}
        removeClippedSubviews={true} // PERFORMANCE: Memory optimization
        maxToRenderPerBatch={9} // PERFORMANCE: Render batch size
        windowSize={10} // PERFORMANCE: Window size optimization
      />
    </View>
  );

  return (
    <>
      {/* FIXME: StatusBar configuration để loại bỏ white space */}
      <StatusBar
        barStyle="light-content" // Text trắng trên dark background
        backgroundColor="transparent" // Background trong suốt
        translucent={true} // Cho phép content extend lên status bar
      />
      
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        {/* FIXME: Dùng View với manual padding thay SafeAreaView */}
        <View style={[
          { flex: 1 },
          { paddingTop: Platform.OS === 'ios' ? 0 : StatusBar.currentHeight }
        ]}>
          <View style={styles.container_body}>
            <ImageBackground
              source={R.images.igBackgroundSlider}
              style={[styles.background_header, {
                // FIXME: Extend background để cover status bar area
                paddingTop: Platform.OS === 'ios' ? 50 : (StatusBar.currentHeight || 0) + 10,
              }]}
            >
              <HeaderCus
                pathLogo={R.images.igLogo}
                width={75}
                height={36}
                textInput={R.colors.white}
                backgroundInput={R.colors.backgroundInputSearch}
                textLabel={I18n.t("Search")}
                textColorLabel={R.colors.white}
              />

              {renderProfileCard()}
            </ImageBackground>
            
            <ScrollView
              showsVerticalScrollIndicator={false}
              style={styles.scroll}
              bounces={false} // OPTIMIZE: Tắt bounce trên iOS
              overScrollMode="never" // OPTIMIZE: Tắt over scroll trên Android
            >
              {/* FUNCTIONALITY: Render các menu sections */}
              {renderMenuSection("Học tập", menuDataStudy)}
              {renderMenuSection("Cá nhân", menuDataIndividual)}
              {renderMenuSection("Dịch vụ trực tuyến", menuDataOnlineSer)}
            </ScrollView>
          </View>
        </View>
      </TouchableWithoutFeedback>
    </>
  );
};

export default HomeView;