import React, { useEffect, useState } from "react";

import { Box, Button, Chip, Paper, TextField, Typography } from "@mui/material";
import { PublicClientApplication } from "@azure/msal-browser";

import { api, getApiErrorMessage } from "../api";
import { clearAuthClientState, getAuthPersistencePreference } from "../auth";
import TwoFactorChallenge from "./TwoFactorChallenge";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";

type MeResponse = {
  provider?: "local" | "google" | "microsoft" | "external";
  email?: string;
  userName?: string;
  displayName?: string;
  firstName?: string;
  lastName?: string;
  microsoftLink?: {
    linked: boolean;
    email?: string | null;
    linkedAt?: string | null;
  } | null;
};

let msalInstance: PublicClientApplication | null = null;
export function getMicrosoftMsalInstance(clientId: string): PublicClientApplication {
  const tenant = (process.env.NEXT_PUBLIC_MICROSOFT_TENANT || "common").trim() || "common";
  msalInstance ??= new PublicClientApplication({
    auth: { clientId, authority: `https://login.microsoftonline.com/${tenant}`, redirectUri: window.location.origin },
  });
  return msalInstance;
}

export default function MicrosoftAuthCard({ onSignedIn, presentation = "account" }: { onSignedIn?: () => void; presentation?: "account" | "sign-in" }) {
  const { toast } = useToast();
  const { t } = useI18n();
  const [me, setMe] = useState<MeResponse | null>(null);
  const [working, setWorking] = useState(false);
  const [pendingToken, setPendingToken] = useState<string | null>(null);
  const [currentPassword, setCurrentPassword] = useState("");

  const clientId = (process.env.NEXT_PUBLIC_MICROSOFT_CLIENT_ID || "").trim();
  const signInOnly = presentation === "sign-in";
  const signedIn = Boolean(me?.provider);
  const actionLabel = signInOnly || !signedIn
    ? t("continueWithMicrosoft")
    : me?.provider === "local" && !me?.microsoftLink?.linked
      ? t("linkWithMicrosoft")
      : t("signInWithMicrosoft");

  async function refreshMe() {
    try {
      const res = await api.get<MeResponse>("/auth/me");
      setMe(res.data);
    } catch {
      setMe(null);
    }
  }

  useEffect(() => {
    if (signInOnly) return;
    void refreshMe();
  }, [signInOnly]);

  useEffect(() => {
    if (signInOnly) return;
    const onAuthChanged = () => { void refreshMe(); };
    window.addEventListener("auth-changed", onAuthChanged);
    return () => window.removeEventListener("auth-changed", onAuthChanged);
  }, [signInOnly]);

  async function handleSignIn() {
    if (!clientId) return;
    setWorking(true);
    try {
      const msal = getMicrosoftMsalInstance(clientId);
      await msal.initialize();
      const result = await msal.loginPopup({ scopes: ["openid", "profile", "email"] });
      const idToken = result.idToken;
      if (!idToken) throw new Error(t("microsoftAuthFailed"));

      if (!signInOnly && me?.provider === "local") {
        const res = await api.post<{ linked: boolean; email?: string | null }>("/auth/microsoft/link", { token: idToken, currentPassword });
        toast(res.data?.email ? t("microsoftLinkedSuccessWithEmail", { email: res.data.email }) : t("microsoftLinkedSuccess"), "success");
        clearAuthClientState();
        setMe(null);
        setCurrentPassword("");
        toast(t("microsoftSecurityChangeSignInAgain"), "info");
      } else {
        const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string; legacyRelinkRequired?: boolean }>("/auth/microsoft/exchange", { token: idToken, rememberMe: getAuthPersistencePreference() === "local" });
        if (res.data?.legacyRelinkRequired) {
          toast(t("microsoftLegacyRelinkEmailSent"), "info");
          return;
        }
        if (res.data?.requiresTwoFactor && res.data.pendingToken) {
          setPendingToken(res.data.pendingToken);
        } else {
          window.dispatchEvent(new Event("auth-changed"));
          toast(t("microsoftSignedIn"), "success");
          onSignedIn?.();
        }
      }
    } catch (e: any) {
      toast(getApiErrorMessage(e, t("microsoftAuthFailed")), "error");
    } finally {
      setWorking(false);
    }
  }

  const signedInName = me?.userName || me?.displayName || [me?.firstName, me?.lastName].filter(Boolean).join(" ") || me?.email || "";

  if (signInOnly) {
    if (pendingToken) {
      return <TwoFactorChallenge
        pendingToken={pendingToken}
        onCancel={() => setPendingToken(null)}
        onSuccess={() => {
          setPendingToken(null);
          window.dispatchEvent(new Event("auth-changed"));
          toast(t("microsoftSignedIn"), "success");
          onSignedIn?.();
        }}
      />;
    }

    return <Button fullWidth variant="outlined" disabled={working || !clientId} onClick={() => void handleSignIn()}>{actionLabel}</Button>;
  }

  return (
    <Paper sx={{ mt: 2, p: 2 }}>
      <Typography variant="h6" sx={{ mb: 1 }}>
        {t("microsoftAccountTitle")}
      </Typography>

      {!clientId && (
        <Typography sx={{ color: "text.secondary" }}>
          {t("microsoftSetupHint")}
        </Typography>
      )}

      {clientId && pendingToken && (
        <TwoFactorChallenge
          pendingToken={pendingToken}
          onCancel={() => setPendingToken(null)}
          onSuccess={() => {
            setPendingToken(null);
            window.dispatchEvent(new Event("auth-changed"));
            toast(t("microsoftSignedIn"), "success");
            onSignedIn?.();
          }}
        />
      )}

      {clientId && !pendingToken && (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 1.25 }}>
          <Box sx={{ display: "flex", gap: 1, flexWrap: "wrap" }}>
            <Chip size="small" label={me?.microsoftLink?.linked ? t("microsoftLinked") : t("microsoftAvailableToLink")} color={me?.microsoftLink?.linked ? "success" : "default"} variant={me?.microsoftLink?.linked ? "filled" : "outlined"} />
            {me?.microsoftLink?.linkedAt ? <Chip size="small" variant="outlined" label={t("microsoftLinkedDate", { date: new Date(me.microsoftLink.linkedAt).toLocaleDateString() })} /> : null}
          </Box>

          {!signedIn ? (
            <Typography sx={{ color: "text.secondary" }}>
              {t("microsoftSignInHint")}
            </Typography>
          ) : me?.provider === "local" ? (
            <Typography sx={{ color: "text.secondary" }}>
              {me.microsoftLink?.linked
                ? t("microsoftLinkedTo", { email: me.microsoftLink.email || t("microsoftLinkedToYourAccount") })
                : t("microsoftBindHint")}
            </Typography>
          ) : (
            <Typography sx={{ color: "text.secondary" }}>
              {t("microsoftExchangeHint")}
            </Typography>
          )}

          <Box sx={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 1 }}>
            <Typography variant="caption" sx={{ color: "text.secondary", fontWeight: 700, letterSpacing: 0.4, textTransform: "uppercase" }}>
              {actionLabel}
            </Typography>
            <Button variant="outlined" disabled={working || (me?.provider === "local" && !currentPassword)} onClick={() => void handleSignIn()}>
              {actionLabel}
            </Button>
          </Box>

          <Box sx={{ display: "flex", alignItems: "center", gap: 2, flexWrap: "wrap" }}>
            {me?.provider === "local" ? (
              <TextField
                size="small"
                label={t("profileCurrentPassword")}
                type="password"
                value={currentPassword}
                onChange={(event) => setCurrentPassword(event.target.value)}
                autoComplete="current-password"
              />
            ) : null}
            {signedIn ? (
              <Button
                variant="outlined"
                onClick={() => {
                  void api.post("/auth/logout").catch(() => undefined).finally(() => {
                    clearAuthClientState();
                    setMe(null);
                    toast(t("signedOut"), "info");
                  });
                }}
              >
                {t("signOut")}
              </Button>
            ) : null}

            {me?.provider === "local" && me.microsoftLink?.linked ? (
              <Button
                variant="outlined"
                color="warning"
                disabled={working || !currentPassword}
                onClick={async () => {
                  try {
                    await api.delete("/auth/microsoft/link", { data: { currentPassword } });
                    clearAuthClientState();
                    setMe(null);
                    setCurrentPassword("");
                    toast(t("microsoftUnlinked"), "info");
                    toast(t("microsoftSecurityChangeSignInAgain"), "info");
                  } catch (e: any) {
                    const msg = e?.response?.data || e?.message || t("microsoftUnlinkFailed");
                    toast(String(msg), "error");
                  }
                }}
              >
                {t("unlinkMicrosoft")}
              </Button>
            ) : null}
          </Box>

          {signedIn && me?.email ? (
            <Typography variant="body2" sx={{ color: "text.secondary" }}>
              {t("signedInAs", { name: signedInName })}
            </Typography>
          ) : null}
        </Box>
      )}
    </Paper>
  );
}
