'use client';

import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';

import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
import type { AccountWithParams } from '@kit/accounts/types/accounts';
import { Button } from '@kit/ui/button';
import { Card, CardDescription, CardTitle } from '@kit/ui/card';
import { Form } from '@kit/ui/form';
import { LanguageSelector } from '@kit/ui/language-selector';
import { toast } from '@kit/ui/sonner';
import { Switch } from '@kit/ui/switch';
import { Trans } from '@kit/ui/trans';

import {
  AccountPreferences,
  accountPreferencesSchema,
} from '../_lib/account-preferences.schema';
import { updatePersonalAccountPreferencesAction } from '../_lib/server/actions';

export default function AccountPreferencesForm({
  account,
}: {
  account: AccountWithParams | null;
}) {
  const revalidateUserDataQuery = useRevalidatePersonalAccountDataQuery();

  const form = useForm({
    resolver: zodResolver(accountPreferencesSchema),
    defaultValues: {
      preferredLanguage: account?.preferred_locale,
      isConsentToAnonymizedCompanyStatistics:
        !!account?.has_consent_anonymized_company_statistics,
    },
  });

  const { register, handleSubmit, watch, setValue } = form;

  const onSubmit = async (data: AccountPreferences) => {
    if (!account?.id) {
      return toast.error(<Trans i18nKey="account:updateAccountError" />);
    }
    const result = await updatePersonalAccountPreferencesAction({
      accountId: account.id,
      data,
    });

    if (result.success) {
      revalidateUserDataQuery(account.primary_owner_user_id);
      return toast.success(
        <Trans i18nKey="account:updateAccountPreferencesSuccess" />,
      );
    }
    return toast.error(
      <Trans i18nKey="account:updateAccountPreferencesError" />,
    );
  };

  const watchedConsent = watch('isConsentToAnonymizedCompanyStatistics');

  if (!account) return null;

  return (
    <>
      <div className="space-y-2">
        <CardTitle className="text-base">
          <Trans i18nKey={'account:language'} />
        </CardTitle>
        <LanguageSelector />
      </div>
      <Form {...form}>
        <form
          className="flex flex-col gap-6 text-left"
          onSubmit={handleSubmit(onSubmit)}
        >
          <div className="space-y-4">
            <h2 className="text-xl font-semibold text-gray-900">
              <Trans i18nKey="account:consents" />
            </h2>

            <Card>
              <div className="flex items-center justify-between p-3">
                <div>
                  <CardTitle className="text-base">
                    <Trans i18nKey="account:consentToAnonymizedCompanyData.label" />
                  </CardTitle>
                  <CardDescription>
                    <Trans i18nKey="account:consentToAnonymizedCompanyData.description" />
                  </CardDescription>
                </div>

                <Switch
                  checked={!!watchedConsent}
                  onCheckedChange={(checked) =>
                    setValue('isConsentToAnonymizedCompanyStatistics', checked)
                  }
                  {...register('isConsentToAnonymizedCompanyStatistics')}
                />
              </div>
            </Card>
          </div>

          <Button type="submit" className="w-36">
            <Trans i18nKey="account:updateProfileSubmitLabel" />
          </Button>
        </form>
      </Form>
    </>
  );
}
