import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios from "axios";
import { Avatar } from "flowbite-react";
import { useSession } from "next-auth/react";
import { FC, useEffect, useState } from "react";
import { MdClose } from "react-icons/md";
import { toast } from "react-toastify";
import Button from "../Button";
import { TScompanyProfileSchema } from "../forms/schema/company-profile";
import Spinner from "../spinner";
import Dropzone from "./Dropzone";

type props = {
  name: string;
  company: TScompanyProfileSchema;
};

const UploadCompanyLogo: FC<props> = ({ name, company }) => {
  const [images, setImages] = useState<any>([]);
  let [file, setFile] = useState<string | null>(null);
  const { data: session }: any = useSession();
  let logo_api = `/api/company/${session?.company?.id}?item=company`;
  if (session?.user?.reseller_id) {
    logo_api = `/api/company/${session?.company?.id}?item=reseller`;
  }

  const queryClient = useQueryClient();
  const { mutate: updateCompany, isPending } = useMutation<any>({
    mutationFn: async (formData: any) => {
      const { data } = await axios.put(logo_api, formData);
      return data?.data;
    },
    onSuccess: (data) => {
      toast.success(`${name} upload successfully!`);
      queryClient.invalidateQueries({ queryKey: ["company"] });
      if (data) {
        let image_url = `${process.env.NEXT_PUBLIC_API}${data[name]}`;
        setFile(image_url);
      }
      window.location.reload();
    },
    onError: () => {},
  });
  const upload = () => {
    let formData: any = new FormData();
    if (images?.length > 0) {
      Array.from(images).forEach((image: any) => {
        formData.append(name, image);
      });
    }
    updateCompany(formData);
  };

  const { mutate: deleteImage, isPending: deletePending } = useMutation({
    mutationFn: async () =>
      await axios.delete(logo_api, {
        data: { [name]: [name] },
      }),
    onSuccess: () => {
      toast.success(`${name} delete successfully!`);
      queryClient.invalidateQueries({ queryKey: ["company"] });
      setFile(null);
      setImages([]);
      window.location.reload();
    },
    onError: () => {
      toast.error(`Unable to delete the ${name}!`);
    },
  });
  const removeImage = () => {
    deleteImage();
  };

  useEffect(() => {
    if (name === "logo" && company?.logo) {
      setFile(`${process.env.NEXT_PUBLIC_API}${company?.logo}`);
    }
    if (name === "favicon" && company?.favicon) {
      setFile(`${process.env.NEXT_PUBLIC_API}${company?.favicon}`);
    }
  }, [name]);
  return (
    <>
      <div className="flex">
        {file ? (
          <Avatar img={`${file}`} size="lg" className="relative">
            <button
              aria-label="Close"
              onClick={() => removeImage()}
              className="absolute -top-0  right-4 bg-gray-100 text-sm text-gray-900 hover:bg-gray-200 hover:text-red-400 dark:hover:bg-gray-600 dark:hover:text-white"
              type="button"
            >
              {!deletePending && <MdClose className="text-xl" />}
              {deletePending && <Spinner />}
            </button>
          </Avatar>
        ) : (
          <>
            <div>
              <Dropzone setImages={setImages} images={images} />
            </div>
            {images?.length > 0 && (
              <div>
                <Button
                  className="mt-4 ml-2"
                  buttonType={"button"}
                  isProcessing={isPending}
                  onClick={() => upload()}
                >
                  upload
                </Button>
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
};

export default UploadCompanyLogo;
