import { m } from "framer-motion";

import Box from "@mui/material/Box";
import Stack from "@mui/material/Stack";
import { alpha } from "@mui/material/styles";
import MenuItem from "@mui/material/MenuItem";
import IconButton from "@mui/material/IconButton";
import Typography from "@mui/material/Typography";
import { useRouter } from "@/hooks";
import { useMockedUser } from "@/hooks";
import { useAuthContext } from "@/hooks";
import { varHover } from "@/shared/components/animate";
import CustomPopover, { usePopover } from "@/shared/components/custom-popover";
import { paths } from "@/routes/paths";
import Tooltip from "@mui/material/Tooltip";
import { useSnackbar } from "notistack";

import {
  ButtonBase,
  FormControl,
  FormControlLabel,
  Radio,
  RadioGroup,
  Select,
  InputLabel,
  Divider,
} from "@mui/material";
import { useState, useEffect } from "react";
import { TokenPayload } from "@/shared/types/user";
import { getTokenInfo } from "@/utils/token";
import axiosInstance from "@/utils/axios";
import { useSettingsContext } from "@/shared/components/settings";
import Iconify from "@/shared/components/iconify";
import { getUserByEmail, useGetUserByEmail } from "@/shared/api/user";

// ----------------------------------------------------------------------
const ICONS = {
  dashboard: <Iconify icon="solar:home-2-outline" />,
  user: <Iconify icon="solar:users-group-rounded-outline" />,
  invoice: <Iconify icon="solar:bill-list-outline" />,
  settings: <Iconify icon="solar:settings-bold-duotone" />,
  logout: <Iconify icon="solar:logout-2-outline" />,
  theme: <Iconify icon="mdi:palette-outline" />
};
const OPTIONS = [
  {
    label: "Home",
    linkTo: "/",
    icon: ICONS.dashboard,
  },
  {
    label: "Profile",
    linkTo: paths.dashboard.user.demo.details,
    icon: <Iconify icon="solar:user-rounded-outline" />,
  },
  {
    label: "My Team",
    linkTo: paths.dashboard.user.root,
    icon: ICONS.user,
  },
  {
    label: "My Bills",
    linkTo: paths.dashboard.invoice.root,
    icon: ICONS.invoice,
  },
  {
    label: 'Theme',
    linkTo: 'settings',
    icon: ICONS.theme,
  },
];
// ----------------------------------------------------------------------

interface AgencyType {
  id: string;
  name: string;
  role: string;
  state: string;
}

