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

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

import { api } from "../api";
import { clearAuthToken, getAuthToken } 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 token = getAuthToken();
  const [me, setMe] = useState<MeResponse | null>(null);

  useEffect(() => {
    if (!token) {
      setMe(null);
      return;
    }
    api
      .get<MeResponse>("/auth/me")
      .then((r) => setMe(r.data))
      .catch(() => setMe(null));
  }, [token]);

  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>

      {!token ? (
        <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={() => {
                clearAuthToken();
                setMe(null);
                toast(t("signedOut"), "info");
              }}
            >
              {t("signOut")}
            </Button>
          </Box>
        </Box>
      )}
    </Paper>
  );
}
