import { useState } from 'react';
import {
Container,
Paper,
Title,
Text,
Stack,
Button,
Card,
Group,
Badge,
TextInput,
Modal,
Alert,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { useDisclosure } from '@mantine/hooks';
import { IconBuilding, IconPlus, IconAlertCircle } from '@tabler/icons-react';
import { useNavigate } from 'react-router-dom';
import api from '../../services/api';
import { useAuthStore } from '../../stores/authStore';
export function SelectOrgPage() {
const { organizations, setCurrentOrg, logout } = useAuthStore();
const navigate = useNavigate();
const [opened, { open, close }] = useDisclosure(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
// If no organizations in store (stale session), redirect to login
if (!organizations || organizations.length === 0) {
return (
No Organizations
Please log in again to refresh your session.
);
}
const form = useForm({
initialValues: { name: '', addressLine1: '', city: '', state: '', zipCode: '' },
validate: {
name: (v) => (v.length >= 2 ? null : 'Name required'),
},
});
// Filter out suspended/archived organizations (defense in depth)
const activeOrganizations = (organizations || []).filter(
(org: any) => !org.status || !['suspended', 'archived'].includes(org.status),
);
const handleSelect = async (org: any) => {
try {
const { data } = await api.post('/auth/switch-org', {
organizationId: org.id,
});
setCurrentOrg(data.organization, data.accessToken);
navigate('/dashboard');
} catch (err: any) {
setError(err.response?.data?.message || 'Failed to switch organization. Please try logging in again.');
}
};
const handleCreateOrg = async (values: typeof form.values) => {
setLoading(true);
setError('');
try {
const { data } = await api.post('/organizations', values);
// Switch to the new org
const switchRes = await api.post('/auth/switch-org', {
organizationId: data.id,
});
setCurrentOrg(
{ id: data.id, name: data.name, role: 'president' },
switchRes.data.accessToken,
);
close();
navigate('/');
} catch (err: any) {
setError(err.response?.data?.message || 'Failed to create organization');
} finally {
setLoading(false);
}
};
return (
Select Organization
Choose an HOA to manage or create a new one
{/* Filter out suspended/archived orgs (defense in depth — backend also filters) */}
{organizations.length > activeOrganizations.length && (
} color="yellow" variant="light" mt="md">
Some organizations are currently suspended or archived and are not shown.
)}
activeOrganizations.length ? 'sm' : 30}>
{activeOrganizations.map((org) => (
handleSelect(org)}
>
{org.name}
{org.role}
))}
}
onClick={open}
fullWidth
>
Create New HOA
);
}