import { Stack, Divider } from '@mantine/core';
import { showNotification } from '@mantine/notifications';
import type { GetServerSideProps, NextPage } from 'next';
import { useSession } from 'next-auth/react';
import { MyPageTitle } from 'ui';

import { getOneProperty } from '../../../../api/getProperties';
import { useUpdateProperty } from '../../../../api/updateProperty';
import Layout from '../../../../components/Layout';
import { PropertyForm } from '../../../../components/Property/PropertyForm';
import { ProtectedRoute } from '../../../../components/ProtectedRoute';
import usePageContentStyles from '../../../../styles/pageContentStyles';
import { IPropertyDTO, IPropertyForm, IPropertyImageDTO } from '../../../../types/dto';

type PropertyEditProps = {
  property?: IPropertyDTO;
  propertyImages?: IPropertyImageDTO[];
};

export const getServerSideProps: GetServerSideProps<PropertyEditProps> = async (
  context,
) => {
  const { params } = context;
  const propertyId = params?.propertyId as string;
  if (propertyId) {
    const property = await getOneProperty({ propertyId });
    return {
      props: {
        property,
      },
    };
  }
  return { props: {} };
};
const PropertyEdit: NextPage<PropertyEditProps> = (props) => {
  const { property } = props;
  const { classes: pageClasses } = usePageContentStyles();
  const sessionData = useSession();
  const updateProperty = useUpdateProperty({
    config: {
      onSuccess: () => {
        showNotification({
          message: 'Property updated successfully.',
        });
      },
    },
  });
  const onSubmit = (data: IPropertyForm) => {
    property &&
      updateProperty.mutate({
        body: data,
        jwt: sessionData.data?.user.jwt,
        propertyId: property._id,
      });
  };
  return (
    <Layout>
      <ProtectedRoute>
        {property ? (
          <Stack spacing="xs" p="xs" className={pageClasses.wrapper}>
            <MyPageTitle>Edit</MyPageTitle>
            <Divider p="xs"></Divider>
            <PropertyForm property={property} onSubmit={onSubmit} labelSubmit="Save" />
          </Stack>
        ) : (
          'Not found'
        )}
      </ProtectedRoute>
    </Layout>
  );
};

export default PropertyEdit;
