import { View, Text, Pressable, ScrollView, Modal, Animated, StyleSheet, Platform,Dimensions ,FlatList} from 'react-native';
import tw from 'twrnc';
import { FontAwesome, Ionicons, Fontisto, FontAwesome6 } from '@expo/vector-icons';
import { useState, useRef, useEffect } from 'react';
import { Calendar } from 'react-native-calendars';
import {fetch as fetchAPI } from "@/middleware/AuthService";
import { checkAuthToken, handleAuthErrors } from "@/middleware/AuthUtils";
import { useRouter } from 'expo-router';
import { useUserAccess } from './_layout';
import * as Location from 'expo-location';
import { useToast } from "../../components/GlobalComponent/ToastContainer/ToastContext";
const { width } = Dimensions.get('window');
const isMobile = width < 768;
import FullScreenLoader from "../../components/GlobalComponent/Loader/loader";
const RefreshButton = ({ isRefreshing, onRefresh }) => {
  const animationValue = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    if (isRefreshing) {
      Animated.loop(
        Animated.timing(animationValue, {
          toValue: 1,
          duration: 1000,
          useNativeDriver: true,
        })
      ).start();
    } else {
      animationValue.stopAnimation();
      animationValue.setValue(0);
    }
  }, [isRefreshing]);

  const spin = animationValue.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '360deg'],
  });

  return (
    <Pressable onPress={onRefresh}>
      <Animated.View style={{ transform: [{ rotate: spin }] }}>
        <FontAwesome name="refresh" size={20} color="#e27953" />
      </Animated.View>
    </Pressable>
  );
};

