"use client";

import { use, useState } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";

import { Skeleton, Typography } from "@/components/ui";
import { ActionFieldsForm } from "@/components/widgets";
import { startGeneration } from "@/entities/generations/actions";
import { useToast } from "@/providers/toast-provider";
import { ROUTES } from "@/shared/constants/client-routes";
import { ActionField } from "@/types";

interface CompatibilityActionFieldsFormProps {
  fields: Promise<ActionField[]>;
  actionId: string;
}

export default function CompatibilityActionFieldsForm({
  fields,
  actionId,
}: CompatibilityActionFieldsFormProps) {
  const t = useTranslations("Compatibility");
  const compatibilityActionFields = use(fields);
  const router = useRouter();
  const { addToast } = useToast();

  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (
    values: Record<string, string | number | null>
  ) => {
    setIsLoading(true);

    const response = await startGeneration({
      actionType: "compatibility",
      actionId,
      variables: values,
    });

    setIsLoading(false);

    if (response?.data?.id) {
      router.push(ROUTES.compatibilityResult(actionId, response.data.id));
    }

    if (response.error) {
      addToast({
        variant: "error",
        message: t("error"),
        duration: 5000,
      });
      return;
    }
  };

  if (!compatibilityActionFields || compatibilityActionFields.length === 0) {
    return (
      <Typography as="p" size="sm" color="danger">
        {t("error")}
      </Typography>
    );
  }

  return (
    <ActionFieldsForm
      fields={compatibilityActionFields}
      onSubmit={handleSubmit}
      buttonText={t("button")}
      isLoading={isLoading}
    />
  );
}

export function CompatibilityActionFieldsFormSkeleton() {
  return <Skeleton style={{ height: "250px" }} />;
}
