import React from "react";
import {
  View,
  Text,
  ImageBackground,
  TouchableOpacity,
  FlatList,
  ScrollView,
  TouchableWithoutFeedback,
  Keyboard,
  SafeAreaView,
  Image,
  StatusBar, // FEATURE: Thêm StatusBar để control status bar
  Platform,  // FEATURE: Check platform để xử lý khác biệt iOS/Android
} from "react-native";
import HeaderCus from "../home/header";
import R from "../../assets/R";
import ItemGrid from "./item";
import styles from "./style";
import { useNavigation } from "@react-navigation/native";
import * as SCREENNAME from "../../routers/ScreenNames";

const HomeView = (props) => {
  const {
    menuActivity,
    menuStatistics,
    menuNotification,
    selectedMenuItem,
    searchText,
    userProfile,
    onMenuItemPress,
    onSearchChange,
  } = props;
  const navigate = useNavigation();

  // FUNCTIONALITY: Render menu item với tối ưu performance
  const renderMenuItem = ({ item }) => {
    return <ItemGrid item={item} onPress={() => onMenuItemPress(item)} />;
  };

  // UI/UX: Card thông tin user với layout tối ưu
  const cardItemInfo = () => {
    return (
      <View style={styles.profileCard}>
        <View style={styles.profile_left}>
          {/* FEATURE: Avatar với fallback placeholder */}
          <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: Thông tin user với null safety */}
          <View style={styles.information}>
            <Text
              style={styles.text_card_info}
              numberOfLines={1}
              ellipsizeMode="tail"
            >
              {userProfile?.name ?? "Không có dữ liệu"}
            </Text>
            <Text
              style={styles.text_card_info}
              numberOfLines={1}
              ellipsizeMode="tail"
            >
              {userProfile?.phone ?? "Không có dữ liệu"}
            </Text>
          </View>
        </View>

        {/* FEATURE: Button navigate tới profile */}
        <TouchableOpacity 
          style={styles.profile_btn} 
          onPress={() => navigate.navigate(SCREENNAME.PROFILE)}
          activeOpacity={0.7}
        >
          <Text style={styles.btn_text}>Hồ sơ cá nhân</Text>
          <View style={styles.iconNext}>
            <Image
              source={R.images.icNext}
              style={{ width: 5, height: 10 }} // OPTIMIZE: Dùng style thay maxWidth/maxHeight
            />
          </View>
        </TouchableOpacity>
      </View>
    );
  };

  // FUNCTIONALITY: Render menu activity với FlatList tối ưu
  const renderMenuActivity = () => {
    return (
      <View style={styles.menu_container}>
        <Text style={styles.menu_title}>Giảng dạy</Text>
        <FlatList
          data={menuActivity}
          renderItem={renderMenuItem}
          numColumns={3}
          keyExtractor={(item) => item.id.toString()}
          scrollEnabled={false}
          columnWrapperStyle={styles.row}
          ListEmptyComponent={renderItemEmpty}
          removeClippedSubviews={true} // PERFORMANCE: Tối ưu memory
          maxToRenderPerBatch={9} // PERFORMANCE: Render tối đa 9 items/batch
        />
      </View>
    );
  };

  // FUNCTIONALITY: Render menu statistics
  const renderMenuStatistics = () => {
    return (
      <View style={styles.menu_container}>
        <Text style={styles.menu_title}>Thống kê</Text>
        <FlatList
          data={menuStatistics}
          renderItem={renderMenuItem}
          numColumns={3}
          keyExtractor={(item) => item.id.toString()}
          scrollEnabled={false}
          columnWrapperStyle={styles.row}
          ListEmptyComponent={renderItemEmpty}
          removeClippedSubviews={true}
          maxToRenderPerBatch={9}
        />
      </View>
    );
  };

  // FUNCTIONALITY: Render menu notification
  const renderMenuNotification = () => {
    return (
      <View style={styles.menu_container}>
        <Text style={styles.menu_title}>Văn bản và thông báo</Text>
        <FlatList
          data={menuNotification}
          renderItem={renderMenuItem}
          numColumns={3}
          keyExtractor={(item) => item.id.toString()}
          scrollEnabled={false}
          columnWrapperStyle={styles.row}
          ListEmptyComponent={renderItemEmpty}
          removeClippedSubviews={true}
          maxToRenderPerBatch={9}
        />
      </View>
    );
  };

  // UI/UX: Empty state component
  const renderItemEmpty = () => {
    return (
      <View style={styles.cardItemEmpty}>
        <Image
          source={R.images.icNoData}
          style={{ width: 50, height: 50 }} // OPTIMIZE: Dùng style object
        />
        <Text style={[styles.menu_text, { color: R.colors.red }]}>
          Không có dữ liệu
        </Text>
      </View>
    );
  };

  return (
    <>
      {/* FIXME: StatusBar để control màu status bar và remove white space */}
      <StatusBar
        barStyle="light-content" // Text trắng trên status bar
        backgroundColor="transparent" // Background trong suốt
        translucent={true} // Cho phép content hiển thị dưới status bar
      />
      
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        {/* FIXME: Dùng View thay SafeAreaView để loại bỏ white space */}
        <View style={[styles.safeArea, { paddingTop: Platform.OS === 'ios' ? 0 : StatusBar.currentHeight }]}>
          <View style={styles.container_body}>
            <ImageBackground
              source={R.images.igBackground}
              style={[styles.background_header, {
                // FIXME: Extend background lên trên để cover status bar
                paddingTop: Platform.OS === 'ios' ? 50 : (StatusBar.currentHeight || 0) + 10,
              }]}
            >
              <HeaderCus
                value={searchText}
                onChangeText={onSearchChange}
              />
              {cardItemInfo()}
            </ImageBackground>
            
            <ScrollView
              showsVerticalScrollIndicator={false}
              style={styles.scroll}
              bounces={false} // OPTIMIZE: Tắt bounce effect
              overScrollMode="never" // OPTIMIZE: Android không over scroll
            >
              {renderMenuActivity()}
              {renderMenuStatistics()}
              {renderMenuNotification()}
            </ScrollView>
          </View>
        </View>
      </TouchableWithoutFeedback>
    </>
  );
};

export default HomeView;