export default function HomeScreen() {
  const router = useRouter();
  const { addToast } = useToast();
  const { userData, userAccess } = useUserAccess();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isLocationRefreshing, setIsLocationRefreshing] = useState(false);
  const [selectedDateDetails, setSelectedDateDetails] = useState({});
  const [currentLocation, setCurrentLocation] = useState(null);
  const [markedUserList, setMarkedUserList] = useState({});
  const [markedDotsList, setMarkedDotsList] = useState({});

  const [loading, setLoading] = useState(false);

  const today = new Date();
  const threeMonthsAgo = new Date(today);
  threeMonthsAgo.setMonth(today.getMonth() - 3);
  const handleLocationRefresh = async () => {
    setIsLocationRefreshing(true);
    await getCurrentLocation();
    setIsLocationRefreshing(false);
  };

  // open cage api usage 
  const getCurrentLocation = async () => {
    try {
      // Check for geolocation availability on the web
      if (!navigator.geolocation) {
        addToast("Geolocation is not supported by your browser.", "Error");
        return;
      }
  
      // Request for geolocation permission (web uses this implicitly)
      const locationPromise = new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, { enableHighAccuracy: true });
      });
  
      const location = await locationPromise;
  
  
      // Reverse geocoding to get the location name using OpenCage API
      const response = await fetch(
        `https://api.opencagedata.com/geocode/v1/json?q=${location.coords.latitude}+${location.coords.longitude}&key=f038d52a2c804bf4b6848dc5dd337d9a`
      );

      if (!response.ok) {
        throw new Error('Failed to fetch location name');
      }
  
      const data = await response.json();
  
      // Check if the response has valid location information
      if (data.results && data.results.length > 0) {
        const locationName = data.results[0].formatted;
  
        const currentLocation = {
          latitude: location.coords.latitude,
          longitude: location.coords.longitude,
          timestamp: new Date(location.timestamp).toLocaleString(),
          locationName,
        };
        console.log(data);
  
        // Set the current location with the name
        setCurrentLocation(currentLocation);
  
        return currentLocation; // Return the location object with the name
      } else {
        addToast("Unable to retrieve location details. Please try again.", "Error");
      }
    } catch (error) {
      console.error('Error fetching current location:', error.message);
      addToast("Error fetching current location: " + error.message, "Error");
    }
  };
  
  const calculateDuration = (punchIn, punchOut) => {
    if (punchIn && punchOut) {
      const punchInDate = new Date(punchIn);
      const punchOutDate = new Date(punchOut);
      if (!isNaN(punchInDate) && !isNaN(punchOutDate)) {
        const durationMs = punchOutDate - punchInDate;
        const hours = Math.floor(durationMs / (1000 * 60 * 60));
        const minutes = Math.floor((durationMs % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((durationMs % (1000 * 60)) / 1000);
        return `${hours}hrs ${minutes}min ${seconds}sec`;
      }
      return "Invalid date";
    }
    return "N/A";
  };

  const fetchMarkedDetails = async () => {
    try {
      const { authToken, deviceId } = await checkAuthToken(addToast);
      const threeMonthsAgo = new Date();
      threeMonthsAgo.setMonth(today.getMonth() - 3);
      
      const formatDate = (date) => {
        return date.toISOString().split('T')[0]; 
      };      
      const Parameter = {
        operation: "fetch",
        tblName: "tbl_attendence_master",
        data: "",
        conditionString: `user_id = '${userData?.user_id}' AND DATE(created_at) >= '${formatDate(threeMonthsAgo)}' ORDER BY PK_AttendenceId ASC`,
        checkAvailability: "",
        customQuery: "",
      };
  
      const response = await fetchAPI(Parameter, authToken, deviceId);
  
      if (Array.isArray(response) && response.length > 0) {
        const markedDates = response.reduce((acc, item) => {
          const dateKey = item?.created_at?.split('T')?.[0]; // Get date part (YYYY-MM-DD)
          if (dateKey) {
            const entry = {
              punchIn: item?.punchIn,
              punchOut: item?.punchOut,
              totalHours: item?.punchIn && item?.punchOut ? calculateDuration(item?.punchIn, item?.punchOut) : 'N/A',
              notes: 'Completed all tasks.',
             };
  
            if (!acc[dateKey]) {
              acc[dateKey] = [];
            }
            acc[dateKey].push(entry);
          }
          return acc;
        }, {});
  
        const dotDates = Object.keys(markedDates).reduce((acc, dateKey) => {
          acc[dateKey] = {
            marked: true,
            dotColor: dateKey === new Date().toISOString().split('T')[0] ? '#52B8AE' : '#E27953',
          };
          return acc;
        }, {});
        setMarkedUserList(markedDates);
        setMarkedDotsList(dotDates);
      } else {
        setMarkedUserList({});
        setMarkedDotsList({});
      }
    } catch (error) {
      setLoading(false);
      console.error("Error fetching attendance details:", error);
      handleAuthErrors(error, addToast, router);
    }
  };
  
  const handleDayPress = (day) => {
    const details = markedUserList[day.dateString] || []; // Get all entries for the selected day
    setSelectedDateDetails(details);
    setIsModalVisible(true);
  };
  


  useEffect(() => {
  
    const initializeLocationTracking = async () => {
      try {
        await fetchMarkedDetails();
        await handleLocationRefresh();


      } catch (error) {
        console.error("Error initializing location tracking:", error);
      }
    };

    initializeLocationTracking();
  }, []);
  
  return (
    <ScrollView >  
    <View style={tw`flex-1 bg-[#fff]   shadow-lg justify-center items-center   `}>
     {
          loading && (
            <FullScreenLoader visible={loading}/>
          )
        }
        <View style={tw ` ${isMobile ? '':'p-20'} pt-0 w-full`}>
          {/* User Info Section */}
          <View style={tw`bg-white  rounded-lg  h-18 mt-5 shadow-lg mx-3`}>
            <View style={tw`flex-row justify-between h-full items-center px-3 `}>
              <View style={tw`  flex-row gap-5 h-full items-center`}>
                <View style={tw` h-full   items-center justify-center  `}>
                  <FontAwesome
                    name="user-circle"
                    size={45}
                    color='#E27953'
                  />
                </View>
                <View style={tw``}>
                  <Text style={tw`text-lg font-bold text-gray-800`}>
                    {userData.name.length > 15 ? `${userData.name.slice(0, 15)}...` : userData.name}
                  </Text>
                  <Text style={tw`text-sm text-gray-500`}>
                    ({userData.username})
                  </Text>
                </View>

              </View>
               </View>
          </View>


          {/* Location Section */}
          <View style={tw`bg-white rounded-lg h-18 mx-3 px-4 mt-5  border-gray-200  flex-row justify-between items-center   shadow-lg`}>
            <View style={tw`flex-row items-center w-[90%]`}>
              <FontAwesome name="map-marker" size={30} color="#E27953" style={tw`mr-2`} />
              <Text style={tw`text-gray-600 text-sm w-[90%]`}>{currentLocation?.locationName || "No location found"}</Text>
            </View>
            <RefreshButton isRefreshing={isLocationRefreshing} onRefresh={handleLocationRefresh} />
          </View>

          {/* Quick Access Section */}
          <View style={tw`flex-col bg-white mt-5 mx-3 px-4  rounded-lg shadow-lg`}>
            <Text style={tw`text-lg font-bold text-gray-800 my-2`}>Quick Access</Text>
            <View style={tw`flex-row justify-start gap-4 mb-5`}>
              <Pressable onPress={() => router.push((`/reports/attendance?userData=${JSON.stringify(userData)}&userAccess=${JSON.stringify(userAccess)}`))}
                style={tw`bg-gray-100  p-2 min-w-28 min-h-28 justify-center items-center rounded-lg shadow-md`}>
                {/* Icon container */}
                <View style={tw`items-center justify-center mb-1`}>
                  <Ionicons name="calendar-number" size={26} color="#E27953" />
                </View>
                {/* Text label */}
                <Text style={tw`text-center text-md text-gray-800 font-semibold`}>
                  Attendance
                </Text>
              </Pressable>
            </View>
          </View>


          <View style={tw`bg-white  my-5 mx-3 rounded-lg shadow-lg p-1`}>
            <View style={tw`w-full rounded-lg`}>
            </View>


            <Calendar
              markingType={'custom'}
              onDayPress={handleDayPress}
              markedDates={markedDotsList || {}}
              renderArrow={(direction) => (
                <Ionicons
                  name={direction === 'left' ? 'chevron-back' : 'chevron-forward'}
                  size={29} 
                  color="#E27953"
                  style={{margin:0 ,padding:0 ,position:"relative" , right:0 , display:"flex"}}
                />
              )}
              theme={{
                todayTextColor: 'red',
                selectedDayBackgroundColor: 'green',
                selectedDayTextColor: 'white',
                dayTextColor: 'black',
                monthTextColor: 'black',
                arrowColor: 'green',
                textDayFontSize: 16,
                textMonthFontSize: Platform.OS == 'web' ? 20 : 18,
                textDayHeaderFontSize: 14,
                textSectionTitleColor: '#006D77',
              }}
              minDate={threeMonthsAgo.toISOString().split('T')[0]}
              maxDate={today.toISOString().split('T')[0]}
            />
          </View>

          <Modal visible={isModalVisible} animationType="slide" transparent={true}>
  <View style={tw`flex-1 justify-center items-center p-5`}>
    <View style={tw`bg-white p-2 ${isMobile ? 'w-full max-h-150' : 'w-full'} rounded-lg shadow-lg`}>
      {/* Close Button */}
      <Pressable
        onPress={() => setIsModalVisible(false)}
        style={tw`bg-[#E27953] p-2 z-1 absolute top-[-4] rounded-full ${isMobile ? 'right-[-3]' : 'left-148'}`}
      >
        <Fontisto name="close-a" size={14} color="white" />
      </Pressable>

      {/* Check for Data */}
      {selectedDateDetails?.length > 0 ? (
        <FlatList
          data={selectedDateDetails}
          renderItem={({ item }) => (
            <View style={tw`w-full mx-0 p-3 bg-gray-100 rounded-lg  ${selectedDateDetails.length==1 ? 'mb-0':'mb-2'}`}>
              <Text style={tw`text-lg font-bold mb-2`}>Attendance Details:</Text>
              <Text style={tw`text-gray-800  mb-2`}>
                Punch-In: {item.punchIn ? new Date(item.punchIn).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true, second: '2-digit' }) : '-'}
              </Text>
              <Text style={tw`text-gray-800 mb-2`}>
                Punch-Out: {item.punchOut ? new Date(item.punchOut).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true, second: '2-digit' }) : '-'}
              </Text>
              <Text style={tw`text-gray-800 mb-2`}>Total Hours: {item.totalHours}</Text>
              <Text style={tw`text-gray-800 mb-2`}>Notes: {item.notes}</Text>
            </View>
          )}
          keyExtractor={(item, index) => `${index}`}
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={tw`flex-grow`}
        />
      ) : (
        <View style={tw`w-full p-4 z-1 bg-gray-100 rounded-lg`}>
          <Text style={tw`text-lg font-bold mb-0 text-center`}>No data available for this date</Text>
        </View>
      )}
    </View>
  </View>
</Modal>

        </View>
    </View>
    </ScrollView>
  
  );
}
const styles = StyleSheet.create({
  hidescroll: {
    scrollbarWidth: 'none',
    '-ms-overflow-style': 'none',
    '&::-webkit-scrollbar': {
      display: 'none',
    }
  }
});