export default function AccountPopover() {
  const roles = JSON.parse(localStorage.getItem("role") || "[]");
  const isAdmin = roles.includes("ADMIN");
  const isManager = roles.includes("MANAGER");
  const userEmail = localStorage.getItem("email") || "";
  const router = useRouter();
  const settings = useSettingsContext();
  const [selectedAgency, setSelectedAgency] = useState<string | null>(null);
  const [agencies, setAgencies] = useState<AgencyType[]>([]);
  const { enqueueSnackbar } = useSnackbar();
  const [userData, setUserData] = useState<any>(null);

  const agencyRoles = JSON.parse(localStorage.getItem("agency_role") || "{}");
  const agencyList = Object.keys(agencyRoles).map((id) => ({
    id,
    role: agencyRoles[id],
  })) as Array<Pick<AgencyType, 'id' | 'role'>>;
  const fetchUserData = async () => {
    try {
      if (!userEmail) return;

      const data = await getUserByEmail(userEmail);
      setUserData(data);
    } catch (error) {
      console.error("Error fetching user data:", error);
    }
  };


  useEffect(() => {
    fetchUserData();
  }, [userEmail]);

  const fetchAgencyNames = async () => {
    try {
      if (agencyList.length === 0) {
        console.log("No agencies found in agencyList");
        return;
      }

      const agenciesData = await Promise.all(
        agencyList.map(async (agency) => {
          const response = await axiosInstance.get(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/agency/${agency.id}`
          );
          return {
            id: agency.id,
            name: response.data.name,
            role: agencyRoles[agency.id],
            state: response.data.status
          } as AgencyType;
        })
      );
      setAgencies(agenciesData);

    } catch (error: any) {
      console.error("Error fetching agency data:", error?.message || error);
    }
  };

  useEffect(() => {
    fetchAgencyNames();
  }, []);

  useEffect(() => {
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "agency_role") {
        fetchAgencyNames();
      }
    };

    window.addEventListener('storage', handleStorageChange);
    return () => window.removeEventListener('storage', handleStorageChange);
  }, []);

  useEffect(() => {
    if (agencies.length > 0) {
      const storedAgency = localStorage.getItem("selectedAgency");
      const agencyExists = agencies.some(agency => agency.id === storedAgency);

      if (!storedAgency || !agencyExists) {
        // Find the first agency with CLIENT role if it exists
        const clientAgency = agencies.find(agency => agency.role.toUpperCase() === 'CLIENT');
        // Otherwise use the first agency
        const defaultAgency = clientAgency || agencies[0];

        console.log('Setting default agency:', defaultAgency);

        const agencyDetails = {
          id: defaultAgency.id,
          name: defaultAgency.name,
          role: defaultAgency.role
        };

        localStorage.setItem("selectedAgency", defaultAgency.id);
        localStorage.setItem("selectedAgencyDetails", JSON.stringify(agencyDetails));
        setSelectedAgency(defaultAgency.id);

        // Trigger agency change event with the correct role
        const agencyChangeEvent = new CustomEvent('agencyChange', {
          detail: agencyDetails
        });
        window.dispatchEvent(agencyChangeEvent);
      } else {
        // Use the stored agency but make sure to set the correct role
        const storedAgencyData = agencies.find(agency => agency.id === storedAgency);
        if (storedAgencyData) {
          const agencyDetails = {
            id: storedAgencyData.id,
            name: storedAgencyData.name,
            role: storedAgencyData.role
          };

          localStorage.setItem("selectedAgencyDetails", JSON.stringify(agencyDetails));
          setSelectedAgency(storedAgency);

          // Trigger agency change event with the correct role
          const agencyChangeEvent = new CustomEvent('agencyChange', {
            detail: agencyDetails
          });
          window.dispatchEvent(agencyChangeEvent);
        }
      }
    }
  }, [agencies]);

  const { user1 } = useMockedUser();

  const { logout } = useAuthContext();

  const popover = usePopover();

  const handleLogout = async () => {
    const token = localStorage.getItem("token");

    if (token) {
      const infosUser: TokenPayload = getTokenInfo(token);

      try {
        localStorage.removeItem('email');
        localStorage.removeItem('selectedAgency');
        localStorage.removeItem("token");
        localStorage.removeItem("refreshToken");
        localStorage.removeItem("expirationDurationInSec");

        popover.onClose();

        router.replace("/auth/jwt/login");
      } catch (error) {
        console.error("An error occurred during the logout process:", error);
      }
    } else {
      console.warn("No token found in localStorage for logout.");
    }
  };
  const handleAgencyChange = async (event: any) => {
    const newAgencyId = event.target.value;

    try {
      const selectedAgency = agencies.find(agency => agency.id === newAgencyId);
      if (!selectedAgency) {
        throw new Error('Selected agency not found');
      }
      const role = agencyRoles[newAgencyId];

      const agencyDetails = {
        id: selectedAgency.id,
        name: selectedAgency.name,
        role: role
      };

      // Clear previous agency data
      localStorage.removeItem('selectedAgencyDetails');
      localStorage.removeItem('selectedAgency');

      // Set new agency data
      localStorage.setItem("selectedAgency", newAgencyId);
      localStorage.setItem("selectedAgencyDetails", JSON.stringify(agencyDetails));

      setSelectedAgency(newAgencyId);

      // Dispatch agency change event
      const agencyChangeEvent = new CustomEvent('agencyChange', {
        detail: agencyDetails
      });
      window.dispatchEvent(agencyChangeEvent);

      // Add success notification
      enqueueSnackbar(`Successfully switched to ${selectedAgency.name}`, {
        variant: 'success',
        anchorOrigin: {
          vertical: 'top',
          horizontal: 'right',
        },
        autoHideDuration: 3000,
      });

      // Force a page reload to refresh the dashboard
      window.location.href = '/dashboard'; // Use href instead of reload()

    } catch (error) {
      console.error('Error switching agency:', error);
      enqueueSnackbar('Failed to switch agency', {
        variant: 'error',
        anchorOrigin: {
          vertical: 'top',
          horizontal: 'right',
        }
      });
    }
  };
  
  const handleClickItem = (path: string) => {
    popover.onClose();
    if (path === 'settings') {
      settings.onToggle();
    } else {
      router.push(path);
    }
  };

  const handleListAgency = () => {
    popover.onClose();
    router.push(paths.dashboard.agency.list);
  };
  const handleNewAgency = () => {
    popover.onClose();
    router.push(paths.dashboard.agency.create);
  };
  const handleNewUserAgency = () => {
    popover.onClose();
    router.push(paths.dashboard.agency.createUserAgency);
  };
  return (
    <>
      <IconButton
      component={m.button}
      whileTap="tap"
      whileHover="hover"
      variants={varHover(1.05)}
      onClick={popover.onOpen}
      sx={{
        width: 40,
        height: 40,
        background: (theme) => alpha(theme.palette.grey[500], 0.08),
      }}
    >
      <Iconify 
        icon="solar:settings-linear" 
        width={24}
        height={24}
      />
    </IconButton>

      <CustomPopover
        open={popover.open}
        onClose={popover.onClose}
        sx={{ width: 280, p: 0 }}
      >
        <Box sx={{ p: 2, pb: 1.5 }}>
          <Typography variant="subtitle2" noWrap>
            {userData ? `${userData.firstName} ${userData.lastName}` : user1?.displayName}
          </Typography>

          <Typography variant="body2" sx={{ color: "text.secondary" }} noWrap>
            {userData?.email || userEmail}
          </Typography>
        </Box>
        <Divider sx={{ borderStyle: "dashed" }} />
        {isAdmin || isManager ? (
        <>
          <Stack sx={{ p: 1 }}>
            <MenuItem onClick={handleNewAgency}>
              <Box component="span" sx={{ display: 'inline-flex', mr: 2 }}>
                <Iconify icon="solar:add-circle-outline" />
              </Box>
              Create Workspace
            </MenuItem>
            
            <MenuItem onClick={handleNewUserAgency}>
              <Box component="span" sx={{ display: 'inline-flex', mr: 2 }}>
                <Iconify icon="solar:user-plus-outline" />
              </Box>
              Add User Workspace
            </MenuItem>
          </Stack>
          <Divider sx={{ borderStyle: "dashed" }} />
        </>
     ) : null}

        <Divider sx={{ borderStyle: "dashed" }} />
        {agencies.length > 0 && (
          <>
            <Box sx={{ px: 2.5, pt: 2, pb: 1 }}>
              <Typography variant="subtitle2" color="text.secondary">
                Select Workspace
              </Typography>
            </Box>

            <MenuItem sx={{ p: 2 }}>
              <FormControl fullWidth variant="outlined" size="small">
                <Select
                  value={selectedAgency || ''}
                  onChange={handleAgencyChange}
                  sx={{
                    '& .MuiSelect-select': {
                      display: 'flex',
                      alignItems: 'center',
                      gap: 1,
                    },
                    backgroundColor: 'background.paper',
                  }}
                  MenuProps={{
                    PaperProps: {
                      sx: {
                        maxHeight: 260,
                        '& .MuiMenuItem-root': {
                          px: 1,
                          py: 1,
                          borderRadius: 1,
                          margin: '4px 8px',
                          width: 'calc(100% - 16px)',
                        },
                      },
                    },
                  }}
                >
     
                  {agencies.map((agency) => (
                    <MenuItem
                      key={agency.id}
                      value={agency.id}
                      sx={{
                        '&:hover': {
                          backgroundColor: 'action.hover',
                        },
                        ...(agency.id === selectedAgency && {
                          backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.08),
                        }),
                      }}
                    >
                      <Stack direction="row" alignItems="center" width="100%">
                        <Box
                          sx={{
                            width: 32,
                            height: 32,
                            flexShrink: 0,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            borderRadius: '50%',
                            backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.08),
                            mr: 1,
                          }}
                        >
                          <Typography variant="subtitle2" color="primary">
                            {agency.name.charAt(0).toUpperCase()}
                          </Typography>
                        </Box>

                        <Box sx={{ flexGrow: 1, minWidth: 0 }}>
                          <Typography variant="body2" noWrap>
                            {agency.name}
                          </Typography>
                          <Typography
                            variant="caption"
                            sx={{
                              color: 'primary.main',
                              backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.08),
                              px: 1,
                              py: 0.25,
                              borderRadius: 1,
                              display: 'inline-block',
                              mt: 0.5,
                            }}
                          >
                            {agency.role}
                          </Typography>
                        </Box>
                      </Stack>
                    </MenuItem>
                  ))}
                </Select>
              </FormControl>
            </MenuItem>
            <Divider sx={{ borderStyle: "dashed" }} />
          </>
        )}

  <MenuItem
  onClick={handleListAgency}
  sx={{ 
    mx: 1,
    my: 0.5,
    px: 1.5,
    py: 0.75,
    borderRadius: 1,
    '&:hover': { backgroundColor: 'action.hover' }
  }}
>
  <Box component="span" sx={{ display: 'inline-flex', mr: 2 }}>
    <Iconify icon="solar:buildings-3-outline" />
  </Box>
  Workspace Management
</MenuItem>
        <Stack sx={{ p: 1 }}>
          {OPTIONS.map((option) => (
            <MenuItem
              key={option.label}
              onClick={() => handleClickItem(option.linkTo)}
            >
              <Box component="span" sx={{ display: 'inline-flex', mr: 2 }}>
                {option.icon}
              </Box>
              {option.label}
            </MenuItem>
          ))}
        </Stack>
        <Divider sx={{ borderStyle: 'dashed', my: 1 }} />


        

<MenuItem
  onClick={handleLogout}
  sx={{ 
    p: 1,
    m: 1,
    color: 'error.main',
    '&:hover': {
      backgroundColor: 'action.hover',
    },
  }}
>
  <Box component="span" sx={{ display: 'inline-flex', mr: 2 }}>
    {ICONS.logout}
  </Box>
  Logout
</MenuItem>
      </CustomPopover>
    </>
  );
}
