'use client';

import { useTransition } from 'react';

import { useRouter } from 'next/navigation';

import { useTranslations } from 'next-intl';

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@kit/ui/alert-dialog';
import { Button } from '@kit/ui/button';
import { toast } from '@kit/ui/sonner';

interface PublishToggleButtonProps {
  pageId: string;
  accountId: string;
  isPublished: boolean;
}

export function PublishToggleButton({
  pageId,
  accountId,
  isPublished,
}: PublishToggleButtonProps) {
  const router = useRouter();
  const t = useTranslations('siteBuilder');
  const [isPending, startTransition] = useTransition();

  const handleToggle = () => {
    startTransition(async () => {
      try {
        const response = await fetch(
          `/api/site-builder/pages/${pageId}/publish`,
          {
            method: 'PATCH',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ accountId, isPublished: !isPublished }),
          },
        );

        if (!response.ok) {
          toast.error(t('pages.toggleError'));
          return;
        }

        router.refresh();
      } catch (error) {
        console.error('Failed to toggle publish state:', error);
        toast.error(t('pages.toggleError'));
      }
    });
  };

  return (
    <AlertDialog>
      <AlertDialogTrigger
        render={
          <Button
            size="sm"
            variant={isPublished ? 'secondary' : 'default'}
            disabled={isPending}
          >
            {isPublished ? t('pages.hide') : t('pages.publish')}
          </Button>
        }
      />
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>
            {isPublished ? t('pages.hideTitle') : t('pages.publishTitle')}
          </AlertDialogTitle>
          <AlertDialogDescription>
            {isPublished ? t('pages.hideDesc') : t('pages.publishDesc')}
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>{t('pages.cancelAction')}</AlertDialogCancel>
          <AlertDialogAction onClick={handleToggle} disabled={isPending}>
            {isPublished ? t('pages.hide') : t('pages.publish')}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
