import { useState } from 'react';

import { toast } from 'sonner';

import { Switch } from '@kit/ui/switch';
import { Trans } from '@kit/ui/trans';

import { useRevalidatePersonalAccountDataQuery } from '../../../hooks/use-personal-account-data';
import { useUpdateAccountData } from '../../../hooks/use-update-account';

// This is temporary. When the profile views are ready, all account values included in the form will be updated together on form submit.
export default function ConsentToggle({
  userId,
  initialState,
}: {
  userId: string;
  initialState: boolean;
}) {
  const [isConsent, setIsConsent] = useState(initialState);
  const updateAccountMutation = useUpdateAccountData(userId);
  const revalidateUserDataQuery = useRevalidatePersonalAccountDataQuery();

  const updateConsent = (consent: boolean) => {
    const promise = updateAccountMutation
      .mutateAsync({
        has_consent_anonymized_company_statistics: consent,
      })
      .then(() => {
        revalidateUserDataQuery(userId);
      });

    return toast.promise(() => promise, {
      success: <Trans i18nKey={'account:updateConsentSuccess'} />,
      error: <Trans i18nKey={'account:updateConsentError'} />,
      loading: <Trans i18nKey={'account:updateConsentLoading'} />,
    });
  };
  return (
    <Switch
      checked={isConsent}
      onCheckedChange={setIsConsent}
      onClick={() => updateConsent(!isConsent)}
      disabled={updateAccountMutation.isPending}
    />
  );
}
