import { mdiUpload } from '@mdi/js';
import { Field, Form, Formik } from 'formik';
import Head from 'next/head';
import Image from 'next/image';
import { useRouter } from 'next/router';
import React, { ReactElement, useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import FormImagePicker from '../components/FormImagePicker';
import { SelectField } from '../components/SelectField';
import { SwitchField } from '../components/SwitchField';
import { getPageTitle } from '../config';
import LayoutAuthenticated from '../layouts/Authenticated';
import { findMe } from '../stores/authSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { update } from '../stores/users/usersSlice';

type ProfileValues = {
  firstName: string;
  lastName: string;
  phoneNumber: string;
  email: string;
  app_role: any;
  disabled: boolean;
  avatar: any[];
  password: string;
};

const initVals: ProfileValues = {
  firstName: '',
  lastName: '',
  phoneNumber: '',
  email: '',
  app_role: '',
  disabled: false,
  avatar: [],
  password: '',
};

function Panel({
  children,
  className = '',
}: {
  children: React.ReactNode;
  className?: string;
}) {
  return (
    <section
      className={`rounded-none border border-[#19192d]/10 bg-white ${className}`}
    >
      {children}
    </section>
  );
}

function FieldWrap({
  label,
  children,
}: {
  label: string;
  children: React.ReactNode;
}) {
  return (
    <label className='block'>
      <span className='mb-2 block text-sm font-semibold text-[#19192d]'>
        {label}
      </span>
      {children}
    </label>
  );
}

const inputClassName =
  'w-full rounded-none border border-[#19192d]/10 bg-[#fffdf9] px-4 py-3 text-sm text-[#19192d] outline-none focus:border-[#35b7a5] focus:ring-2 focus:ring-[#35b7a5]/15 disabled:bg-[#fffdf9] disabled:text-[#72798a]';

const EditUsers = () => {
  const { currentUser } = useAppSelector((state) => state.auth);
  const router = useRouter();
  const dispatch = useAppDispatch();
  const [initialValues, setInitialValues] = useState(initVals);

  useEffect(() => {
    if (currentUser?.id && typeof currentUser === 'object') {
      const newInitialVal = { ...initVals } as Record<string, any>;

      Object.keys(initVals).forEach((key) => {
        newInitialVal[key] = currentUser[key];
      });

      setInitialValues(newInitialVal);
    }
  }, [currentUser]);

  const handleSubmit = async (data: ProfileValues) => {
    await dispatch(update({ id: currentUser.id, data }));
    await dispatch(findMe());
    await router.push('/users/users-list');
    toast('Profile was updated!', { type: 'success' });
  };

  const avatarUrl = currentUser?.avatar?.[0]?.publicUrl;

  return (
    <>
      <Head>
        <title>{getPageTitle('Edit profile')}</title>
      </Head>

      <main className='mx-auto max-w-7xl px-6 py-6'>
        <div className='mb-4 rounded-none bg-[#19192d] p-7 text-white'>
          <div className='flex items-center gap-3 text-[#35b7a5]'>
            <span className='text-lg'>●</span>
            <span className='text-xs font-semibold uppercase tracking-[0.22em]'>
              Account
            </span>
          </div>
          <h1 className='mt-3 text-xl font-semibold'>Profile</h1>
          <p className='mt-2 max-w-2xl text-sm leading-6 text-[#fffdf9]'>
            Update your workspace profile, avatar, role, and password.
          </p>
        </div>

        <Panel className='p-5'>
          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form className='grid gap-5'>
              <div className='grid gap-5 xl:grid-cols-[180px_1fr]'>
                <div>
                  <p className='text-sm font-semibold text-[#19192d]'>Avatar</p>
                  <div className='mt-3 flex h-32 w-32 items-center justify-center overflow-hidden rounded-none border border-[#19192d]/10 bg-[#fffdf9]'>
                    {avatarUrl ? (
                      <Image
                        className='h-full w-full object-cover object-center'
                        src={avatarUrl}
                        alt='Avatar'
                        width={128}
                        height={128}
                        unoptimized
                      />
                    ) : (
                      <span className='text-3xl font-semibold text-[#35b7a5]'>
                        {currentUser?.firstName?.[0] ||
                          currentUser?.email?.[0] ||
                          'U'}
                      </span>
                    )}
                  </div>
                  <div className='mt-4'>
                    <Field
                      label='Avatar'
                      color='info'
                      icon={mdiUpload}
                      path='users/avatar'
                      name='avatar'
                      id='avatar'
                      schema={{
                        size: undefined,
                        formats: undefined,
                      }}
                      component={FormImagePicker}
                    />
                  </div>
                </div>

                <div className='grid gap-6 md:grid-cols-2 xl:grid-cols-3'>
                  <FieldWrap label='First name'>
                    <Field
                      className={inputClassName}
                      name='firstName'
                      placeholder='First name'
                    />
                  </FieldWrap>

                  <FieldWrap label='Last name'>
                    <Field
                      className={inputClassName}
                      name='lastName'
                      placeholder='Last name'
                    />
                  </FieldWrap>

                  <FieldWrap label='Phone number'>
                    <Field
                      className={inputClassName}
                      name='phoneNumber'
                      placeholder='Phone number'
                    />
                  </FieldWrap>

                  <FieldWrap label='Email'>
                    <Field
                      className={inputClassName}
                      name='email'
                      placeholder='Email'
                      disabled
                    />
                  </FieldWrap>

                  <FieldWrap label='App role'>
                    <Field
                      name='app_role'
                      id='app_role'
                      component={SelectField}
                      options={initialValues.app_role}
                      itemRef='roles'
                      showField='name'
                    />
                  </FieldWrap>

                  <FieldWrap label='Password'>
                    <Field
                      className={inputClassName}
                      name='password'
                      placeholder='New password'
                    />
                  </FieldWrap>

                  <div className='md:col-span-2 xl:col-span-3'>
                    <FieldWrap label='Disabled'>
                      <Field
                        name='disabled'
                        id='disabled'
                        component={SwitchField}
                      />
                    </FieldWrap>
                  </div>
                </div>
              </div>

              <div className='flex flex-wrap justify-end gap-3 border-t border-[#19192d]/10 pt-5'>
                <button
                  type='button'
                  className='rounded-none border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold text-[#19192d]'
                  onClick={() => router.push('/users/users-list')}
                >
                  Cancel
                </button>
                <button
                  type='reset'
                  className='rounded-none border border-[#19192d]/10 bg-white px-4 py-2 text-sm font-semibold text-[#19192d]'
                >
                  Reset
                </button>
                <button
                  type='submit'
                  className='rounded-none bg-[#35b7a5] px-4 py-2 text-sm font-semibold text-white'
                >
                  Save profile
                </button>
              </div>
            </Form>
          </Formik>
        </Panel>
      </main>
    </>
  );
};

EditUsers.getLayout = function getLayout(page: ReactElement) {
  return <LayoutAuthenticated>{page}</LayoutAuthenticated>;
};

export default EditUsers;
