/* eslint-disable @next/next/no-img-element */
import {
  mdiAccountCircle,
  mdiAccountTie,
  mdiChartTimelineVariant,
  mdiCheckCircleOutline,
  mdiEmailOutline,
  mdiLockReset,
  mdiPhoneOutline,
  mdiShieldAccountOutline,
  mdiStoreCogOutline,
  mdiUpload,
} from '@mdi/js';
import Head from 'next/head';
import React, { ReactElement, useEffect, useMemo, useState } from 'react';
import { toast } from 'react-toastify';

import BaseButton from '../components/BaseButton';
import BaseButtons from '../components/BaseButtons';
import BaseIcon from '../components/BaseIcon';
import CardBox from '../components/CardBox';
import FormField from '../components/FormField';
import FormImagePicker from '../components/FormImagePicker';
import LayoutAuthenticated from '../layouts/Authenticated';
import SectionMain from '../components/SectionMain';
import SectionTitleLineWithButton from '../components/SectionTitleLineWithButton';
import { Field, Form, Formik } from 'formik';
import { SelectField } from '../components/SelectField';
import { SwitchField } from '../components/SwitchField';
import { findMe } from '../stores/authSlice';
import { getPageTitle } from '../config';
import { update } from '../stores/users/usersSlice';
import { useAppDispatch, useAppSelector } from '../stores/hooks';
import { hasPermission } from '../helpers/userPermissions';

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

