// mui
import { Container, Grid, Stack, Typography } from '@mui/material';
// components
import Page from '../../components/Page';
// utils
import useSettings from '../../hooks/useSettings';
// react
import { useNavigate, useParams } from 'react-router-dom';
import { useEffect, useState, useContext } from 'react';
import axios from '../../utils/axios';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
import CardPersonalInformation from '../../sections/employee-data/user-profile/CardPersonalInformation';
import CardFamilyInformation from '../../sections/employee-data/user-profile/CardFamilyInformation';
import { FamilyInformationtype, PersonalInformationType } from '../../@types/member';

// ----------------------------------------------------------------------

type UserProfileDataType = {
  person: PersonalInformationType;
  families: FamilyInformationtype[];
};

export default function UserProfile() {
  const { themeStretch } = useSettings();
  const navigate = useNavigate();
  const [data, setData] = useState<UserProfileDataType>();
  const [loading, setLoading] = useState(true);

  const { corporateValue } = useContext(UserCurrentCorporateContext);
  const { id } = useParams();

  useEffect(() => {
    (async () => {
      await axios
        .get(corporateValue + '/members/' + id)
        .then((response) => {
          setTimeout(() => {
            setData(response.data);
            setLoading(false);
          }, 1000);
        })
        .catch((error) => {
          if (error.response.data.statusCode === 404) {
            navigate(-1);
          } else {
            console.error(error);
          }
        });
    })();
  }, []);

  return (
    <Page title="Profile">
      <Container maxWidth={themeStretch ? false : 'xl'}>
        <Stack direction="row" alignItems="center" sx={{ marginBottom: 3 }}>
          <ArrowBackIosIcon sx={{ cursor: 'pointer' }} onClick={() => navigate(-1)} />
          <Typography variant="h5" sx={{ marginLeft: 2 }}>
            Profile
          </Typography>
        </Stack>
        <Grid container spacing={2}>
          {/* Row 1 */}
          <Grid item xs={12} md={12}>
            <CardPersonalInformation data={data?.person} />
          </Grid>
          <Grid item xs={12} md={12}>
            <CardFamilyInformation data={data?.families} loading={loading} />
          </Grid>
        </Grid>
      </Container>
    </Page>
  );
}
