import { type FC, useEffect, useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';

import Divider from '@material-hu/mui/Divider';

import Button from '@material-hu/components/design-system/Buttons/Button';

import { conversationsRoutes } from 'src/pages/dashboard/Conversations/routes';
import { type Member } from 'src/pages/dashboard/Conversations/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

import SelectGroupInfo from './components/ConversationsNew/SelectGroupInfo';
import SelectMembers from './components/ConversationsNew/SelectMembers';
import CloseActionHeader from './components/shared/CloseActionHeader';
import SidebarConversations from './components/shared/SidebarConversations';
import { useCreateGroup } from './hooks/useConversationsQueries';

const DEFAULT_VALUES: {
  filter: string;
  users: Member[];
  picture: string;
  name: string;
} = {
  filter: '',
  users: [],
  picture: '',
  name: '',
};

const ConversationsNewGroup: FC = () => {
  const [step, setStep] = useState(0);
  const { t } = useLokaliseTranslation(['chat', 'general']);
  const navigate = useNavigate();
  const createGroupMutation = useCreateGroup();

  const form = useForm({
    defaultValues: DEFAULT_VALUES,
  });
  const { users, name } = form.watch();
  const steps = [
    {
      id: 'participants',
      component: <SelectMembers />,
    },
    {
      id: 'info',
      component: <SelectGroupInfo />,
    },
  ];

  const isFinalStep = step === steps.length - 1;

  const handleOnClick = () => navigate(conversationsRoutes.conversations());

  const handleNext = (values: any) => {
    if (isFinalStep) {
      createGroupMutation.mutate({
        ...values,
        picture: values.picture || null,
        users: users.map(user => user.id.toString()),
      });
      return;
    }
    setStep(step + 1);
  };

  useEffect(() => {
    if (step === 1) {
      form.setFocus('name');
    }
  }, [step, form]);

  const handleBack = () => {
    setStep(step - 1);
  };

  const currentStep = steps[step];

  return (
    <SidebarConversations
      title={t(
        !step ? 'chat:groups.create.add_members' : 'chat:groups.new_group',
      )}
      onBack={handleBack}
      step={step}
      variantTitle="globalM"
      subtitle={
        !step
          ? t('chat:groups.create.select_members', { count: users.length })
          : ''
      }
      callToActionHeader={<CloseActionHeader onClose={handleOnClick} />}
    >
      <FormProvider {...form}>{currentStep.component}</FormProvider>
      <Divider />
      <Button
        loading={createGroupMutation.isLoading}
        disabled={Boolean(step) && !name}
        sx={{ mx: 2, my: 3 }}
        variant="primary"
        onClick={form.handleSubmit(handleNext)}
      >
        {t(isFinalStep ? 'chat:groups.create.cta' : 'general:next')}
      </Button>
    </SidebarConversations>
  );
};

export default ConversationsNewGroup;