const fieldClass =
  'h-12 rounded-xl border border-slate-300 bg-white px-4 text-slate-950 outline-none focus:border-emerald-500 focus:ring-2 focus:ring-emerald-100';

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

  useEffect(() => {
    if (currentUser?.id && typeof currentUser === 'object') {
      const nextInitialValues = { ...initVals };

      Object.keys(initVals).forEach((fieldName) => {
        nextInitialValues[fieldName] =
          currentUser[fieldName] ?? initVals[fieldName];
      });

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

  const avatarUrl = currentUser?.avatar?.[0]?.publicUrl;
  const roleName = currentUser?.app_role?.name || 'Role pending';
  const canManageUserAccess =
    !!currentUser &&
    hasPermission(currentUser, ['READ_ROLES', 'UPDATE_USERS']);
  const fullName = useMemo(() => {
    const name = [initialValues.firstName, initialValues.lastName]
      .filter(Boolean)
      .join(' ');

    return name || currentUser?.email || 'Workspace user';
  }, [currentUser?.email, initialValues.firstName, initialValues.lastName]);

  const initials = useMemo(() => {
    return fullName
      .split(' ')
      .filter(Boolean)
      .slice(0, 2)
      .map((part) => part[0])
      .join('')
      .toUpperCase();
  }, [fullName]);

  async function handleSubmit(data) {
    if (!currentUser?.id) {
      throw new Error('Cannot update profile without current user id');
    }

    const payload = { ...data };

    if (!canManageUserAccess) {
      delete payload.app_role;
      delete payload.disabled;
      delete payload.password;
    }

    if (!payload.password) {
      delete payload.password;
    }

    await dispatch(update({ id: currentUser.id, data: payload }));
    await dispatch(findMe());
    toast('Profile was updated!', { type: 'success' });
  }

  return (
    <>
      <Head>
        <title>{getPageTitle('Profile')}</title>
      </Head>
      <SectionMain>
        <SectionTitleLineWithButton
          icon={mdiChartTimelineVariant}
          title='Profile'
          main
        >
          <div className='flex flex-wrap gap-2'>
            <BaseButton
              href='/dashboard'
              color='info'
              label='Operations dashboard'
            />
          </div>
        </SectionTitleLineWithButton>

        <div className='grid gap-6 xl:grid-cols-[420px_minmax(0,1fr)]'>
          <div className='space-y-5'>
            <CardBox cardBoxClassName='p-0'>
              <div className='bg-slate-950 p-6 text-white'>
                <p className='text-xs font-semibold uppercase tracking-[0.24em] text-emerald-300'>
                  Northstar identity
                </p>
                <p className='mt-3 text-sm leading-6 text-slate-300'>
                  Profile details for the supplier operations workspace.
                </p>
              </div>

              <div className='p-6'>
                <div className='flex items-start gap-4'>
                  <div className='inline-flex h-24 w-24 flex-none items-center justify-center overflow-hidden rounded-2xl border border-slate-200 bg-slate-100 text-3xl font-semibold text-slate-700 shadow-sm'>
                    {avatarUrl ? (
                      <img
                        src={avatarUrl}
                        alt={`${fullName} avatar`}
                        className='h-full w-full object-cover'
                      />
                    ) : (
                      initials || 'NS'
                    )}
                  </div>

                  <div className='min-w-0 pt-1'>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-emerald-700'>
                      Signed-in user
                    </p>
                    <h2 className='mt-2 break-words text-2xl font-semibold text-slate-950'>
                      {fullName}
                    </h2>
                    <p className='mt-2 break-all text-sm text-slate-500'>
                      {currentUser?.email || 'Email pending'}
                    </p>
                  </div>
                </div>

                <div className='mt-6 grid gap-3'>
                  <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                    <div className='flex items-center gap-3'>
                      <span className='inline-flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-50 text-emerald-700'>
                        <BaseIcon path={mdiShieldAccountOutline} size={22} />
                      </span>
                      <div>
                        <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-400'>
                          Access role
                        </p>
                        <p className='mt-1 font-semibold text-slate-950'>
                          {roleName}
                        </p>
                      </div>
                    </div>
                  </div>

                  <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                    <div className='flex items-center gap-3'>
                      <span className='inline-flex h-10 w-10 items-center justify-center rounded-xl bg-emerald-50 text-emerald-700'>
                        <BaseIcon path={mdiCheckCircleOutline} size={22} />
                      </span>
                      <div>
                        <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-400'>
                          Account status
                        </p>
                        <p className='mt-1 font-semibold text-slate-950'>
                          {initialValues.disabled ? 'Disabled' : 'Active'}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </CardBox>

            <CardBox>
              <p className='text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700'>
                Workspace context
              </p>
              <div className='mt-5 space-y-4'>
                <div className='flex gap-3'>
                  <span className='inline-flex h-10 w-10 flex-none items-center justify-center rounded-xl bg-slate-50 text-emerald-700 shadow-sm'>
                    <BaseIcon path={mdiStoreCogOutline} size={22} />
                  </span>
                  <div>
                    <p className='font-semibold text-slate-950'>
                      Supplier operations
                    </p>
                    <p className='mt-1 text-sm leading-6 text-slate-500'>
                      This profile controls identity and access inside the
                      catalog, pricing, orders, and fulfillment admin.
                    </p>
                  </div>
                </div>

                <div className='flex gap-3'>
                  <span className='inline-flex h-10 w-10 flex-none items-center justify-center rounded-xl bg-slate-50 text-emerald-700 shadow-sm'>
                    <BaseIcon path={mdiAccountTie} size={22} />
                  </span>
                  <div>
                    <p className='font-semibold text-slate-950'>
                      Buyer-facing responsibility
                    </p>
                    <p className='mt-1 text-sm leading-6 text-slate-500'>
                      Keep name, phone, and avatar current so buyer teams can
                      recognize account owners in the portal.
                    </p>
                  </div>
                </div>
              </div>
            </CardBox>
          </div>

          <Formik
            enableReinitialize
            initialValues={initialValues}
            onSubmit={(values) => handleSubmit(values)}
          >
            <Form className='space-y-6'>
              <CardBox>
                <div className='mb-6 flex flex-col gap-3 border-b border-slate-100 pb-5 md:flex-row md:items-start md:justify-between'>
                  <div>
                    <p className='text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700'>
                      Profile details
                    </p>
                    <h3 className='mt-2 text-2xl font-semibold text-slate-950'>
                      Contact identity
                    </h3>
                    <p className='mt-2 max-w-2xl text-sm leading-6 text-slate-500'>
                      Update the information that appears in the supplier admin
                      and buyer-support workflows.
                    </p>
                  </div>
                  <div className='rounded-xl border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-600'>
                    <span className='font-semibold text-slate-950'>Role:</span>{' '}
                    {roleName}
                  </div>
                </div>

                <div className='grid gap-6 lg:grid-cols-[minmax(0,1fr)_220px]'>
                  <div className='grid gap-x-4 md:grid-cols-2'>
                    <FormField label='First name'>
                      <Field
                        name='firstName'
                        placeholder='First name'
                        className={fieldClass}
                      />
                    </FormField>

                    <FormField label='Last name'>
                      <Field
                        name='lastName'
                        placeholder='Last name'
                        className={fieldClass}
                      />
                    </FormField>

                    <FormField label='Phone number' icons={[mdiPhoneOutline]}>
                      <Field
                        name='phoneNumber'
                        placeholder='Phone number'
                        className={fieldClass}
                      />
                    </FormField>

                    <div className='md:col-span-2'>
                      <FormField label='Email' icons={[mdiEmailOutline]}>
                        <Field
                          name='email'
                          placeholder='Email'
                          disabled
                          className={fieldClass}
                        />
                      </FormField>
                    </div>
                  </div>

                  <div className='rounded-2xl border border-slate-200 bg-slate-50 p-4'>
                    <p className='text-xs font-semibold uppercase tracking-[0.18em] text-slate-400'>
                      Avatar
                    </p>
                    <div className='mt-4 flex items-center gap-4 lg:block'>
                      <div className='inline-flex h-20 w-20 items-center justify-center overflow-hidden rounded-2xl bg-white text-2xl font-semibold text-slate-700 shadow-sm lg:h-28 lg:w-28'>
                        {avatarUrl ? (
                          <img
                            src={avatarUrl}
                            alt={`${fullName} avatar preview`}
                            className='h-full w-full object-cover'
                          />
                        ) : (
                          initials || 'NS'
                        )}
                      </div>
                      <div className='min-w-0 flex-1 lg:mt-4'>
                        <Field
                          label='Upload avatar'
                          color='info'
                          icon={mdiUpload}
                          path='users/avatar'
                          name='avatar'
                          id='avatar'
                          schema={{
                            size: undefined,
                            formats: undefined,
                          }}
                          component={FormImagePicker}
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </CardBox>

              <CardBox>
                <div className='mb-6 border-b border-slate-100 pb-5'>
                  <p className='text-xs font-semibold uppercase tracking-[0.2em] text-emerald-700'>
                    Access and security
                  </p>
                  <h3 className='mt-2 text-2xl font-semibold text-slate-950'>
                    Role, account state, and password
                  </h3>
                  <p className='mt-2 max-w-2xl text-sm leading-6 text-slate-500'>
                    Keep operational access intentional. These fields affect how
                    the user moves through buyer, catalog, order, and system
                    modules.
                  </p>
                </div>

                <div className='grid gap-x-4 md:grid-cols-2'>
                  {canManageUserAccess ? (
                    <>
                      <FormField label='App role' labelFor='app_role'>
                        <Field
                          name='app_role'
                          id='app_role'
                          component={SelectField}
                          options={initialValues.app_role}
                          itemRef='roles'
                          showField='name'
                        />
                      </FormField>

                      <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                        <FormField label='Disabled' labelFor='disabled'>
                          <Field
                            name='disabled'
                            id='disabled'
                            component={SwitchField}
                          />
                        </FormField>
                        <p className='text-sm leading-6 text-slate-500'>
                          Disabling an account should be reserved for
                          offboarding, access review, or compromised
                          credentials.
                        </p>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                        <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-400'>
                          App role
                        </p>
                        <p className='mt-2 font-semibold text-slate-950'>
                          {roleName}
                        </p>
                      </div>

                      <div className='rounded-xl border border-slate-200 bg-slate-50 p-4'>
                        <p className='text-xs font-semibold uppercase tracking-[0.16em] text-slate-400'>
                          Account status
                        </p>
                        <p className='mt-2 font-semibold text-slate-950'>
                          {initialValues.disabled ? 'Disabled' : 'Active'}
                        </p>
                      </div>
                    </>
                  )}

                  <div className='md:col-span-2'>
                    <FormField label='New password' icons={[mdiLockReset]}>
                      <Field
                        name='password'
                        type='password'
                        placeholder='Optional new password'
                        className={fieldClass}
                      />
                    </FormField>
                  </div>
                </div>
              </CardBox>

              <CardBox>
                <div className='flex flex-col gap-4 md:flex-row md:items-center md:justify-between'>
                  <div className='flex items-start gap-3'>
                    <span className='inline-flex h-11 w-11 flex-none items-center justify-center rounded-xl bg-emerald-50 text-emerald-700'>
                      <BaseIcon path={mdiAccountCircle} size={24} />
                    </span>
                    <div>
                      <p className='font-semibold text-slate-950'>
                        Save profile changes
                      </p>
                      <p className='mt-1 text-sm leading-6 text-slate-500'>
                        Changes are applied to this account and refreshed in the
                        current session.
                      </p>
                    </div>
                  </div>

                  <BaseButtons>
                    <BaseButton
                      type='submit'
                      color='info'
                      label={isFetching ? 'Saving...' : 'Save profile'}
                      disabled={isFetching}
                    />
                    <BaseButton
                      type='reset'
                      color='info'
                      outline
                      label='Reset'
                    />
                  </BaseButtons>
                </div>
              </CardBox>
            </Form>
          </Formik>
        </div>
      </SectionMain>
    </>
  );
};

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

export default Profile;
