import { Form, useFetcher, useParams } from "@remix-run/react";
import { FC, useEffect, useState } from "react";
import { useRemixForm } from "remix-hook-form";
import { Button } from "~/components/ui/button";
import { Input } from "~/components/ui/input";
import { Label } from "~/components/ui/label";
import { CreateDatasetResolver, CreateDatasetSchemaType } from "~/pages/datasets/forms/CreateDatasetValidator";
import { CreateDatasetActionData } from "~/pages/datasets/forms/types";
import { Routes } from "~/routes";

export const CreateFinetuningDatasetForm: FC<{
  isOpen: boolean;
  onClose: () => void;
}> = ({ isOpen, onClose }) => {
  const fetcher = useFetcher<CreateDatasetActionData>();
  const params = useParams();
  const [error, setError] = useState<string | null>(null);
  const {
    handleSubmit,
    formState: { errors, isSubmitting },
    register,
    reset,
  } = useRemixForm<CreateDatasetSchemaType>({
    mode: "onSubmit",
    resolver: CreateDatasetResolver,
    defaultValues: {
      name: "",
      description: "",
      isFineTuning: true,
    },
    fetcher,
    submitConfig: {
      method: "post",
      action: Routes.actions.dataset.create({
        projectId: params.projectId!,
        envId: params.envId!,
      }),
    },
  });

  const checkIfSuccessful = () => {
    if (!fetcher.data) {
      return;
    } else if (fetcher.data.error) {
      setError(fetcher.data.error);
    } else if (fetcher.data.dataset) {
      setError(null);
      reset();
      onClose();
    }
  };
  useEffect(checkIfSuccessful, [fetcher.data]);

  const resetOnClose = () => {
    if (!isOpen) {
      reset();
      setError(null);
    }
  };
  useEffect(resetOnClose, [isOpen]);

  return (
    <Form onSubmit={handleSubmit}>
      <fieldset disabled={isSubmitting} className={"flex flex-col gap-2"}>
        <div>
          <Label htmlFor={"name"}>Name</Label>
          <Input {...register("name")} />
          {errors.name && <p className="text-destructive">{errors.name.message}</p>}
        </div>
        <div>
          <Label htmlFor={"description"}>Description</Label>
          <Input {...register("description")} />
          {errors.description && <p className="text-destructive">{errors.description.message}</p>}
        </div>
        <div className={"mt-4"}>
          <p>
            A Fine-Tuning dataset has a preset input and output schema. Check out our documentation for more information.
          </p>
        </div>
        <div className={"mt-4 flex justify-end"}>
          {error && <p className="text-destructive">{error}</p>}
          <Button type="submit">Create Fine-Tuning Dataset</Button>
        </div>
      </fieldset>
    </Form>
  );
};
