"use client";

import { useState, useEffect } from "react";
import axios from "axios";
import { Grid, Typography, CircularProgress, Alert } from "@mui/material";
import PageContainer from "@/app/components/container/PageContainer";
import { getSession } from "@/utils/sessionData";

export default function LinkAccountPage() {
  const [sessionData, setSessionData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 1️⃣ Load session + getAdmin
  useEffect(() => {
    const session = getSession();
    setSessionData(session);

    if (!session?.token) {
      setError("No valid session found");
      setLoading(false);
      return;
    }

    const fetchAdmin = async () => {
      try {
        const response = await axios.post("/api/getAdmin", {
          token: session.token,
        });

        if (response.data.status === "error") {
          throw new Error(response.data.message);
        }

        // (optional) Set admin data if needed
        // setAdmin(response.data.admin);
      } catch (err: any) {
        setError(err.message || "Failed to load admin");
        setLoading(false);
      }
    };

    fetchAdmin();
  }, []);

  // 2️⃣ After sessionData is loaded → call storeCoinFlowBankToken
  useEffect(() => {
    if (!sessionData?.token || !sessionData?.admin_id) return;

    const storeToken = async () => {
      try {
        setLoading(true);

        const response = await axios.post("/api/storeCoinFlowBankToken", {
          userId: sessionData.admin_id,
          token: sessionData.token,
        });

        if (response.data.status === "error") {
          throw new Error(response.data.message);
        }

        // 3️⃣ On success → redirect
        window.location.href = "/cashout";
      } catch (err: any) {
        setError(err.message || "Failed to finalize bank linking");
        setLoading(false);
      }
    };

    storeToken();
  }, [sessionData]);

  return (
    <PageContainer title="Linking Bank Account" description="">
      <Grid
        container
        sx={{
          width: "100%",
          height: "70vh",
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
          justifyContent: "center",
          textAlign: "center",
          gap: 2,
        }}
      >
        {error && <Alert severity="error">{error}</Alert>}

        {!error && (
          <>
            <CircularProgress size={60} />
            <Typography variant="h6" sx={{ mt: 2, fontWeight: 600 }}>
              Linking your bank account…
            </Typography>
            <Typography variant="body2" sx={{ color: "gray" }}>
              Please wait, do not close this page.
            </Typography>
          </>
        )}
      </Grid>
    </PageContainer>
  );
}
