'use client';

import { useRouter } from 'next/navigation';

import { SubmitButton } from '@/components/ui/submit-button';
import { sendCompanyOfferEmail } 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 { FormItem } from '@kit/ui/form';
import { Input } from '@kit/ui/input';
import { Label } from '@kit/ui/label';
import { Trans } from '@kit/ui/trans';

const CompanyOfferForm = () => {
  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) => {
    const formData = new FormData();
    Object.entries(data).forEach(([key, value]) => {
      if (value !== undefined) formData.append(key, value);
    });

    try {
      sendCompanyOfferEmail(data, language)
        .then(() => router.push('/company-offer/success'))
        .catch((error) => alert('error: ' + error));
    } catch (err: unknown) {
      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={!isValid || isSubmitting}
        pendingText="Saatmine..."
        type="submit"
      >
        <Trans i18nKey={'account:requestCompanyAccount:button'} />
      </SubmitButton>
    </form>
  );
};

export default CompanyOfferForm;
