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

import { Box, Button, Paper, Typography } from "@mui/material";

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

type MeResponse = {
  provider?: string;
  id?: string;
  email?: string;
  userName?: string;
  firstName?: string;
  lastName?: string;
  displayName?: string;
  roles?: string[];
  googleLink?: {
    linked: boolean;
    email?: string | null;
  } | null;
};

export default function AuthStatusCard() {
  const { toast } = useToast();
  const { t } = useI18n();
  const [me, setMe] = useState<MeResponse | null>(null);

  useEffect(() => {
    const refresh = () => {
      api
        .get<MeResponse>("/auth/me")
        .then((r) => setMe(r.data))
        .catch(() => setMe(null));
    };

    refresh();
    window.addEventListener("auth-changed", refresh);
    return () => window.removeEventListener("auth-changed", refresh);
  }, []);

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

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

      {!me ? (
        <Typography sx={{ color: "text.secondary" }}>{t("authStatusNotSignedIn")}</Typography>
      ) : (
        <Box sx={{ display: "flex", flexDirection: "column", gap: 0.5 }}>
          <Typography sx={{ color: "text.secondary" }}>
            Signed in{label ? ` as ${label}` : ""}{me?.provider ? ` (${me.provider})` : ""}.
          </Typography>
          {me?.roles && me.roles.length > 0 ? (
            <Typography sx={{ color: "text.secondary" }}>
              {t("authStatusRoles", { roles: me.roles.join(", ") })}
            </Typography>
          ) : null}
          {me?.googleLink?.linked ? (
            <Typography sx={{ color: "text.secondary" }}>
              {t("authStatusGoogleLinked", { suffix: me.googleLink.email ? `: ${me.googleLink.email}` : "." })}
            </Typography>
          ) : null}

          <Box sx={{ mt: 1 }}>
            <Button
              variant="outlined"
              onClick={() => {
                void api.post("/auth/logout").catch(() => undefined).finally(() => {
                  setMe(null);
                  clearAuthClientState();
                  toast(t("signedOut"), "info");
                });
              }}
            >
              {t("signOut")}
            </Button>
          </Box>
        </Box>
      )}
    </Paper>
  );
}
