'use client';
import Link from 'next/link';
import { useState } from 'react';
import { useRouter } from "next/navigation";
import MicrosoftIcon from '@mui/icons-material/Microsoft';
import ExitToAppOutlinedIcon from '@mui/icons-material/ExitToAppOutlined';

import Button from "./Button";

const EntraLogin: React.FC = () => {
  const router = useRouter();
  const [error] = useState<string>('');

  const openPopup = (url: string, name = "MicrosoftLogin", width = 600, height = 700) => {
    const left = (window.innerWidth - width) / 2;
    const top = (window.innerHeight - height) / 2;
    return window.open(
      url,
      name,
      `width=${width},height=${height},top=${top},left=${left}`
    );
  };

  const handleEntraLogin = () => {
    openPopup(`${process.env.NEXT_PUBLIC_API_URL}/auth/microsoft/redirect`);
    window.addEventListener("message", (event) => {
      if (event.data?.type === "LOGIN_SUCCESS") {
        router.push(
          event.data.role === "manager"
            ? "/manager/dashboard"
            : "/candidate/booking");
      }
    });
  };


  const handleLogoutRedirect = () => {
    openPopup(`${process.env.NEXT_PUBLIC_API_URL}/auth/microsoft/logout`);
  };

  return (
    <div className="flex items-center justify-center p-0 my-2 md:p-10">
      <div className="w-full max-w-md rounded-xl bg-white p-10 shadow-md">
        <h2 className="mb-6 text-center text-2xl font-bold text-pink-500">IO.FIFA</h2>

        {error && <p className="mb-4 text-sm text-red-500">{error}</p>}

        <div className="space-y-5">
          <div className="text-center mb-4">
            <Button
              variant="solid"
              onClick={handleEntraLogin}
            >
              <MicrosoftIcon fontSize={"medium"} />
              <span>Sign In With Microsoft Entra</span>
            </Button>
          </div>
          <div className="text-center mb-5">
            <Button
              variant="outlined"
              onClick={handleLogoutRedirect}
            >
              <ExitToAppOutlinedIcon fontSize={"medium"} />
              <span>Sign Out Of Microsoft Entra</span>
            </Button>
          </div>
        </div>

        <p className="mt-6 text-center text-sm text-gray-600">
          <Link href="/" className="font-medium text-pink-500 hover:underline">
            Go back
          </Link>
        </p>
      </div>
    </div>
  );
};

export default EntraLogin;