"use client";
import {Form, FormikProps} from "formik";
import React, {Suspense, useRef} from "react";
import {CreateFormProps, CreateTosFormValues} from "./CreateTosForm";
import {Field, FieldLabel} from "@/components/ui/field";
import {Input} from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import Loader from "@/components/Loader";
import RichTextEditor, {RichTextEditorHandle} from "@/components/TextEditor";
import {Button} from "@/components/ui/button";

export default function InnerCreateTosForm(
  props: FormikProps<CreateTosFormValues> & CreateFormProps
) {
  const editorRef = useRef<RichTextEditorHandle>(null);
  const handleSave = () => {
    const html = editorRef.current?.getContent();
    props.setFieldValue("content", html);
    props.submitForm();
  };
  return (
    <Form className="grid grid-cols-3 w-full items-center gap-x-4 mb-10">
      <Field className="col-span-1">
        <FieldLabel>عنوان</FieldLabel>
        <Input
          value={props.values.title}
          onChange={(e) => props.setFieldValue("title", e.target.value)}
          className="bg-white"
        />
      </Field>
      <Field className="col-span-1">
        <FieldLabel>ورژن</FieldLabel>
        <Input
          value={props.values.version}
          onChange={(e) => props.setFieldValue("version", e.target.value)}
          className="bg-white"
        />
      </Field>
      <Field className="col-span-1 flex items-center space-x-2">
        <FieldLabel>فعال بودن نسخه</FieldLabel>

        <Select
          onValueChange={(value) => props.setFieldValue("isActive", value)}
          dir="rtl"
        >
          <SelectTrigger className="w-[180px] bg-white w-full">
            <SelectValue placeholder="فعال بودن را انتخاب کنید" />
          </SelectTrigger>
          <SelectContent className="bg-white w-full">
            <SelectGroup>
              <SelectItem value="true">فعال باشد</SelectItem>
              <SelectItem value="false">فعال نباشد</SelectItem>
            </SelectGroup>
          </SelectContent>
        </Select>
      </Field>
      <Field className="col-span-3 w-full mt-10">
        <Suspense fallback={<Loader />}>
          <RichTextEditor ref={editorRef} value={props.values.content} />
        </Suspense>
      </Field>
      <div className="col-span-3  flex items-center justify-start gap-4  mt-10 w-full">
        <div>
          <Button type="button" onClick={handleSave}>
            {props.isPending ? <Loader size="4" /> : "ثبت نسخه جدید"}
          </Button>
        </div>
        <div>
          <Button
            variant={"destructive"}
            type="button"
            onClick={() => props.setMode("new")}
          >
            انصراف
          </Button>
        </div>
      </div>
    </Form>
  );
}
