import React, { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";

import { FieldError, Input, Label } from "@phoenix/components";
import { TextField, type TextFieldProps } from "@phoenix/components/core/field";
import {
  useEvaluatorStore,
  useEvaluatorStoreInstance,
} from "@phoenix/contexts/EvaluatorContext";

const useEvaluatorDescriptionInputForm = () => {
  const store = useEvaluatorStoreInstance();
  const description = useEvaluatorStore((state) => {
    return state.evaluator.description;
  });
  const form = useForm({ defaultValues: { description }, mode: "onChange" });
  const { getValues, setValue, subscribe } = form;
  useEffect(() => {
    if (getValues("description") !== description) {
      setValue("description", description, {
        shouldDirty: false,
        shouldTouch: false,
        shouldValidate: true,
      });
    }
  }, [description, getValues, setValue]);
  useEffect(() => {
    return subscribe({
      formState: { isValid: true, values: true },
      callback({ values: { description }, isValid }) {
        if (!isValid) {
          return;
        }
        const { setEvaluatorDescription } = store.getState();
        setEvaluatorDescription(description);
      },
    });
  }, [subscribe, store]);
  return form;
};

export const EvaluatorDescriptionInput = ({
  placeholder = "e.g. rate the response on correctness",
  ...props
}: Partial<TextFieldProps> & { placeholder?: string }) => {
  const form = useEvaluatorDescriptionInputForm();
  const { control } = form;
  return (
    <Controller
      name="description"
      control={control}
      render={({ field, fieldState: { error } }) => (
        <TextField {...field} autoComplete="off" isInvalid={!!error} {...props}>
          <Label>Description (optional)</Label>
          <Input placeholder={placeholder} />
          <FieldError>{error?.message}</FieldError>
        </TextField>
      )}
    />
  );
};
