'use client';

import { useState } from 'react';

import { useRouter } from 'next/navigation';

import { sendEmailFromTemplate } from '@/lib/services/mailer.service';
import { CompanySubmitData } from '@/lib/types/company';
import { companyOfferSchema } from '@/lib/validations/company-offer.schema';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { renderCompanyOfferEmail } from '@kit/email-templates';
import { SubmitButton } from '@kit/shared/components/ui/submit-button';
import { FormItem } from '@kit/ui/form';
import { Input } from '@kit/ui/input';
import { Label } from '@kit/ui/label';
import { Spinner } from '@kit/ui/spinner';
import { Trans } from '@kit/ui/trans';

const CompanyOfferForm = () => {
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();
  const language = useTranslation().i18n.language;
  const {
    register,
    handleSubmit,
    formState: { isValid, isSubmitting },
  } = useForm({
    resolver: zodResolver(companyOfferSchema),
    mode: 'onChange',
  });

  const onSubmit = async (data: CompanySubmitData) => {
    setIsLoading(true);
    const formData = new FormData();
    Object.entries(data).forEach(([key, value]) => {
      if (value !== undefined) formData.append(key, value);
    });

    try {
      sendEmailFromTemplate(
        renderCompanyOfferEmail,
        {
          companyData: data,
          language,
        },
        process.env.CONTACT_EMAIL!,
      )
        .then(() => router.push('/company-offer/success'))
        .catch((error) => {
          setIsLoading(false);
          alert('Could not send email at this time');
          console.warn('error: ' + error);
        });
    } catch (err: unknown) {
      setIsLoading(false);
      if (err instanceof Error) {
        console.warn('Server validation error: ' + err.message);
      }
      console.warn('Server validation error: ', err);
    }
  };

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      noValidate
      className="flex flex-col gap-6 px-6 pt-8 text-left"
    >
      <FormItem>
        <Label>
          <Trans i18nKey={'common:formField:companyName'} />
        </Label>
        <Input {...register('companyName')} />
      </FormItem>
      <FormItem>
        <Label>
          <Trans i18nKey={'common:formField:contactPerson'} />
        </Label>
        <Input {...register('contactPerson')} />
      </FormItem>
      <FormItem>
        <Label>
          <Trans i18nKey={'common:formField:email'} />
        </Label>
        <Input type="email" {...register('email')}></Input>
      </FormItem>
      <FormItem>
        <Label>
          <Trans i18nKey={'common:formField:phone'} />
        </Label>
        <Input type="tel" {...register('phone')} />
      </FormItem>
      <SubmitButton
        disabled={isLoading || !isValid || isSubmitting}
        pendingText="Saatmine..."
        type="submit"
      >
        {isLoading ? (
          <Spinner />
        ) : (
          <Trans i18nKey={'account:requestCompanyAccount:button'} />
        )}
      </SubmitButton>
    </form>
  );
};

export default CompanyOfferForm;
