import { Button, Stack } from '@mui/material'

import { useMutation, useQuery } from 'react-query'
import { NoDataIllustration } from '..'
import { noDevices } from '../../assets/images'
import axios from '../../config/axios'
import useConfirm from '../PopupConfirm/useConfirm'
import Spinner from '../Spinner'
import { DeviceInformationCard } from './DeviceInformationCard'

const ActiveDevices = ({ close }) => {
  const { isConfirmed } = useConfirm()
  const {
    data: activeSessions,
    isLoading,
    isRefetching,
    refetch,
  } = useQuery('activeDevices', () =>
    axios.get('/auth-server/auth/active-sessions').then((res) => res?.data),
  )

  const { mutate: logoutAllOtherDevices } = useMutation(
    () => axios.post('/auth-server/auth/logout-active-sessions'),
    {
      onSuccess: () => {
        close()
      },
    },
  )

  const handleLogoutAllOtherDevices = async () => {
    const confirm = await isConfirmed(
      'Are you sure you want to logout from all other devices?',
    )
    if (confirm) {
      logoutAllOtherDevices()
    }
  }
  if (isLoading || isRefetching) return <Spinner />
  if (activeSessions?.length == 0)
    return (
      <NoDataIllustration
        height="60vh"
        message="No active devices found"
        imageSrc={noDevices.default}
      />
    )
  return (
    <Stack height="60vh" padding="10px 50px" gap={3} alignItems="flex-end">
      <Button onClick={handleLogoutAllOtherDevices} sx={{ width: '300px' }}>
        Logout from All Other Devices
      </Button>
      {activeSessions?.map((sessionData) => (
        <DeviceInformationCard sessionData={sessionData} refetch={refetch} />
      ))}
    </Stack>
  )
}

export default ActiveDevices
