"use client";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { GoogleSignInButton } from "@/app/(auth)/AuthProviders";
import useAxios from "@/hooks/useAxios";
import React, { useCallback, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type GoogleStatus = {
  linked: boolean;
  email: string | null;
  auth_provider?: string;
};

export default function GoogleAccountSettingsPage() {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const [status, setStatus] = useState<GoogleStatus | null>(null);
  const [loading, setLoading] = useState(true);

  const loadStatus = useCallback(async () => {
    setLoading(true);
    try {
      const data = (await request("GET", "/auth/google/status")) as GoogleStatus;
      setStatus(data);
    } catch {
      toast.error(t("settings.edit.googleAccount.loadError"));
    } finally {
      setLoading(false);
    }
  }, [request, t]);

  useEffect(() => {
    loadStatus();
  }, [loadStatus]);

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.edit.nav.googleAccount")}</PageTitle>
        <div className="mx-auto flex max-w-md flex-col items-center py-8 text-center">
          {loading ? (
            <p className="text-sm text-neutral-500">{t("common.loading")}</p>
          ) : status?.linked ? (
            <>
              <p className="text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.googleAccount.linkedHint")}
              </p>
              {status.email ? (
                <p className="mt-3 text-sm font-semibold" dir="ltr">
                  {status.email}
                </p>
              ) : null}
            </>
          ) : (
            <>
              <p className="mb-6 text-sm text-neutral-600 dark:text-neutral-300">
                {t("settings.edit.googleAccount.unlinkedHint")}
              </p>
              <GoogleSignInButton mode="link" onLinked={loadStatus} />
            </>
          )}
        </div>
      </Container>
    </LocalePageShell>
  );
}
