import React, { useEffect, useState } from 'react';
import axios from 'axios';
import useIsAuthenticated from 'react-auth-kit/hooks/useIsAuthenticated';
import useAuthUser from 'react-auth-kit/hooks/useAuthUser';
import { Tabs, Tab, Box, Typography, AppBar, IconButton, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Button, TextField } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { debounce } from 'lodash';

const FriendRequestsPopup = ({ onClose }) => {
    const isAuthenticated = useIsAuthenticated();
    const isLoggedIn = isAuthenticated(); // This will be true or false
    const user = useAuthUser();
    const [tabIndex, setTabIndex] = useState(0);
    const [friendRequests, setFriendRequests] = useState([]);
    const [sentRequests, setSentRequests] = useState([]);
    const [friends, setFriends] = useState([]);
    const [searchResults, setSearchResults] = useState([]);
    const [searchQuery, setSearchQuery] = useState('');

    useEffect(() => {
        if (isLoggedIn) {
            fetchFriendRequests();
            fetchSentRequests();
            fetchFriends();
        }
    }, [isLoggedIn]);

    useEffect(() => {
        if (searchQuery.length > 0) {
            handleSearch();
        }
    }, [searchQuery]);

    const handleTabChange = (event, newValue) => {
        setTabIndex(newValue);
    };

    const fetchFriendRequests = async () => {
        try {
            const res = await axios.get(`${import.meta.env.VITE_REACT_APP_LEUMAS_LOGIN_ENDPOINT}/soxial/friendRequests`, {
                headers: {
                    'x-backend-token': user?.backendToken // MongoDB token
                }
            });
            setFriendRequests(res.data);
        } catch (error) {
            console.error(error);
        }
    };

    const fetchSentRequests = async () => {
        // Implement fetching sent requests
    };

    const fetchFriends = async () => {
        // Implement fetching friends
    };

    const handleSearch = debounce(async () => {
        try {
            const res = await axios.get(`${import.meta.env.VITE_REACT_APP_LEUMAS_LOGIN_ENDPOINT}/soxial/searchUsers?query=${searchQuery}`, {
                headers: {
                    'x-backend-token': user?.backendToken // MongoDB token
                }
            });
            console.log(res)
            setSearchResults(res.data);
        } catch (error) {
            console.error(error);
        }
    }, 300);

    const handleSendRequest = async (recipientId) => {
        const confirmSend = window.confirm("Are you sure you want to send a friend request?");
        if (!confirmSend) return;
    
        try {
            await axios.post(`${import.meta.env.VITE_REACT_APP_LEUMAS_LOGIN_ENDPOINT}/soxial/sendFriendRequest`, { recipientId }, {
                headers: {
                    'x-backend-token': user.backendToken // MongoDB token
                }
            });
            fetchSentRequests();
            alert('Friend request sent successfully!');
        } catch (error) {
            console.error('Error sending friend request:', error);
            alert('Failed to send friend request. Please try again later.');
        }
    };
    

    return (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center w-screen h-screen p-2">
            <div className="bg-white p-4 rounded-lg w-full max-w-lg">
                <AppBar position="static" color="default">
                    <Box display="flex" justifyContent="space-between" alignItems="center" p={1}>
                        <Typography variant="h6" component="div">
                            Friend Requests
                        </Typography>
                        <IconButton onClick={onClose} color="inherit">
                            <CloseIcon />
                        </IconButton>
                    </Box>
                    <Tabs value={tabIndex} onChange={handleTabChange} indicatorColor="primary" textColor="primary" variant="fullWidth">
                        <Tab label="Friend Requests" />
                        <Tab label="Sent Requests" />
                        <Tab label="My Friends" />
                        <Tab label="Search Users" />
                    </Tabs>
                </AppBar>
                <TabPanel value={tabIndex} index={0}>
                    <ul>
                        {friendRequests?.map((request, index) => (
                            <li key={index}>
                                {request.nicename}
                                <button onClick={() => handleAcceptRequest(request._id)}>Accept</button>
                                <button onClick={() => handleDeclineRequest(request._id)}>Decline</button>
                            </li>
                        ))}
                    </ul>
                </TabPanel>
                <TabPanel value={tabIndex} index={1}>
                    {/* Render sent requests */}
                </TabPanel>
                <TabPanel value={tabIndex} index={2}>
                    {/* Render friends */}
                </TabPanel>
                <TabPanel value={tabIndex} index={3}>
                    <TextField
                        fullWidth
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        placeholder="Search users..."
                        variant="outlined"
                        margin="normal"
                    />
                    <TableContainer>
                        <Table>
                            <TableHead>
                                <TableRow>
                                    <TableCell>Username</TableCell>
                                    <TableCell>Nice Name</TableCell>
                                    <TableCell>Email</TableCell>
                                    <TableCell>Action</TableCell>
                                </TableRow>
                            </TableHead>
                            <TableBody>
                                {searchResults.map((user, index) => (
                                    <TableRow key={index}>
                                        <TableCell>{user.frontend_username}</TableCell>
                                        <TableCell>{user.nicename}</TableCell>
                                        <TableCell>{user.email}</TableCell>
                                        <TableCell>
                                            <Button variant="contained" color="primary" onClick={() => handleSendRequest(user._id)}>
                                                Add Friend
                                            </Button>
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    </TableContainer>
                </TabPanel>
            </div>
        </div>
    );
};

const TabPanel = (props) => {
    const { children, value, index, ...other } = props;

    return (
        <div
            role="tabpanel"
            hidden={value !== index}
            id={`tabpanel-${index}`}
            aria-labelledby={`tab-${index}`}
            {...other}
        >
            {value === index && (
                <Box p={3}>
                    <Typography>{children}</Typography>
                </Box>
            )}
        </div>
    );
};

export default FriendRequestsPopup;
