"use client";
import { RetrieveInputByType } from "@/hooks/renderInputWithValidation";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form";
import { convertApiValidationToZodValidation } from "@/lib/renderZodValidation";

interface CreatePageComponentInterface {
  validator: any;
  headers: any;
}

const CreatePageComponent: React.FC<CreatePageComponentInterface> = ({
  validator,
  headers,
}) => {
  const returnValidation = convertApiValidationToZodValidation(validator);
  const { validSchemaZod, zodValidation, apiValidation } = returnValidation;

  const form = useForm<z.infer<typeof validSchemaZod>>({
    resolver: zodResolver(validSchemaZod),
    defaultValues: {},
  });

  function submitUpdate(formData: z.infer<typeof validSchemaZod>) {
    // saveFunction({
    //   uu_id: updateUUID,
    //   payload: validDataParser(formData),
    // }).then((res: any) => {
    //   console.log(res);
    //   if (res?.status === 200) {
    //   } else {
    //     alert("Güncelleme başarısız");
    //   }
    // });
  }

  return (
    <div className="container mx-auto p-4">
      <Form {...form}>
        <form action="">
          {Object.entries(validator).map(([key, value]: [string, any]) => (
            <FormField
              key={key}
              control={form.control}
              name={String(key)}
              render={({ field }) => {
                return (
                  <FormItem>
                    <FormLabel>
                      {headers[key] || `Header not found ${key}`}
                    </FormLabel>
                    <FormControl>
                      {RetrieveInputByType({
                        type: value?.fieldType || "string",
                        props: {
                          className: "",
                          field: field,
                          placeholder: headers[key],
                          required: value?.required || false,
                        },
                      })}
                    </FormControl>
                    {String(form.formState.errors[key]?.type) ===
                    "invalid_type" ? (
                      <span id={key} className="text-red-700">
                        "Lütfen metinsel bir değer giriniz"
                      </span>
                    ) : (
                      <></>
                    )}
                  </FormItem>
                );
              }}
            />
          ))}
          <button type="submit" className="mt-4">
            Submit
          </button>
        </form>
      </Form>
    </div>
  );
};

export default CreatePageComponent;
