import { Box, TextField, Typography, styled } from '@mui/material'
import { useState } from 'react'
import { InstitutionsStore } from '../../shared-state/InstitutionsStore'
import Image from '../Image/Image'

export default function InstitutionsDialog({ close }) {
  const [searchText, setSearchText] = useState('')
  const { institutions } = InstitutionsStore.useState((s) => s)
  const filteredInstitutions = institutions.filter((item) =>
    item.name.toLowerCase().includes(searchText.toLowerCase()),
  )

  return (
    <Box sx={{ padding: '20px' }}>
      <Typography variant="h6" textAlign={'center'}>
        Select an Institution
      </Typography>
      <TextField
        label="Search Institution"
        variant="outlined"
        margin="normal"
        value={searchText}
        onChange={(e) => setSearchText(e.target.value)}
      />
      <StyledInstitutionContainer>
        {filteredInstitutions?.map((item, index) => (
          <InstitutionCard institution={item} key={index} />
        ))}
      </StyledInstitutionContainer>
    </Box>
  )
}

const InstitutionCard = ({ institution }) => {
  const urlTenantKey = window.location.pathname.split('/')[1]
  const handleClick = () => {
    localStorage.setItem('institution_key', institution?.code)
    window.location.replace(
      `${window.location.origin}/${urlTenantKey}/${institution?.code}`,
    )
  }

  return (
    <StyledInstitutionCard onClick={handleClick}>
      <Image
        alt="logo"
        height={'100px'}
        width="100%"
        src={institution?.imageSquare?.url}
      />
      <Typography variant="body2">{institution?.name}</Typography>
    </StyledInstitutionCard>
  )
}

const StyledInstitutionCard = styled(Box)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  alignItems: 'center',
  gap: '20px',
  padding: '14px',
  border: '1px solid black',
  borderRadius: '10px',
  cursor: 'pointer',
  width: '200px',
  flexShrink: 0,
}))

export const StyledInstitutionContainer = styled(Box)(({ theme }) => ({
  marginTop: '20px',
  display: 'flex',
  justifyContent: 'center',
  padding: '20px',
  flexWrap: 'wrap',
  gap: '20px',
  '&::-webkit-scrollbar': {
    width: '0.5em',
    height: '0.5em',
    backgroundColor: 'rgba(0, 0, 0, 0.1)',
  },
  '&::-webkit-scrollbar-thumb': {
    backgroundColor: 'rgba(0, 0, 0, 0.2)',
    borderRadius: '3px',

    '&:hover': {
      background: 'rgba(0, 0, 0, 0.3)',
    },
  },
}))
