import { useEffect, type FC } from 'react';
import { Box, CircularProgress, MenuItem, Select, Typography } from '@mui/material';
import { useProfileStore } from '../../store/useStore';

/** A compact dropdown for switching the active profile (the subject of care
 *  whose data the dashboard shows). Sits in the AppBar. Triggers `loadProfiles`
 *  on mount so the list + per-profile DEKs are ready. */
export const ProfileSwitcher: FC = () => {
  const { profiles, activeProfileId, isLoading, loadProfiles, setActiveProfile } =
    useProfileStore();

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

  if (profiles.length === 0) {
    return isLoading ? (
      <Box sx={{ display: 'flex', alignItems: 'center' }}>
        <CircularProgress size={18} sx={{ color: 'common.white' }} />
      </Box>
    ) : (
      <Typography variant="body2" sx={{ opacity: 0.7, mr: 2 }}>
        No profile
      </Typography>
    );
  }

  return (
    <Select
      size="small"
      value={activeProfileId ?? ''}
      onChange={(e) => setActiveProfile(e.target.value)}
      sx={{
        mr: 2,
        color: 'common.white',
        '.MuiOutlinedInput-notchedOutline': { borderColor: 'rgba(255,255,255,0.5)' },
        '.MuiSvgIcon-root': { color: 'common.white' },
      }}
    >
      {profiles.map((p) => (
        <MenuItem key={p.profile_id} value={p.profile_id}>
          {p.name || p.relationship || p.profile_id}
        </MenuItem>
      ))}
    </Select>
  );
};

export default ProfileSwitcher;
