"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { Loader2, Sparkles } from "lucide-react";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "@/components/ui/use-toast";
import { getImageEditorStage } from "@/lib/image-editor-stage-ref";
import {
  getBaseImageLayer,
  useImageEditorStore,
} from "@/lib/image-editor-store";

export function AiRemoveBgModal() {
  const t = useTranslations("auto.componentsImageEditorAiRemoveBgModal");
  const isOpen = useImageEditorStore((s) => s.isAiModalOpen);
  const setAiModalOpen = useImageEditorStore((s) => s.setAiModalOpen);
  const replaceBaseImage = useImageEditorStore((s) => s.replaceBaseImage);
  const layers = useImageEditorStore((s) => s.layers);
  const [isLoading, setIsLoading] = useState(false);

  const handleRemoveBg = async () => {
    const stage = getImageEditorStage();
    const base = getBaseImageLayer({ layers });
    if (!stage || !base) {
      toast({ title: t("openImageFirst") });
      return;
    }

    const dataUrl = stage.toDataURL({ pixelRatio: 1 });
    setIsLoading(true);

    try {
      const response = await fetch("/api/remove-bg", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ image: dataUrl }),
      });
      const payload = (await response.json()) as {
        image?: string;
        error?: string;
      };

      if (!response.ok || !payload.image) {
        toast({ title: payload.error ?? t("removalFailed") });
        return;
      }

      replaceBaseImage(payload.image);
      toast({ title: t("backgroundRemoved") });
      setAiModalOpen(false);
    } catch {
      toast({ title: t("serviceUnreachable") });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={setAiModalOpen}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Sparkles className="h-5 w-5 text-primary-400" />
            {t("title")}
          </DialogTitle>
          <DialogDescription>{t("description")}</DialogDescription>
        </DialogHeader>
        <Button
          type="button"
          className="w-full bg-primary-600 hover:bg-primary-700"
          disabled={isLoading}
          onClick={handleRemoveBg}
        >
          {isLoading ? (
            <>
              <Loader2 className="h-4 w-4 animate-spin" />
              {t("processing")}
            </>
          ) : (
            t("removeBackground")
          )}
        </Button>
      </DialogContent>
    </Dialog>
  );
}
