'use client';

import BaseButton from '@/components/ui-kit/BaseButton';
import BaseInput from '@/components/ui-kit/BaseInput';
import { party_requests } from '@/data/party/party.requests';
import { pageLinks } from '@/helpers/constants';
import useInput from '@/hooks/useInput';
import { useMyTranslation } from '@/hooks/useMyTranslation';
import { notifyUnknownError } from '@/services/notification';
import { Box, Stack, Typography } from '@mui/material';
import { useRouter } from 'next/navigation';
import React, { useState } from 'react';
import { useLocale } from 'use-intl';

type Props = {
    initialValues?: {
        id: number;
        party_name: string;
    };
};

const DashboardCreatePartyPage = ({ initialValues }: Props) => {
    const editMode = !!initialValues && !!initialValues.id;
    const t = useMyTranslation();
    const router = useRouter();
    const locale = useLocale();
    const partyNameInput = useInput(editMode ? initialValues.party_name : '');
    const [loading, setLoading] = useState(false);

    const onSubmit: React.FormEventHandler<HTMLFormElement> = async event => {
        event.preventDefault();
        try {
            setLoading(true);
            if (editMode) {
                await party_requests.update({ name: partyNameInput.value, id: initialValues.id });
            } else {
                await party_requests.create({ name: partyNameInput.value });
            }
            router.push(`/${locale}` + pageLinks.dashboard.parties.index);
        } catch (error) {
            notifyUnknownError(error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Box
            width={1}
            mb={3}
            sx={{
                padding: '28px',
                borderRadius: '16px',
                backgroundColor: '#fff',
            }}
        >
            <Box component={'form'} onSubmit={onSubmit}>
                <Typography variant='h5' mb={3.5}>
                    {editMode ? t('update_party') : t('create_party')}
                </Typography>

                <Stack spacing={2} maxWidth={340} mb={3}>
                    <Typography fontSize={'18px'} fontWeight={500} color='#5D5850'>
                        {t('party_name')}
                    </Typography>
                    <BaseInput placeholder={t('party_name')} value={partyNameInput.value} onChange={partyNameInput.onChange} />
                </Stack>

                <BaseButton type='submit' colorVariant='blue' loading={loading}>
                    {editMode ? t('update') : t('create')}
                </BaseButton>
            </Box>
        </Box>
    );
};

export default DashboardCreatePartyPage;
