"use client";
import CreateTosForm from "@/components/forms/tos/create/CreateTosForm";
import UpdateTosForm from "@/components/forms/tos/update/UpdateTosForm";
import Loader from "@/components/Loader";
import SectionTitle from "@/components/SectionTitle";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  useCreateTos,
  useDeleteTos,
  useGetAllTos,
  useGetSingleTos,
  useTosToggleActive,
} from "@/hooks/tos";
import { handleAxiosError } from "@/lib/utils";
import { useQueryClient } from "@tanstack/react-query";
import { Plus, Trash } from "lucide-react";
import { useRouter } from "next/navigation";
import React, { Suspense,  useState } from "react";
import { toast } from "react-toastify";




export default function Page() {
  const router = useRouter();
  const [mode, setMode] = useState<"new" | "edit" | "form">("new");
  const [version, setVersion] = useState<string>("");
  const { mutateAsync: createAsync, isPending: createPending } = useCreateTos();
  const queryClient = useQueryClient();

  const { data: AllTos} = useGetAllTos();
  const { mutateAsync: toggleAsync, isPending: togglePending } =
    useTosToggleActive();
  const { mutateAsync: deleteAsync, isPending: deletePending } = useDeleteTos();
  const {
    mutateAsync: updateAsync,
    isPending: singleTosPending,
    data: preValues,
  } = useGetSingleTos();

  const handleGetSingleTos = async (version: string) => {
    try {
      await updateAsync(version);
    } catch (error) {
      toast.error("adassd");
    }
  };

  const handleToggleActive = async (version: string) => {
    try {
      const { message } = await toggleAsync(version);
      await queryClient.invalidateQueries({ queryKey: ["get-all-tos"] });
      toast.success(message);
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  };
  const handleDeleteTos = async (version: string) => {
    try {
      const { message } = await deleteAsync(version);
      await queryClient.invalidateQueries({ queryKey: ["get-all-tos"] });
      toast.success(message);
    } catch (error) {
      toast.error(handleAxiosError(error));
    }
  };
  return (
    <div className="p-4">
      <div className="flex items-center gap-x-4 w-full mb-10">
        {mode === "new" && (
          <Button
            onClick={() => {
              setMode("form");
              setVersion("");
            }}
          >
            <Plus />
            ایجاد نسخه جدید
          </Button>
        )}
        {mode === "form" && (
          <>
            <CreateTosForm
              router={router}
              createFn={createAsync}
              isPending={createPending}
              mode={mode}
              setMode={setMode}
              queryClient={queryClient}
            />
          </>
        )}

        {mode === "edit" && version && preValues?.data && (
          <Suspense fallback={<Loader />}>
            <UpdateTosForm
              router={router}
              updateFn={updateAsync}
              updatePending={singleTosPending}
              mode={mode}
              setMode={setMode}
              queryClient={queryClient}
              preValues={preValues?.data}
              version={version}
              setVersion={setVersion}
            />
          </Suspense>
        )}
      </div>
      <div className=" mb-10">
        <SectionTitle label="ورژن های موجود" />
      </div>
      <div className="grid grid-cols-2 gap-y-4">
        {AllTos &&
          AllTos?.data?.length > 0 &&
          AllTos?.data?.map((item, index) => (
            <div
              key={item?.id}
              className="col-span-2 flex items-center justify-between gap-4  bg-white rounded-lg px-4 py-2 shadow-sm min-w-[200px]"
            >
              <div>
                <span>ردیف : </span>
                <span>{index + 1}</span>
              </div>
              <div className="rounded-lg p-4 flex items-center justify-start gap-x-2">
                <span>عنوان : </span>
                <span>{item.title}</span>
              </div>
              <div className="flex items-center justify-start shadow-inset gap-x-2  p-1">
                <span>ورژن : </span>
                <span>
                  <Badge variant={"secondary"}>{item.version}</Badge>
                </span>
              </div>
              <div className="flex items-center justify-end gap-x-4">
                <div>
                  {item.version === version && mode === "edit" ? (
                    <Button
                      type="button"
                      variant={"destructive"}
                      onClick={() => {
                        setVersion("");
                        setMode("new");
                      }}
                    >
                      انصراف
                    </Button>
                  ) : (
                    <Button
                      disabled={mode === "form" || version ? true : false}
                      type="button"
                      variant={"outline"}
                      onClick={() => {
                        setVersion(item.version);
                        setMode("edit");
                        handleGetSingleTos(item.version);
                      }}
                    >
                      ویرایش
                    </Button>
                  )}
                </div>
                <div>
                  {item.isActive ? (
                    <Badge variant={"default"} className="bg-green-600">
                      فعال است
                    </Badge>
                  ) : (
                    <Button
                      variant={"default"}
                      onClick={() => handleToggleActive(item.version)}
                    >
                      فعال کردن
                    </Button>
                  )}
                </div>
                <div>
                  <Button
                    // disabled={item.isActive || deletePending}
                    variant={item.isActive ? "secondary" : "destructive"}
                    onClick={() => handleDeleteTos(item.version)}
                  >
                    {deletePending ? <Loader size="4" /> : <Trash />}
                  </Button>
                </div>
              </div>
            </div>
          ))}
      </div>
    </div>
  );
}
