import React, { useState, useEffect, useCallback } from 'react';
import { View, Text, ScrollView, Image, Pressable, Modal, Dimensions, FlatList, TouchableWithoutFeedback,TextInput, Platform } from 'react-native';
import { FontAwesome, FontAwesome5, MaterialCommunityIcons, Entypo, Feather, AntDesign ,Fontisto} from '@expo/vector-icons';
import { useNavigation, useRoute } from '@react-navigation/native';
import tw from 'twrnc';
import { SafeAreaView } from 'react-native-safe-area-context';
import CustomDateTimePicker from '../DatePicker/CustomDateTimePicker';
import { checkAuthToken, handleAuthErrors } from '../../middleware/AuthUtils';
import { fetch } from '../../middleware/AuthService';
import Header from '../../components/GlobalComponent/Header/header';
import { useRouter } from 'expo-router';
import { useToast } from "../../components/GlobalComponent/ToastContainer/ToastContext";
import MapWeb from "../../components/GlobalComponent/Map/mapWeb";
import FullScreenLoader from "../../components/GlobalComponent/Loader/loader";

import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
const AttendanceLog = () => {
  const { userData } = useRoute().params || {};
  const { addToast } = useToast();
  const parsedUserData = userData ? JSON.parse(userData) : null;
  const navigation = useNavigation();
    const router = useRouter();
  
  const [activeTab, setActiveTab] = useState('Self');
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalTeamVisible, setIsModalTeamVisible] = useState(false);
  const [selectedTeamMember, setSelectedTeamMember] = useState([]);
  const [teamMember, setTeamMember] = useState([]);
  const [attendanceLog, setAttendanceLog] = useState([]);
  const [teamAttendanceLog, setTeamAttendanceLog] = useState([]);
  const [ISfilterbtn, setISfilterbtn] = useState(true);
  const [loading, setLoading] = useState(false);
  const [startDate, setStartDate] = useState(() => {
    const currentDate = new Date();
    return new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
  });
  const [endDate, setEndDate] = useState(new Date());
  const [teamStartDate, setTeamStartDate] = useState(() => {
    const currentDate = new Date();
    return new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
  });
  const [teamEndDate, setTeamEndDate] = useState(new Date());
  const [selectedStartDate, setSelectedStartDate] = useState(() => {
    const currentDate = new Date();
    return new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
  });
  const [selectedEndDate, setSelectedEndDate] = useState(new Date());
  const [isDatePickerVisible, setIsDatePickerVisible] = useState(false);
  const [selectedUserId, setSelectedUserId] = useState(null);

  const { width, height } = Dimensions.get('window');
  const isMobile = width < 768;
  
  const baseTableHeight1 = isMobile ? height * 0.75 : height * 0.75;
  const tableHeight1 = ISfilterbtn ? baseTableHeight1 - 16 : baseTableHeight1 - 122;
    
  const tableWidth1 = isMobile ? width * 1.4 : width * 0.97;
  
  const [isMeetingModalVisible, setIsMeetingModalVisible] = useState(false); 
  const handleOpenMeetingModal = async(id) => {
    setIsMeetingModalVisible(true);
    await handleGetMeetingData(id);
  };
  const handleCloseMeetingModal = () => setIsMeetingModalVisible(false);
  const handlePopup = async (selfAttendanceData) => {
    await fetchSelectedAttendanceList(selfAttendanceData);
    setSelectedUserId(selfAttendanceData?.user_id);
    setIsModalVisible(true);
  };

  const handleTeamPopup = async () => {
    await fetchTeamExcelAttendanceList();
    setIsModalTeamVisible(true);
  };

  const handelCloseModal = () => {
    setIsModalVisible(false);
    setIsModalTeamVisible(false);
    setTeamMember([]);
    setTeamStartDate(() => {
      const currentDate = new Date();
      return new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
    });
    setTeamEndDate(new Date());
    setSelectedUserId(null);
    setSelectedTeamMember([]);
    setStartDate(() => {
      const currentDate = new Date();
      return new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000);
    });
    setEndDate(new Date());
  }

  const fetchAttendanceList = async () => {
    try {
      const { authToken,deviceId } = await checkAuthToken(addToast);
      const formattedStartDate = selectedStartDate.toISOString().split('T')[0];
      const formattedEndDate = selectedEndDate.toISOString().split('T')[0];

      const response = await fetch(
        {
          operation: 'fetch',
          tblName: 'tbl_attendence_master',
          conditionString: `user_id = ${parsedUserData?.user_id} AND DATE(created_at) >= '${formattedStartDate}' AND DATE(created_at) <= '${formattedEndDate}' ORDER BY PK_AttendenceId DESC`,
        },
        authToken,
        deviceId
      );
      setAttendanceLog(response || []);
    } catch (error) {
      handleAuthErrors(error, addToast, router);
    }
  };

  useEffect(() => {
    fetchAttendanceList();
  }, [selectedStartDate, selectedEndDate]);

  const fetchTeamAttendanceList = useCallback(async () => {
    try {
      const { authToken,deviceId } = await checkAuthToken(addToast);
  
      const response = await fetch(
        {
          operation: 'custom',
          tblName: 'tbl_attendence_master',
          conditionString: `managerId = ${parsedUserData?.user_id} ORDER BY PK_AttendenceId DESC`,
        customQuery: `SELECT a.PK_AttendenceId, a.user_id, a.username, a.name, a.punchIn, a.punchOut, a.punchInPic, a.punchOutPic, a.created_at, a.created_by, a.updated_at, a.updated_by FROM tbl_attendence_master a INNER JOIN tbl_user_master u ON a.user_id = u.user_id WHERE u.managerId = ${parsedUserData?.user_id} AND a.created_at = ( SELECT MAX(sub_a.created_at) FROM tbl_attendence_master sub_a WHERE sub_a.user_id = a.user_id ) `
        },
        authToken,
        deviceId
      );
  
      setTeamAttendanceLog(response || []);
    } catch (error) {
      handleAuthErrors(error, addToast, router);
    }
  }, [parsedUserData]);

  useEffect(() => {
    fetchTeamExcelAttendanceList();
  }, [teamStartDate, teamEndDate]);

  const fetchTeamExcelAttendanceList = async () => {
    try {
      const { authToken,deviceId } = await checkAuthToken(addToast);
      const formattedStartDate = teamStartDate.toISOString().split('T')[0];
      const formattedEndDate = teamEndDate.toISOString().split('T')[0];
      const response = await fetch(
        {
          operation: 'custom',
          tblName: 'tbl_attendence_master',
          conditionString: ``,
          customQuery: ` SELECT a.PK_AttendenceId, a.user_id, a.username, a.name, a.punchIn, a.punchOut, a.punchInPic, a.punchOutPic, a.created_at, a.created_by, a.updated_at, a.updated_by FROM tbl_attendence_master a INNER JOIN tbl_user_master u ON a.user_id = u.user_id WHERE u.managerId = ${parsedUserData?.user_id} AND DATE(a.created_at) BETWEEN '${formattedStartDate}' AND '${formattedEndDate}'`
        },
          authToken,
          deviceId
      );
      setTeamMember(response || []);
    } catch (error) {
      handleAuthErrors(error, addToast, router);
    }
  };
  
  const fetchSelectedAttendanceList = async (item) => {
    try {
      const { authToken,deviceId } = await checkAuthToken(addToast);
      const formattedStartDate = startDate.toISOString().split('T')[0];
      const formattedEndDate = endDate.toISOString().split('T')[0];

      const response = await fetch(
        {
          operation: 'fetch',
          tblName: 'tbl_attendence_master',
          conditionString: `user_id = ${item?.user_id || selectedUserId} AND DATE(created_at) >= '${formattedStartDate}' AND DATE(created_at) <= '${formattedEndDate}' ORDER BY PK_AttendenceId DESC`,
        },
        authToken,
        deviceId
      );
      setSelectedTeamMember(response || []);
    } catch (error) {
      handleAuthErrors(error, addToast, router);
    }
  };

  const [meetingLog, setMeetingLog] = useState([]);
  const handleGetMeetingData = async (id) => {
    try {
      const { authToken,deviceId } = await checkAuthToken(addToast);
      const Parameter = {
        operation: "fetch",
        tblName: "tbl_meeting_log",
        data: "",
        conditionString: `FK_AttendenceId = ${id}`,
        checkAvailability: false,
        customQuery: ``,
      };

      const response = await fetch(
        Parameter,
        authToken,
        deviceId
      );

      if (response) {
        setMeetingLog(response.reverse());
      }
    } catch (error) {
      handleAuthErrors(error, addToast, router);
    }
  };
  const renderLogItem = ({ item }) => (
    <View style={tw`flex-row border-b border-gray-300 py-2 `}>
      <Text style={tw`flex-1 text-center text-sm text-gray-800`}>
        {item?.meetingIn && new Date(item?.meetingIn)?.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true, second: '2-digit' }) || "N/A"}
      </Text>
   
      <Text style={tw`flex-1 text-center text-sm text-gray-800`}>
        {item?.meetingOut && new Date(item?.meetingOut)?.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true, second: '2-digit' }) || "N/A"}
      </Text>
      <Text style={tw`flex-1 text-center text-sm text-gray-800`}>
        {item?.meetingOut && calculateDuration(item?.meetingIn, item?.meetingOut) || "N/A"}
      </Text>
      <Text style={tw`flex-1 text-center`}>{item.meetingDesc || 'No description'}</Text>

    </View>
  );
  const renderHeader = (title) => {
    const navigation = useNavigation();
    return (
      <Header title={title} userData={userData} showBackButton={true} onBackPress={() => navigation.goBack()} />
    );
  }
  useEffect(() => {
    fetchSelectedAttendanceList();
  }, [startDate, endDate]);
  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);

        let durationStr = '';
        if (hours > 0) {
          durationStr += `${hours} hrs `;
        }
        if (minutes > 0) {
          durationStr += `${minutes} min `;
        }
        if (seconds > 0) {
          durationStr += `${seconds} sec`;
        }

        return durationStr.trim();

      } else {
        return "Invalid date";
      }
    }
    return "N/A";
  };
  const [teamLocationMark, setTeamLocationMark] = useState([]);
  const [isModalMapVisible, setIsModalMapVisible] = useState(false);
  const toggleModal = () => setIsModalVisible(!isModalVisible);


  const toggleMapModal = async (id) => {
    try {
      setLoading(true);
      const { authToken,deviceId } = await checkAuthToken(addToast);
      const Parameter = {
        operation: "fetch",
        tblName: "tbl_location_log",
        data: "",
        conditionString: `FK_AttendenceId = '${id}' ORDER BY PK_locationLogId ASC `,
        checkAvailability: "",
        customQuery: "",
      };

      const response = await fetch(Parameter, authToken,deviceId);
      if (Array.isArray(response) && response.length > 0) {
        const locationMarked = response.map((item) => ({
          latitude: item.latitude,
          longitude: item.longitude,
          timestamp: item.created_at
        }));

        setTeamLocationMark(locationMarked);
        setIsModalMapVisible(!isModalMapVisible);
        setLoading(false);
      } else {
        setTeamLocationMark([]);
        setLoading(false);
      }
    } catch (error) {
      handleAuthErrors(error, addToast, router);
      setLoading(false);
    }
  };
  const handelCloseMapModal = () =>{
    setIsModalMapVisible(!isModalMapVisible);
    setLoading(false);
    setTeamLocationMark([]);
  }
  useEffect(() => {
    fetchAttendanceList();
    fetchTeamAttendanceList();
  }, []);

  // const handleExport = async () => {
  //   try {
  //     let dataToExport;
  //     let type;
  
  //     if (isModalVisible) {
  //       dataToExport = selectedTeamMember;
  //       type = 'modal';
  //     } else {
  //       dataToExport = activeTab === 'Self' ? attendanceLog : teamAttendanceLog;
  //       type = activeTab === 'Self' ? 'self' : 'team';
  //     }
  
  //     const csvContent = convertToCSV(dataToExport, type);
      
  //     if (!csvContent) {
  //       addToast('No data to export', 'info');
  //       return;
  //     }
  
  //     const filename = FileSystem.documentDirectory + `attendance_${Date.now()}.csv`;
  //     await FileSystem.writeAsStringAsync(filename, csvContent, { encoding: FileSystem.EncodingType.UTF8 });
  //     await Sharing.shareAsync(filename, { mimeType: 'text/csv', dialogTitle: 'Export Attendance Report' });
  //   } catch (error) {
  //     console.error('Error exporting data:', error);
  //     addToast(`Export failed: ${error.message}`, 'error');
  //   }
  // };
  

