'use client';

import { useState } from 'react';

import { useRouter } from 'next/navigation';

import { UpdateHealthBenefitSchema } from '@/packages/billing/core/src/schema';
import {
  Account,
  CompanyParams,
} from '@/packages/features/accounts/src/types/accounts';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';

import { Button } from '@kit/ui/button';
import { Form } from '@kit/ui/form';
import { Spinner } from '@kit/ui/makerkit/spinner';
import { toast } from '@kit/ui/shadcn/sonner';
import { Trans } from '@kit/ui/trans';

import { cn } from '~/lib/utils';

import { updateHealthBenefit } from '../_lib/server/server-actions';
import HealthBenefitFields from './health-benefit-fields';

const HealthBenefitFormClient = ({
  account,
  companyParams,
}: {
  account: Account;
  companyParams: CompanyParams;
}) => {
  const { t } = useTranslation('account');
  const router = useRouter();

  const [currentCompanyParams, setCurrentCompanyParams] =
    useState<CompanyParams>(companyParams);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  const form = useForm({
    resolver: zodResolver(UpdateHealthBenefitSchema),
    mode: 'onChange',
    defaultValues: {
      occurrence: currentCompanyParams.benefit_occurance || 'yearly',
      amount: currentCompanyParams.benefit_amount || 0,
    },
  });

  const isDirty = form.formState.isDirty;

  const onSubmit = (data: { occurrence: string; amount: number }) => {
    const promise = async () => {
      setIsLoading(true);
      try {
        await updateHealthBenefit({ ...data, accountId: account.id });
        setCurrentCompanyParams((prev) => ({
          ...prev,
          benefit_amount: data.amount,
          benefit_occurance: data.occurrence,
        }));
      } finally {
        form.reset(data);
        setIsLoading(false);
        router.refresh();
      }
    };

    toast.promise(promise, {
      success: t('account:healthBenefitForm.updateSuccess'),
      error: 'error',
    });
  };

  return (
    <Form {...form}>
      <form
        className="flex flex-col gap-6"
        onSubmit={form.handleSubmit(onSubmit)}
      >
        <HealthBenefitFields />

        <Button
          type="submit"
          className="relative"
          disabled={!isDirty || isLoading}
        >
          {isLoading && (
            <div className="absolute inset-0 flex items-center justify-center">
              <Spinner />
            </div>
          )}
          <div className={cn({ invisible: isLoading })}>
            <Trans i18nKey="account:saveChanges" />
          </div>
        </Button>
      </form>
    </Form>
  );
};

export default HealthBenefitFormClient;
