'use client';

import Image from 'next/image';
import { useRouter } from 'next/navigation';

import { CaretRightIcon } from '@radix-ui/react-icons';

import { useRevalidatePersonalAccountDataQuery } from '@kit/accounts/hooks/use-personal-account-data';
import { useUpdateAccountData } from '@kit/accounts/hooks/use-update-account';
import { Button } from '@kit/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@kit/ui/dialog';
import { toast } from '@kit/ui/sonner';
import { Trans } from '@kit/ui/trans';

export default function ConsentDialog({ userId }: { userId: string }) {
  const router = useRouter();

  const updateAccountMutation = useUpdateAccountData(userId);
  const revalidateUserDataQuery = useRevalidatePersonalAccountDataQuery();

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

    toast.promise(() => promise, {
      success: <Trans i18nKey={'account:updateConsentSuccess'} />,
      error: <Trans i18nKey={'account:updateConsentError'} />,
      loading: <Trans i18nKey={'account:updateConsentLoading'} />,
    });

    return router.refresh();
  };

  return (
    <Dialog defaultOpen>
      <DialogContent
        className="flex max-w-[436px] flex-col items-center gap-4 space-y-4"
        disableClose
      >
        <DialogHeader className="items-center text-center">
          <Image alt="Toggle" src="/assets/toggle.png" width={96} height={96} />
          <DialogTitle>
            <Trans i18nKey="account:consentModal.title" />
          </DialogTitle>
          <DialogDescription>
            <Trans i18nKey="account:consentModal.description" />
          </DialogDescription>
        </DialogHeader>
        <DialogFooter>
          <Button variant="secondary" onClick={() => updateConsent(false)}>
            <Trans i18nKey="account:consentModal.reject" />
          </Button>
          <Button onClick={() => updateConsent(true)}>
            <Trans i18nKey="account:consentModal.accept" />
            <CaretRightIcon />
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