const handleExport = async () => {
  try {
    let dataToExport;
    let type;

    if (isModalVisible) {
      dataToExport = selectedTeamMember;
      type = 'modal';
    } else {
      dataToExport = activeTab === 'Self' ? attendanceLog : teamAttendanceLog;
      type = activeTab === 'Self' ? 'self' : 'team';
    }

    const csvContent = convertToCSV(dataToExport, type);
    
    if (!csvContent) {
      addToast('No data to export', 'info');
      return;
    }

    // Web platform handling
    if (Platform.OS === 'web') {
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      
      link.setAttribute('href', url);
      link.setAttribute('download', `attendance_${Date.now()}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } 
    // Mobile platform handling
    else {
      const filename = FileSystem.documentDirectory + `attendance_${Date.now()}.csv`;
      await FileSystem.writeAsStringAsync(filename, csvContent, { 
        encoding: FileSystem.EncodingType.UTF8 
      });
      await Sharing.shareAsync(filename, { 
        mimeType: 'text/csv', 
        dialogTitle: 'Export Attendance Report' 
      });
    }
  } catch (error) {
    addToast(`Export failed: ${error.message}`, 'error');
  }
};

const handleExportByTeam = async () => {
  try {
    let dataToExport;
    let type;

    if (isModalVisible) {
      dataToExport = selectedTeamMember;
      type = 'modal';
    } else {
      dataToExport = teamMember;
      type = 'team';
    }

    const csvContent = convertToCSV(dataToExport, type);
    if (!csvContent) {
      addToast('No data to export', 'info');
      return;
    }

    // Web platform handling
    if (Platform.OS === 'web') {
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      
      link.setAttribute('href', url);
      link.setAttribute('download', `attendance_${Date.now()}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } 
    // Mobile platform handling
    else {
      const filename = FileSystem.documentDirectory + `attendance_${Date.now()}.csv`;
      await FileSystem.writeAsStringAsync(filename, csvContent, { 
        encoding: FileSystem.EncodingType.UTF8 
      });
      await Sharing.shareAsync(filename, { 
        mimeType: 'text/csv', 
        dialogTitle: 'Export Attendance Report' 
      });
    }
  } catch (error) {
    addToast(`Export failed: ${error.message}`, 'error');
  }
};

const handleExportByMeeting = async () => {
  try {
    if (!meetingLog || meetingLog.length === 0) {
      addToast('No meeting data to export', 'info');
      return;
    }

    const csvContent = convertToCSVByMeeting(meetingLog, 'meeting');
    
    // Web platform handling
    if (Platform.OS === 'web') {
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      const url = URL.createObjectURL(blob);
      
      link.setAttribute('href', url);
      link.setAttribute('download', `meeting_logs_${Date.now()}.csv`);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    } 
    // Mobile platform handling
    else {
      const filename = FileSystem.documentDirectory + `meeting_logs_${Date.now()}.csv`;
      await FileSystem.writeAsStringAsync(filename, csvContent, { 
        encoding: FileSystem.EncodingType.UTF8 
      });
      await Sharing.shareAsync(filename, { 
        mimeType: 'text/csv', 
        dialogTitle: 'Export Meeting Report' 
      });
    }
  } catch (error) {
    addToast(`Export failed: ${error.message}`, 'error');
  }
};

// Update convertToCSV function to handle meeting data
const convertToCSVByMeeting = (data, type) => {
  if (!data || data.length === 0) return null;

  const headers = [];
  const rows = [];

  switch (type) {
    case 'meeting':
      headers.push('Meeting In', 'Meeting Out', 'Duration', 'Description');
      data.forEach(item => {
        const meetingIn = item.meetingIn 
          ? new Date(item.meetingIn).toLocaleString('en-US', {
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: true
            })
          : 'N/A';
        
        const meetingOut = item.meetingOut 
          ? new Date(item.meetingOut).toLocaleString('en-US', {
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: true
            })
          : 'N/A';

        const duration = calculateDuration(item.meetingIn, item.meetingOut);
        
        rows.push([
          escapeCSVField(meetingIn),
          escapeCSVField(meetingOut),
          escapeCSVField(duration),
          escapeCSVField(item.meetingDesc || 'No description')
        ]);
      });
      break;
  }

  return [headers.join(',')].concat(rows.map(row => row.join(','))).join('\n');
};

  const escapeCSVField = (field) => {
    if (typeof field === 'string' && (field.includes(',') || field.includes('"'))) {
      return `"${field.replace(/"/g, '""')}"`;
    }
    return field;
  };
  
  const convertToCSV = (data, type) => {
    if (!data || data.length === 0) return null;
  
    const headers = [];
    const rows = [];
  
    // Determine headers and row data based on export type
    if (type === 'modal' || type === 'self') {
      headers.push('Date', 'In-Time', 'Out-Time', 'Duration');
      data.forEach(item => {
        const date = item.punchIn ? new Date(item.punchIn).toLocaleDateString('en-GB') : 'N/A';
        const inTime = item.punchIn ? new Date(item.punchIn).toLocaleTimeString('en-US', { 
          hour: '2-digit', 
          minute: '2-digit', 
          hour12: true 
        }) : 'N/A';
        const outTime = item.punchOut ? new Date(item.punchOut).toLocaleTimeString('en-US', { 
          hour: '2-digit', 
          minute: '2-digit', 
          hour12: true 
        }) : 'N/A';
        const duration = calculateDuration(item.punchIn, item.punchOut);
        
        rows.push([
          escapeCSVField(date),
          escapeCSVField(inTime),
          escapeCSVField(outTime),
          escapeCSVField(duration)
        ]);
      });
    } else if (type === 'team') {
      headers.push('Employee ID', 'Name', 'Date', 'In-Time', 'Out-Time', 'Duration');
      data.forEach(item => {
        const empId = item.created_by?.split?.('(')?.[1]?.split(')')?.[0] || 'N/A';
        const name = item.created_by?.split?.(' (')?.[0] || 'N/A';
        const date = item.punchIn ? new Date(item.punchIn).toLocaleDateString('en-GB') : 'N/A';
        const inTime = item.punchIn ? new Date(item.punchIn).toLocaleTimeString('en-US', { 
          hour: '2-digit', 
          minute: '2-digit', 
          hour12: true 
        }) : 'N/A';
        const outTime = item.punchOut ? new Date(item.punchOut).toLocaleTimeString('en-US', { 
          hour: '2-digit', 
          minute: '2-digit', 
          hour12: true 
        }) : 'N/A';
        const duration = calculateDuration(item.punchIn, item.punchOut);
        
        rows.push([
          escapeCSVField(empId),
          escapeCSVField(name),
          escapeCSVField(date),
          escapeCSVField(inTime),
          escapeCSVField(outTime),
          escapeCSVField(duration)
        ]);
      });
    }
  
    // Combine headers and rows
    return [headers.join(',')].concat(rows.map(row => row.join(','))).join('\n');
  };

  return (
    <View style={tw`flex-1 bg-gray-100`}>
      <Header
        title="Daily Attendance"
        userData={userData}
        showBackButton={true}
        onBackPress={() => navigation.goBack()}
      />
        <ScrollView style={[tw`px-2 py-4  `,]}>
        <View style={tw`bg-white rounded-lg shadow  px-12 py-4`}>
        <View style={tw`flex-row justify-between items-center mb-4`}>
                  <View style={[tw`flex-row justify-center`, { width: isMobile ? '80%' : '50%' }]}>
              {['Self', 'Team'].map((tab) => (
                      <Pressable
                        key={tab}
                        style={[
                          tw`flex-1 flex-row justify-center items-center py-2 border-b-4`,
                          {
                            borderColor: activeTab === tab ? '#e94957' : 'transparent', 
                            width: isMobile ? '100%' : '45%',
                          },
                        ]}
                        onPress={() => setActiveTab(tab)}
                      >
                        <Text>
                        <FontAwesome
                          name={tab === 'Self' ? 'user' : 'users'}
                          size={20}
                          color={activeTab === tab ? '#e94957' : '#808080'} // Icon color matches the active tab
                        /></Text>
                        <Text
                          style={tw`ml-2 text-base font-semibold ${activeTab === tab ? 'text-[#e94957]' : 'text-gray-500'
                            }`}
                        >
                          {tab}
                        </Text>
                      </Pressable>
                    ))}
                  </View>
                  <Pressable onPress={() => activeTab === 'Team' ? handleTeamPopup() : handleExport()} style={tw`p-2`}>
                  <FontAwesome name="file-excel-o" size={30} color="green" />
                </Pressable>
              </View>
            
            {(activeTab === 'Self') && (
              <View style={[tw`flex-row ${ISfilterbtn ? 'hidden' : ''}  z-9  mb-4 `, { justifyContent: isMobile ? 'flex-start' : 'flex-start' ,position:"relative" }]}>
                <CustomDateTimePicker
                  date={selectedStartDate}
                  onDateChange={setSelectedStartDate}
                  placeholder="Start Date"
                  maxDateValue={selectedEndDate}
                  style={[
                    tw`px-2`,
                    { position: 'relative', zIndex: 10 },
                  ]}
                  placeholderTextStyle={tw`text-base text-gray-500 p-8`}
                />
                <CustomDateTimePicker
                  date={selectedEndDate}
                  onDateChange={setSelectedEndDate}
                  placeholder="End Date"
                  minDateValue={selectedStartDate}
                  maxDateValue={new Date()}
                  style={[
                    tw`px-0`,
                    { position: 'relative', zIndex: 10 },
                  ]}
                />
              </View>
            )}
            <ScrollView
              horizontal={isMobile ? true : true}
              nestedScrollEnabled
              contentContainerStyle={tw`flex-grow mt-2`}
            >
              <View style={[{ maxHeight: isMobile ? tableHeight1 : tableHeight1, minWidth: isMobile ? tableWidth1 : tableWidth1, }, tw`   `]}>
                <FlatList
                  data={activeTab === 'Self' ? attendanceLog : teamAttendanceLog}
                  keyExtractor={(item, index) => index.toString()}
                  ListHeaderComponent={() => (
                    <View
                      style={[
                        tw`flex-row bg-[#006d77] p-2 border-b border-gray-300`
                      ]}
                    >
                      {activeTab === 'Team' && (
                        <Text
                          style={[
                            tw`font-semibold text-white text-left`,
                            { width: isMobile ? 80 : 300, }
                          ]}
                        >
                        Empl ID
                        </Text>
                      )}
                    {activeTab === 'Team' && (
                        <Text
                          style={[
                            tw`font-semibold text-white text-left`,
                            { width: isMobile ? 100 : 300, }
                          ]}
                        >
                          Name 
                        </Text>
                      )}
                      <Text
                        style={[
                          tw`font-semibold text-white text-center`,
                          {
                            width: activeTab === 'Team'
                              ? (isMobile ? 150 : 300) 
                              : (isMobile ? 150 : 400),
                          },
                        ]}
                      >
                        Date
                      </Text>
                      <Text
                        style={[
                          tw`font-semibold text-white text-center`,
                          {
                            width: activeTab === 'Team'
                              ? (isMobile ? 150 : 300) 
                              : (isMobile ? 150 : 400),
                          },
                        ]}
                      >
                        In-Time 
                      </Text>
                      <Text
                        style={[
                          tw`font-semibold text-white text-center`,
                          {
                            width: activeTab === 'Team'
                              ? (isMobile ? 150 : 300) 
                              : (isMobile ? 150 : 400),
                          },
                        ]}
                      >
                        Out-Time 
                      </Text>
                 
                      <Text
                        style={[
                          tw`font-semibold text-white text-center`,
                          {
                            width: activeTab === 'Team'
                              ? (isMobile ? 120 : 300) 
                              : (isMobile ? 120 : 400),
                          },
                        ]}
                      >
                   Duration
                      </Text>
                      <Text   style={[
                                        tw`font-semibold text-white`,
                                        {
                                          textAlign: isMobile ? 'right' : 'right',
                                        },
                                      ]}
                                    >     Actions
                           {(activeTab === 'Team' || activeTab === 'Self') && (
                                  <>
                                  </>
                                  )}
                </Text>
                    </View>
                  )}
                  renderItem={({ item }) => (
                    <Pressable style={tw`flex-row items-center border-b border-gray-300 p-2`}>

                      {activeTab === 'Team' && (
                        <View style={{ width: isMobile ? 80 : 300 }}>
                          <Text style={tw`text-gray-800 font-semibold text-sm text-left`}>
                          {item.created_by?.split?.('(')?.[1]?.split(')')?.[0] || 'N/A'}                        
                          </Text>
                        </View>
                      )}
                  {activeTab === 'Team' && (
                                        <View style={{ width: isMobile ? 100 : 300 }}>
                                          <Text style={tw`text-gray-800 font-semibold text-sm text-left`}>
                                          {item.created_by?.split?.(' (')?.[0] || 'N/A'}

                                          </Text>
                                        </View>
                                      )}
                      <View
                        style={{
                          width: activeTab === 'Team'
                            ? (isMobile ? 150 : 300) 
                            : (isMobile ? 150 : 400),
                        }}
                      >
                        <Text style={tw`text-gray-800 font-semibold text-sm text-center`}>
                          {item.punchIn
                            ? new Date(item.punchIn).toLocaleDateString("en-GB", {
                              day: "2-digit",
                              month: "short",
                              year: "numeric",
                            })
                            : "-"}
                        </Text>
                      </View>
                      <View
                        style={{
                          width: activeTab === 'Team'
                            ? (isMobile ? 150 : 300)
                            : (isMobile ? 150 : 400),
                          alignItems: "center",
                        }}
                      >
                        <Text style={tw`text-gray-600 text-sm text-center`}>
                          {item.punchIn
                            ? new Date(item.punchIn).toLocaleTimeString("en-US", {
                              hour: "2-digit",
                              minute: "2-digit",
                              hour12: true,
                            })
                            : "-"}
                        </Text>
                      </View>
                      <View
                        style={{
                          width: activeTab === 'Team'
                            ? (isMobile ? 150 : 300)
                            : (isMobile ? 150 : 400),
                          alignItems: "left",
                        }}
                      >
                        <Text style={tw`text-gray-600 text-sm text-center`}>
                          {item.punchOut
                            ? new Date(item.punchOut).toLocaleTimeString("en-US", {
                              hour: "2-digit",
                              minute: "2-digit",
                              hour12: true,
                            })
                            : "-"}
                        </Text>
                      </View>

                      <View
                        style={{
                          width: activeTab === 'Team'
                            ? (isMobile ? 150 : 300)
                            : (isMobile ? 150 : 400),
                          alignItems: "left",
                        }}
                      >
                          <Text style={tw`flex-1 text-center text-sm text-gray-800`}>
                            {item?.punchOut && calculateDuration(item?.punchIn, item?.punchOut) || "N/A"}
                        </Text>

                  </View>
                      <View
                        style={{
                          justifyContent: "flex-end",
                          alignItems:"center",
                          display:"inline-block"
                        }}
                      >
                        {activeTab === 'Team' && (
                          <Pressable onPress={() => handlePopup(item)} style={tw`ml-2 `}>
                                  <Text>  
                                    <AntDesign name="copy1" size={24} color="teal" />
                                  </Text>
                         
                          </Pressable>
                        )}

                        {activeTab === 'Self' && (
                          <View style={tw`flex-row mr-4`}>
                            <Pressable onPress={() => toggleMapModal(item.PK_AttendenceId)}  style={[tw`ml-2`]}>
                              <Text>
                                <AntDesign name="eyeo" size={24} color="teal" />
                              </Text>
                            </Pressable>
                            <Pressable   onPress={() => handleOpenMeetingModal(item.PK_AttendenceId)} style={tw`ml-2 `} >
                                <FontAwesome5 name="meetup" size={24} color="teal" />
                            </Pressable>
                            </View>
                          )}
                    </View>

                      
                    </Pressable>
                  )}
                  ListEmptyComponent={
                    <Text style={tw`text-center text-gray-500 mt-4`}>There is no data</Text>
                  }
                />
              </View>
            </ScrollView>

            <Modal
              visible={isModalVisible}
              transparent={true}
              animationType="slide"
              onRequestClose={() => setIsModalVisible(false)}
             >
            <SafeAreaView style={tw`flex-1 bg-black bg-opacity-50 justify-center items-center`}>
              <View
                style={[
                  tw`bg-white relative rounded-lg overflow-hidden p-5`,
                  { width: isMobile ? '95%' : '80%', height: isMobile ? '95%' : '90%' },
                ]}
              >
                {/* Close Button */}
                <Pressable
                  style={[tw`absolute z-20`,{top:-3 ,right:-3}]}
                  onPress={() => handelCloseModal()}
                >
                  <Entypo name="circle-with-cross" size={35} color="#E27953" />
                </Pressable>

                {/* Header */}
                <View style={tw`mb-4  mt-6 p-3 bg-gray-100 flex-row justify-between items-center`}>
                <Text style={tw`text-lg font-bold text-center`}>Team Member Details</Text>
                <Pressable onPress={handleExport}>
                  <FontAwesome name="file-excel-o" size={30} color="green" />
                </Pressable>
                </View>

                {/* Date Pickers */}
                <View style={tw`flex-row gap-4 z-9 py-5 px-12` }>
                  <CustomDateTimePicker
                    date={startDate}
                    onDateChange={setStartDate}
                    placeholder="Start Date"
                    maxDateValue={endDate}
                  />
                  <CustomDateTimePicker
                    date={endDate}
                    onDateChange={setEndDate}
                    placeholder="End Date"
                    minDateValue={startDate}
                    maxDateValue={new Date()}
                  />
                </View>

                <ScrollView horizontal={true} showsHorizontalScrollIndicator={true}>
                  <View style={tw`flex-1`}>
                    <FlatList
                      data={selectedTeamMember}
                      keyExtractor={(item, index) => index.toString()}
                      contentContainerStyle={tw`flex-grow`}
                      ListHeaderComponent={
                        <View style={tw`flex-row bg-[#006d77] p-2`}>
                          {['Date', 'In-Time', 'Out-Time', 'Duration','Action'].map((header, index) => (
                            <Text
                              key={index}
                              style={[
                                tw`font-bold text-white `,
                                index === 0 ? tw`text-left` : tw`text-center`,
                                { width: isMobile ? 100 : 300 },
                              ]}
                            >
                              {header}
                            </Text>
                          ))}
                        </View>
                      }
                      renderItem={({ item }) => (
                        <View style={tw`flex-row border-b border-gray-300 p-2`}>
                          <Text style={[tw`text-gray-600 text-left`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchIn
                              ? new Date(item.punchIn).toLocaleDateString('en-GB', {
                                  day: '2-digit',
                                  month: 'short',
                                  year: 'numeric',
                                })
                              : 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchIn
                              ? new Date(item.punchIn).toLocaleTimeString('en-US', {
                                  hour: '2-digit',
                                  minute: '2-digit',
                                  hour12: true,
                                })
                              : 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchOut
                              ? new Date(item.punchOut).toLocaleTimeString('en-US', {
                                  hour: '2-digit',
                                  minute: '2-digit',
                                  hour12: true,
                                })
                              : 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchIn && item.punchOut
                              ? calculateDuration(item.punchIn, item.punchOut)
                              : 'N/A'}
                          </Text>
                          <View style={[tw`justify-center items-center flex-row` , { width: isMobile ? 100 : 300 }]}>

                            <Pressable onPress={() => toggleMapModal(item.PK_AttendenceId)}  style={tw`ml-2`}>
                              <Text>
                                <AntDesign name="eyeo" size={24} color="teal" />
                              </Text>
                            </Pressable>
                            <Pressable   onPress={() => handleOpenMeetingModal(item.PK_AttendenceId)} style={tw`ml-2 `} >
                                <FontAwesome5 name="meetup" size={24} color="teal" />
                            </Pressable>
                            </View>
                        </View>
                      )}
                      ListEmptyComponent={
                        <Text style={tw`text-center text-gray-500 mt-4`}>There is no data</Text>
                      }
                    />
                  </View>
                </ScrollView>
              </View>
            </SafeAreaView>
          </Modal>


      <Modal
              visible={isModalTeamVisible}
              transparent={true}
              animationType="slide"
              onRequestClose={() => setIsModalTeamVisible(false)}
             >
            <SafeAreaView style={tw`flex-1 bg-black bg-opacity-50 justify-center items-center `}>
              <View
                style={[
                  tw`bg-white relative rounded-lg overflow-hidden p-8`,
                  { width: isMobile ? '95%' : '80%', height: isMobile ? '95%' : '95%' , zIndex: 1},
                ]}
              >
                {/* Close Button */}
                <Pressable
                  style={[tw`absolute z-20`,{top:-3 ,right:-3}]}
                  onPress={() => handelCloseModal()}
                >
                  <Entypo name="circle-with-cross" size={35} color="#E27953" />
                </Pressable>

                {/* Header */}
                <View style={tw`mb-4 p-3 bg-gray-100 flex-row justify-between items-center`}>
                <Text style={tw`text-lg font-bold text-center`}>Team Member Details</Text>
                <Pressable onPress={handleExportByTeam}>
                  <FontAwesome name="file-excel-o" size={30} color="green" />
                </Pressable>
                </View>

                {/* Date Pickers */}
                <View style={tw`flex-row gap-4  z-9 py-5 px-10`}>
                  <CustomDateTimePicker
                    date={teamStartDate}
                    onDateChange={setTeamStartDate}
                    placeholder="Start Date"
                    maxDateValue={teamEndDate}
                    placeholderTextStyle={tw`text-base text-gray-500 px-4`} 
                    // style={tw`w-90`} 

                  />
                  <CustomDateTimePicker
                    date={teamEndDate}
                    onDateChange={setTeamEndDate}
                    placeholder="End Date"
                    minDateValue={teamStartDate}
                    maxDateValue={new Date()}
                    placeholderTextStyle={tw`text-base text-gray-500 px-4`} 

                  />
                </View>

                <ScrollView horizontal={true} showsHorizontalScrollIndicator={true}>
                  <View style={tw`flex-1`}>
                  <FlatList
                      data={teamMember}
                      keyExtractor={(item, index) => index.toString()}
                      contentContainerStyle={tw`flex-grow`}
                      ListHeaderComponent={
                        <View style={tw`flex-row bg-[#006d77] p-2`}>
                          {['Empl ID','Name','Date', 'In-Time', 'Out-Time', 'Duration','Action'].map((header, index) => (
                            <Text
                              key={index}
                              style={[
                                tw`font-bold text-white `,
                                index === 0 ? tw`text-left` : tw`text-center`,
                                { width: isMobile ? 100 : 300 },
                              ]}
                            >
                              {header}
                            </Text>
                          ))}
                        </View>
                      }
                      renderItem={({ item }) => (
                        <View style={tw`flex-row border-b border-gray-300 p-2`}>
                          <Text style={[tw`text-gray-600 text-left`, { width: isMobile ? 100 : 300 }]}>
                            {item.created_by?.split?.('(')?.[1]?.split(')')?.[0] || 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.created_by?.split?.(' (')?.[0] || 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchIn
                              ? new Date(item.punchIn).toLocaleDateString('en-GB', {
                                  day: '2-digit',
                                  month: 'short',
                                  year: 'numeric',
                                })
                              : 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchIn
                              ? new Date(item.punchIn).toLocaleTimeString('en-US', {
                                  hour: '2-digit',
                                  minute: '2-digit',
                                  hour12: true,
                                })
                              : 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchOut
                              ? new Date(item.punchOut).toLocaleTimeString('en-US', {
                                  hour: '2-digit',
                                  minute: '2-digit',
                                  hour12: true,
                                })
                              : 'N/A'}
                          </Text>
                          <Text style={[tw`text-gray-600 text-center`, { width: isMobile ? 100 : 300 }]}>
                            {item.punchIn && item.punchOut
                              ? calculateDuration(item.punchIn, item.punchOut)
                              : 'N/A'}
                          </Text>
                          <View style={[tw`justify-center items-center flex-row` , { width: isMobile ? 100 : 300 }]}>

                            <Pressable onPress={() => toggleMapModal(item.PK_AttendenceId)}  style={[tw`ml-2`,{zIndex:10}]}>
                              <Text>
                                <AntDesign name="eyeo" size={24} color="teal" />
                              </Text>
                            </Pressable>
                            <Pressable   onPress={() => handleOpenMeetingModal(item.PK_AttendenceId)} style={tw`ml-2 `} >
                                <FontAwesome5 name="meetup" size={24} color="teal" />
                            </Pressable>
                            </View>
                        </View>
                      )}
                      ListEmptyComponent={
                        <Text style={tw`text-center text-gray-500 mt-4`}>There is no data</Text>
                      }
                    />
                  </View>
                </ScrollView>
              </View>
            </SafeAreaView>
          </Modal>


{/* modal for Meeting */}
<Modal
        visible={isMeetingModalVisible}
        transparent={true}
        animationType="slide"
        onRequestClose={handleCloseMeetingModal}
      >
        <View style={tw`flex-1 bg-black bg-opacity-50 justify-center items-center`}>
          <View
            style={[
              tw`bg-white relative rounded-lg p-4 shadow-lg p-5`,
              // { width: "90%", height: "90%" },
              { width: isMobile ? '95%' : '80%', height: isMobile ? '95%' : '95%' ,}
            ]}
          >
            <Pressable
              style={[tw`absolute z-20`, { top: -4, right: -4 }]}
              onPress={handleCloseMeetingModal}
            >
              <Entypo name="circle-with-cross" size={35} color="#E27953" />
            </Pressable>

            {/* Header */}
            <View style={tw`mb-4 p-2 bg-gray-100 flex-row justify-between items-center mt-4`}>
              <Text style={tw`text-lg font-bold text-center`}>Meeting Details</Text>
              <Pressable onPress={handleExportByMeeting} style={tw`p-2`}>
            <FontAwesome name="file-excel-o" size={30} color="green" />
          </Pressable>
            </View>

            {/* Modal Content */}
            <View style={tw`mt-8 p-8 flex-1 bg-white rounded-lg shadow-md  `}>
              <View style={tw`flex-row rounded-t-lg bg-[#006d77] py-2`}>
                <Text style={tw`flex-1 text-center font-bold text-white`}>In-Time</Text>
                <Text style={tw`flex-1 text-center font-bold text-white`}>Out-Time</Text>
                <Text style={tw`flex-1 text-center font-bold text-white`}>Duration</Text>
                <Text style={tw`flex-1 text-center font-bold text-white`}>Description</Text>
              </View>
              <FlatList
                data={meetingLog}
                renderItem={renderLogItem}
                keyExtractor={(item) => item.Pk_MeetingId}
                contentContainerStyle={tw`pb-4`}
                showsVerticalScrollIndicator={false}
                ListEmptyComponent={
                  <Text style={tw`text-center text-gray-500 mt-4`}>There is no data</Text>
                }
              />
            </View>
          </View>
        </View>
      </Modal>
    
<Modal visible={isModalMapVisible} animationType="slide" transparent={true}>    
            <View style={[tw`flex-1 justify-center items-center py-5 px-3  bg-[#f6f6f6] `, { zIndex: 1000 , }]}>
            <Pressable onPress={handelCloseMapModal} style={tw`absolute top-5 right-2 bg-[#E27953] p-2 rounded-full z-50`}>
                  <Fontisto name="close-a" size={22} color="white" />

                </Pressable>
            <View style={tw`bg-white w-full h-full shadow p-1 rounded-lg`}>
            {  loading && (
  <FullScreenLoader visible={true}/>
          )
          }
          {<MapWeb locationsArray={teamLocationMark}/>}
              </View>
            </View>
           
      </Modal>


          </View>
        </ScrollView>
        {
            activeTab === 'Self' && (

              <View style={tw`absolute z-5 bottom-4 right-2 rounded-full p-2 bg-[#e94957] w-14 h-14 justify-center items-center`}>

                <Pressable onPress={() => setISfilterbtn(prevState => !prevState)}  >
                  <Text><FontAwesome name="filter" size={30} color='white' /></Text>

                </Pressable>
              </View>

            )
          }
     
    </View>
  );
};

export default AttendanceLog;
