"use client";
import React from "react";
import EventButton from "./ButtonEvent";
import FormPage from "./FormPage";

import * as z from "zod";
import { retrieveValidationsByEndpointWithData } from "../functions/retrieveEndpointAndValidations";

interface UpdatePageButtonProps {
  endpoint: string;
  pageInfo: any;
  selectedRow: any;
  returnToPage: any;
  saveFunction: any;
}

const PageUpdate: React.FC<UpdatePageButtonProps> = ({
  endpoint,
  pageInfo,
  selectedRow,
  returnToPage,
  saveFunction,
}) => {
  const [validatedData, setValidatedData] = React.useState({});
  const [zodValidation, setZodValidation] = React.useState(null);
  const [apiValidation, setApiValidation] = React.useState<{
    [key: string]: any;
  }>({});
  const [apiHeaders, setApiHeaders] = React.useState<{
    [key: string]: any;
  }>({});

  React.useEffect(() => {
    if (Object.keys(validatedData).length === 0) {
      retrieveValidationsByEndpointWithData(endpoint, selectedRow).then(
        (validations: any) => {
          setValidatedData(selectedRow);
          setZodValidation(validations.zodValidation);
          setApiValidation(validations.apiValidation?.validated);
          setApiHeaders(validations.apiValidation?.headers);
        }
      );
    }
  }, []);

  return (
    <>
      <h1 className="text-center text-3xl">{pageInfo?.title}</h1>
      <div className=" md:flex items-center py-5 my-5 rounded-sm border border-stroke bg-white shadow-default dark:border-strokedark dark:bg-boxdark">
        <EventButton
          onClick={() => returnToPage()}
          label="Dashboarda Dön"
          bgColor="bg-red-700"
          icon={
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="28"
              height="28"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="lucide lucide-square-x"
            >
              <rect width="18" height="18" x="3" y="3" rx="2" ry="2" />
              <path d="m15 9-6 6" />
              <path d="m9 9 6 6" />
            </svg>
          }
        />
      </div>
      {zodValidation && apiValidation && (
        <FormPage
          validatedData={selectedRow}
          zodValidation={zodValidation}
          apiValidation={apiValidation}
          apiHeaders={apiHeaders}
        />
      )}
    </>
  );
};

export default PageUpdate;
