import { yupResolver } from '@hookform/resolvers/yup';
import {
  Button,
  FileInput,
  Input,
  Link,
  LoaderSpinner,
  Select
} from '@theme/components';
import { useSession } from 'next-auth/react';
import { useEffect, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { useAppSelector } from '@akinon/next/redux/hooks';
import {
  useGetContactSubjectsQuery,
  useGetOrdersQuery,
  useSendContactMutation
} from '@akinon/next/data/client/account';
import { ContactFormType } from '@akinon/next/types';
import * as yup from 'yup';
import { useLocalization } from '@akinon/next/hooks';

const contactFormSchema = (t) =>
  yup.object().shape({
    full_name: yup.string().required(t('account.contact.form.error.required')),
    email: yup
      .string()
      .email(t('account.contact.form.error.email_valid'))
      .required(t('account.contact.form.error.required')),
    phone: yup
      .string()
      .transform((value: string) => value.replace(/_/g, '').replace(/ /g, ''))
      .length(11, t('account.contact.form.error.phone_length'))
      .required(t('account.contact.form.error.required')),
    subject: yup.string().required(t('account.contact.form.error.required')),
    message: yup
      .string()
      .required(t('account.contact.form.error.required'))
      .min(10, t('account.contact.form.error.message_length'))
      .label('message'),
    order: yup
      .string()
      .nullable()
      .notRequired()
      .when('subject', {
        is: (value) => value === '2',
        then: yup.string().required(t('account.contact.form.error.required'))
      }),
    file: yup.mixed()
  });

const ContactForm = () => {
  const { t } = useLocalization();
  const { data: session, status } = useSession();

  const filteredOrders = [
    { label: t('account.contact.form.order.placeholder'), value: '' }
  ];
  const filteredSubjects = [
    { label: t('account.contact.form.subject.placeholder'), value: '' }
  ];
  const [selectedSubject, setSelectedSubject] = useState(null);
  const { user_phone_format } = useAppSelector((state) => state.config);

  const {
    data: contactSubject,
    isLoading: subjectLoading,
    isSuccess: subjectSuccess
  } = useGetContactSubjectsQuery();

  const {
    data: orders,
    isLoading: ordersLoading,
    isSuccess: ordersSuccess
  } = useGetOrdersQuery(
    {},
    {
      skip: status === 'unauthenticated' || status === 'loading'
    }
  );

  const [
    sendContact,
    { isSuccess: formSuccess, isLoading: isSubmitting, error: submitError }
  ] = useSendContactMutation();

  if (ordersSuccess) {
    orders?.results?.map((item) => {
      filteredOrders.push({ label: item.number, value: item.id.toString() });
    });
  }

  if (subjectSuccess) {
    contactSubject
      ?.filter((item) => {
        if (status === 'unauthenticated') {
          return !item.is_order_needed;
        }

        return item;
      })
      .forEach((item) => {
        filteredSubjects.push({ label: item.text, value: item.id });
      });
  }

  const {
    register,
    reset,
    handleSubmit,
    control,
    formState: { errors }
  } = useForm<ContactFormType>({
    resolver: yupResolver(contactFormSchema(t))
  });

  const onSubmit: SubmitHandler<ContactFormType> = (data) => {
    const formData = new FormData();

    Object.keys(data ?? {}).forEach((key) => {
      if (key === 'file' && data[key]) {
        formData.append(key, data[key][0]);
      } else if (data[key] && key !== 'file') {
        formData.append(key, data[key]);
      }
    });

    formData.append('subject', 'tdsadasdsa');
    formData.append('order', '2222');

    sendContact(formData);
  };

  const handleChange = (e) => {
    setSelectedSubject(e.target.value);
  };

  useEffect(() => {
    reset({
      full_name:
        session?.user?.firstName && session?.user?.lastName
          ? `${session?.user?.firstName} ${session?.user?.lastName}`
          : '',
      email: session?.user?.email,
      phone: session?.user?.phone
    });
  }, [session, reset]);

  return (
    <div className="max-w-lg mx-auto">
      <div className="flex flex-col text-black-750">
        {formSuccess ? (
          <div>
            <h3 className="text-3xl mb-5">
              {t('account.contact.form.success.title')}
            </h3>
            <p className="text-sm mb-4">
              {t('account.contact.form.success.description')}
            </p>
            <Link href={'/'} className="underline">
              {t('account.contact.form.success.button')}
            </Link>
          </div>
        ) : (
          <>
            <div>
              <h2 className="text-[40px] mb-8">
                {' '}
                {t('account.contact.header.title')}
              </h2>

              <div className="mb-16">
                <h3 className="mb-8 font-bold">{t('account.contact.hours')}</h3>
                <p> Monday – Friday: 10:00am – 7:30pm</p>
                <p>Saturday: 10:00am – 6:00pm</p>
                <p>Sunday: 11:00am – 6:00pm</p>
              </div>
            </div>

            <form
              onSubmit={handleSubmit(onSubmit)}
              className="flex flex-col gap-4"
            >
              <div className="flex flex-col gap-4 lg:flex-row">
                <div className="lg:w-1/2">
                  <Input
                    placeholder={t(
                      'account.contact.form.full_name.placeholder'
                    )}
                    {...register('full_name')}
                    error={errors.full_name}
                    className="h-12"
                    required
                  />
                </div>

                <div className="lg:w-1/2">
                  <Input
                    placeholder={t('account.contact.form.email.placeholder')}
                    type="email"
                    {...register('email')}
                    className="h-12"
                    error={errors.email}
                    required
                  />
                </div>
              </div>

              <div>
                <Input
                  placeholder={t('account.contact.form.phone.placeholder')}
                  type="tel"
                  className="h-12"
                  format={user_phone_format.replace(/9/g, '#')}
                  mask="_"
                  allowEmptyFormatting={true}
                  control={control}
                  {...register('phone')}
                  error={errors.phone}
                  required
                />
              </div>

              <div className="relative">
                {subjectLoading && <LoaderSpinner />}
                {subjectSuccess && (
                  <>
                    <Select
                      className="w-full h-12 border-gray-500 text-sm"
                      options={filteredSubjects}
                      {...register('subject')}
                      error={errors.subject}
                      onChange={handleChange}
                      required
                    />
                  </>
                )}
              </div>

              {selectedSubject === '2' && (
                <div className="relative">
                  {ordersLoading && <LoaderSpinner />}
                  {ordersSuccess && (
                    <>
                      <Select
                        className="w-full h-12 border-gray-500 text-sm"
                        options={filteredOrders}
                        {...register('order')}
                        error={errors.order}
                        required
                      />
                    </>
                  )}
                </div>
              )}

              <textarea
                className="border-gray-500 border w-full text-xs p-2.5 focus-visible:outline-none focus:border-black hover:border-black"
                rows={7}
                name="message"
                placeholder={t('account.contact.form.message.title')}
                // eslint-disable-next-line @typescript-eslint/ban-ts-comment
                // @ts-ignore - Fix TS error
                {...register('message')}
              />
              {errors.message && (
                <div className="text-sm text-error">
                  {errors.message.message}
                </div>
              )}

              <FileInput
                name="file"
                title="file"
                buttonClassName="w-full h-12"
                {...register('file')}
              />
              <Button
                type="submit"
                className="w-fit mt-4 h-12 px-8"
                disabled={isSubmitting}
              >
                {isSubmitting
                  ? t('account.contact.form.submitting')
                  : t('account.contact.form.submit_button')}
              </Button>

              {submitError && (
                <div className="text-sm text-error mt-2">
                  {'data' in submitError &&
                  submitError.data &&
                  typeof submitError.data === 'object'
                    ? Object.entries(submitError.data).map(
                        ([field, messages]) => (
                          <div key={field}>
                            {Array.isArray(messages)
                              ? messages.join(', ')
                              : String(messages)}
                          </div>
                        )
                      )
                    : t('account.contact.form.error.general')}
                </div>
              )}
            </form>
          </>
        )}
      </div>
    </div>
  );
};

export default ContactForm;
