import { ApiRoute } from "@/utils/type";
import classNames from "classnames";
import { useState } from "react";
import Highlight from "react-highlight";
import { BiLogoPython, BiSolidCopy } from "react-icons/bi";
import { Options } from "redaxios";

export const PythonSnippet = ({
  endpoint,
  headers,
  parameters,
  body,
  onCopyToClipboard,
}: {
  endpoint: ApiRoute;
  parameters?: Record<string, any>;
  headers?: Record<string, any>;
  body?: Options | undefined;
  onCopyToClipboard: (e: string) => void;
}) => {
  const [isCopied, setIsCopied] = useState<boolean>(false);

  const generatePythonRequestFromEndpoint = () => {
    const { method, path } = endpoint;
    const fullpath = `${process.env.NEXT_PUBLIC_APP_APIURL}${path}`;

    const removeEmptyValues = (data: Record<string, any>) => {
      const formattedData = { ...data };
      Object.entries(formattedData).forEach(([key, value]) => {
        if (!value) {
          delete formattedData[key];
        }
        if (typeof value === "boolean") {
          formattedData[key] = value ? "True" : "False";
        }
      });
      return formattedData;
    };

    const Dict: Record<string, any> = {
      GET: () => {
        const filteredEmptyParameters = removeEmptyValues(parameters ?? {});

        return `import requests
response = requests.get(
  "${fullpath}",
  params=${JSON.stringify(filteredEmptyParameters)},
  headers=${JSON.stringify(headers)}
)`;
      },
      DELETE: () => {
        const formattedBody = removeEmptyValues(body ?? {});
        return `import requests
response = requests.delete(
  "${fullpath}",
  data=${JSON.stringify(formattedBody)},
  headers=${JSON.stringify(headers)}
)`;
      },
      DEFAULT: () => {
        const formattedBody = removeEmptyValues(body ?? {});
        return `import requests
response = requests.${method.toLocaleLowerCase()}(
  "${fullpath}",
  json=${JSON.stringify(formattedBody)},
  headers=${JSON.stringify(headers)}
)`;
      },
    };

    return Dict[method] ? Dict[method]() : Dict["DEFAULT"]();
  };

  const handleCopy = () => {
    onCopyToClipboard(generatePythonRequestFromEndpoint());
    setIsCopied(true);
    setTimeout(() => {
      setIsCopied(false);
    }, 1000);
  };

  return (
    <div className="border dark:border-0 border-slate-200 bg-slate-50 dark:bg-slate-950/50 rounded-xl overflow-hidden">
      <header className="bg-slate-200 dark:bg-slate-950 flex items-center justify-start px-5 py-4 uppercase gap-2 text-blue-500">
        <BiLogoPython className="text-xl" />
        <p className="text-xs font-semibold">Python</p>
      </header>
      <main className="px-6 py-6">
        <Highlight className="curl text-xs font-code !bg-transparent !p-0 !whitespace-pre-wrap break-all !leading-relaxed !text-slate-800 dark:!text-slate-100">
          {generatePythonRequestFromEndpoint()}
        </Highlight>
        <div className="flex justify-end relative" onClick={handleCopy}>
          <BiSolidCopy className="text-slate-400 dark:text-slate-500 cursor-pointer hover:text-slate-500 dark:hover:text-slate-300 transition-all duration-75" />
          <div
            className={classNames(
              "bg-indigo-500/60 text-slate-100 text-xs font-semibold absolute bottom-0 right-0 z-10 rounded-lg px-2 py-1 pointer-events-none -translate-y-full transition-all duration-200",
              {
                "opacity-0": !isCopied,
              }
            )}
          >
            Copied!
          </div>
        </div>
      </main>
    </div>
  );
};
