"use client";
import React from "react";
import { set, z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { retrieveHeadersByEndpoint } from "../functions/retrieveEndpointAndValidations";

interface TableProps {
  createEndpoint: string;
  updateEndpoint: string;
  tableFunction: any;
  UpdatePage: any;
  setFormPage: any;
  updatePageInfo: any;
  returnToPage: any;
}

const formSchema = z.object({
  searchText: z.string().default(""),
});

const Table: React.FC<TableProps> = ({
  createEndpoint,
  updateEndpoint,
  tableFunction,
  UpdatePage,
  setFormPage,
  updatePageInfo,
  returnToPage,
}) => {
  const [apiHeaders, setApiHeaders] = React.useState<string[]>([]);
  const [tabledata, settabledata] = React.useState([]);
  const [searchDropDown, setSearchDropDown] = React.useState("");

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

  function retrieveData(query: null | any = null) {
    return tableFunction(query)
      .then((res: any) => {
        settabledata(res?.data || []);
        return res?.data || [];
      })
      .catch((err: any) => {});
  }

  React.useEffect(() => {
    retrieveHeadersByEndpoint(createEndpoint).then((validations: any) => {
      if (validations?.headers.length !== 0) {
        tableFunction({
          page: 1,
          limit: 10,
          order_field: "uu_id",
          order_type: "desc",
        })
          .then((response: any) => {
            settabledata(response?.data || []);
            for (const key in response?.data[0]) {
              if (Object.keys(validations?.headers).includes(key)) {
                setApiHeaders((prev: string[]) => [
                  ...prev,
                  validations?.headers[key],
                ]);
              }
            }
          })
          .catch((err: any) => {});
      }
      retrieveData();
    });
  }, []);

  function cleanSearch() {
    retrieveData();
  }

  function searchByForm() {
    const searchText = form.getValues("searchText");
    if (searchText === "") {
      cleanSearch();
    } else {
      if (searchText.length > 3) {
        setQuery({ searchDropDown: searchText });
        retrieveData();
      }
    }
  }

  function updateSelectedRow({ selectedComponent }: any) {
    setFormPage(
      <UpdatePage
        endpoint={updateEndpoint}
        pageInfo={updatePageInfo}
        selectedRow={selectedComponent}
        returnToPage={returnToPage}
        saveFunction={() => console.log("saveFunction")}
      />
    );
  }

  return (
    <>
      <div className="text-lg rounded-sm border border-stroke bg-white px-5 pb-2.5 pt-6 shadow-default dark:border-strokedark dark:bg-boxdark sm:px-7.5 xl:pb-1">
        <div className="my-5  max-w-full justify-start text-lg align-middle">
          <Form {...form}>
            <form onSubmit={searchByForm}>
              <div className="relative">
                <FormField
                  control={form.control}
                  name="searchText"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <input
                          type="text"
                          placeholder="Aramak istediğiniz metini yazınız"
                          className="w-full rounded-lg border border-stroke bg-transparent py-4 pl-6 pr-10 text-black outline-none focus:border-primary focus-visible:shadow-none dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                          {...field}
                          value={field.value || ""}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <button
                  type="submit"
                  className="absolute right-5 top-1/2 -translate-y-1/2"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="32"
                    height="32"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="lucide lucide-search"
                  >
                    <circle cx="11" cy="11" r="8" />
                    <path d="m21 21-4.3-4.3" />
                  </svg>
                </button>
                <button
                  onClick={() => cleanSearch()}
                  className="absolute right-20 top-1/2 -translate-y-1/2"
                >
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="32"
                    height="32"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="lucide lucide-x"
                  >
                    <path d="M18 6 6 18" />
                    <path d="m6 6 12 12" />
                  </svg>
                </button>
              </div>
            </form>
          </Form>
        </div>
        <div className="max-w-full mt-5 mb-10 overflow-x-auto">
          {tabledata.map((row: any) => {
            return (
              <span
                key={`${row.uu_id}-update`}
                className="absolute left-20 bottom-30 mt-9"
              >
                <svg
                  onClick={() => updateSelectedRow({ selectedComponent: row })}
                  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-pencil"
                >
                  <path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" />
                  <path d="m15 5 4 4" />
                </svg>
              </span>
            );
          })}
          <table className="w-full table-auto">
            <thead>
              <tr className="bg-gray-2 dark:bg-meta-4 border-b border-[#eee] py-5  dark:border-strokedark xl:pl-11">
                {apiHeaders &&
                  apiHeaders?.map((header, key) => (
                    <th
                      key={key}
                      className="min-w-auto px-4 py-4 font-medium text-black dark:text-white"
                    >
                      {header}
                    </th>
                  ))}
              </tr>
            </thead>

            <tbody>
              {tabledata.map((row: any) => (
                <tr key={row.uu_id}>
                  {Object.entries(row).map(
                    ([key, value]: [key: string, value: any]) => {
                      return (
                        <td
                          key={key}
                          className="border-b border-[#eee] py-5 pl-9 dark:border-strokedark xl:pl-11"
                        >
                          <h5>{value || ""}</h5>
                        </td>
                      );
                    }
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
};

export default Table;
