import { useLabContext } from "@/components/labs/context";
import { useLabFeedback } from "@/components/labs/hook";
import {
  LabFeedbackCommentField,
  LabFeedbackRatingField,
} from "@/components/labs/lab-feedback";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { useLocale, useLocaleFunction } from "@/hooks/use-localed";
import { client } from "@/lib/api-client";
import { submitLabFeedback } from "@/lib/api/labs";
import { destroyLabInstance } from "@/lib/api/labs.v2";
import { getErrorMessage } from "@/lib/errors";
import { transformPathLocale } from "@/lib/locale";
import { useForm } from "@tanstack/react-form";
import { useRouter } from "next/navigation";
import { MouseEvent, useEffect, useState, useTransition } from "react";

export function LabTerminate() {
  const { lab } = useLabContext();

  const [showAlert, setShowAlert] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [error, setError] = useState<unknown>(undefined);

  const locale = useLocale();
  const router = useRouter();
  const [transitioning, startTransition] = useTransition();

  const {
    data: { rating_score = 0, comment = "" } = {},
    isLoading: isFeedbackLoading,
  } = useLabFeedback(lab.lab_code);

  const disabled = isFeedbackLoading;
  const feedbackForm = useForm({
    defaultValues: {
      rating_score,
      comment,
    },
    onSubmit({ value, formApi }) {
      if (value.rating_score > 0 && formApi.state.isDirty) {
        submitLabFeedback(lab.lab_code, value).catch(() => {});
      }
    },
  });

  useEffect(() => {
    if (rating_score != null && comment != null) {
      feedbackForm.reset(
        {
          rating_score,
          comment,
        },
        { keepDefaultValues: false }
      );
    }
  }, [feedbackForm, rating_score, comment]);

  const t = useLocaleFunction();

  const handleConfirmDelete = async (event: MouseEvent) => {
    event.preventDefault();
    feedbackForm.handleSubmit().catch(() => {});
    setDeleting(true);
    try {
      await destroyLabInstance(lab.id);
      setShowAlert(false);
      startTransition(() => {
        router.push(
          transformPathLocale(
            `/lab?preview=${encodeURIComponent(lab.lab_code)}`,
            locale
          )
        );
        router.refresh();
      });
      void client.invalidateQueries({
        queryKey: ["lab.active-instance"],
        refetchType: "all",
      });
    } catch (error) {
      setError(error);
    } finally {
      setDeleting(false);
    }
  };

  return (
    <AlertDialog open={showAlert} onOpenChange={setShowAlert}>
      <AlertDialogTrigger asChild>
        <Button
          variant="secondary"
          className="w-full cursor-pointer"
          disabled={transitioning || showAlert || deleting}
        >
          {t("lab.terminate")}
        </Button>
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{t("lab.terminate.title")}</AlertDialogTitle>
          <AlertDialogDescription />
        </AlertDialogHeader>
        <LabFeedbackRatingField form={feedbackForm} disabled={disabled} />
        <LabFeedbackCommentField form={feedbackForm} disabled={disabled} />
        {!!error && (
          <Alert variant="destructive">
            <AlertTitle>{t("lab.terminate.failed")}</AlertTitle>
            <AlertDescription>{getErrorMessage(error)}</AlertDescription>
          </Alert>
        )}
        <AlertDialogFooter>
          <AlertDialogAction
            disabled={deleting || transitioning || isFeedbackLoading}
            onClick={(event) => handleConfirmDelete(event)}
          >
            {t("lab.terminate.confirm")}
          </AlertDialogAction>
          <AlertDialogCancel>{t("lab.terminate.cancel")}</AlertDialogCancel>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
