import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { X } from "lucide-react";
import { useApiServices } from "@/store/admin/apiServices";
import type { ApiServiceCredentials } from "@/types";

const download = (credentials: ApiServiceCredentials) => {
  const jsonStr = JSON.stringify(credentials, null, 2);
  const blob = new Blob([jsonStr], { type: "application/json" });
  const url = URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = url;
  a.download = `credentials.json`;
  a.click();

  URL.revokeObjectURL(url);
};

const ApiServiceCredentialsModal = () => {
  const credentials = useApiServices((state) => state.createdCredentials);
  const resetCredentials = useApiServices((state) => state.resetCredentials);

  const portalRoot = document.getElementById("portal-root");
  if (!portalRoot || !credentials) return null;

  return createPortal(
    <div className="fixed z-50 inset-0 flex items-center justify-center bg-black/30 dark:bg-white/30 px-5">
      <div className="rounded-2xl flex flex-col items-stretch bg-white dark:bg-black min-w-[300px] max-w-md w-full">
        <div className="flex flex-row items-center justify-between p-4 border-b dark:border-gray-800 border-gray-300">
          <p className="text-gray-800 dark:text-gray-200">New Credentials</p>
          <Button variant="icon" onClick={resetCredentials}>
            <X />
          </Button>
        </div>
        <div className="p-4">
          <div className="flex flex-col gap-2 mb-4">
            <p className="text-gray-600 dark:text-gray-400 text-sm">
              Client ID
            </p>
            <Input value={credentials.client_id} disabled />
          </div>
          <div className="flex flex-col gap-2 mb-4">
            <p className="text-gray-600 dark:text-gray-400 text-sm">
              Client Secret
            </p>
            <Input value={credentials.client_secret} disabled />
          </div>
          <div className="mt-4 flex flex-row items-center justify-between">
            <Button variant="contained" onClick={resetCredentials}>
              Close
            </Button>
            <Button variant="outlined" onClick={() => download(credentials)}>
              Download
            </Button>
          </div>
        </div>
      </div>
    </div>,
    portalRoot,
  );
};

export default ApiServiceCredentialsModal;
