'use client'

import Link from "next/link";
import {
  Grid, Box, Card, Stack, Typography,
  Button,
  Alert
} from "@mui/material";

import PageContainer from "@/app/components/container/PageContainer";
import AuthLogin from "./AuthLogin";
import CustomTextField from "@/app/components/forms/theme-elements/CustomTextField";
import CustomFormLabel from "@/app/components/forms/theme-elements/CustomFormLabel";

import { useState, useEffect } from "react";
import axios from "axios";
import { useRouter } from "next/navigation";
import { setSession, getSession } from "@/utils/sessionData";
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";

// Google reCAPTCHA
import ReCAPTCHA from "./RecaptchaClientOnly";

export default function Login2() {
  const { executeRecaptcha } = useGoogleReCaptcha();

  const [isLoading, setIsLoading] = useState(false);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [sessionData, setSessionData] = useState<any>(null);
  const [recaptchaToken, setRecaptchaToken] = useState("");

  const router = useRouter();


  // Login handler
  const handleLogin = async () => {
    setError("");

    // Validate fields
    if (!username || username.length < 4) {
      setError("Username must be at least 4 characters long.");
      return;
    }
    if (!password || password.length < 4) {
      setError("Password must be at least 4 characters long.");
      return;
    }

    // reCAPTCHA not loaded yet (FIRST important fix)
    if (!executeRecaptcha) {
      setError("reCAPTCHA is not ready. Please wait 1–2 seconds.");
      return;
    }

    // Safe to call now
    const token = await executeRecaptcha("login_action");
    setRecaptchaToken(token);

    setIsLoading(true);

    try {
      const result = await axios.post("/api/login", {
        username,
        password,
        recaptcha: token,
      });

      if (result.data.status === "error") {
        setError(result.data.message);
      } else {
        // success
        setSession({
          token: result.data.accessToken,
          admin_id: result.data.user.id,
          role: result.data.user.role,
          username: result.data.user.username,
        });

        router.push("/dashboard");
      }
    } catch (err: any) {
      setError(err.response?.data?.message || "Something went wrong.");
    } finally {
      setIsLoading(false);
    }
  };

  // Load session
  const fetchSession = async () => {
    const sessionData = getSession();
    setSessionData(sessionData);
  };

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

  useEffect(() => {
    if (sessionData?.token && sessionData?.admin_id) {
      router.push("/dashboard");
    }
  }, [sessionData]);

  return (
    
    <PageContainer title="Emanage Login" description="this is Sample page">
      <Box
        sx={{
          position: "relative",
          "&:before": {
            content: '""',
            background: "radial-gradient(#d2f1df, #d3d7fa, #bad8f4)",
            backgroundSize: "400% 400%",
            animation: "gradient 15s ease infinite",
            position: "absolute",
            height: "100%",
            width: "100%",
            opacity: "0.3",
          },
        }}
      >
        <Grid
          container
          spacing={0}
          justifyContent="center"
          sx={{ height: "100vh" }}
        >
          <Grid
            display="flex"
            justifyContent="center"
            alignItems="center"
            size={{ xs: 12, sm: 12, lg: 5, xl: 4 }}
          >
            <Card
              elevation={9}
              sx={{ p: 4, zIndex: 1, width: "100%", maxWidth: "450px" }}
            >
              <Box display="flex" alignItems="center" justifyContent="center">
                <Typography color="textSecondary" variant="h2" fontWeight="600">
                  Emanage Login
                </Typography>
              </Box>

              <AuthLogin
                subtitle={
                  <Stack>
                    <Box>
                      <CustomFormLabel htmlFor="username">Username</CustomFormLabel>
                      <CustomTextField
                        id="username"
                        variant="outlined"
                        fullWidth
                        value={username}
                        onChange={(e: any) => setUsername(e.target.value)}
                      />
                    </Box>

                    <Box>
                      <CustomFormLabel htmlFor="password">Password</CustomFormLabel>
                      <CustomTextField
                        id="password"
                        type="password"
                        variant="outlined"
                        fullWidth
                        value={password}
                        onChange={(e: any) => setPassword(e.target.value)}
                      />
                    </Box>

                    {/* GOOGLE RECAPTCHA */}
                    {/* <Box mt={2} sx={{ display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                      <ReCAPTCHA
                        sitekey="6LcpKxMsAAAAAKw2QwFw1Sp7iHdv79cDd09FDOXa"
                        onChange={(token: any) => setRecaptchaToken(token || "")}
                      />
                    </Box> */}

                    {error && (
                      <>
                        <br />
                        <Alert variant="filled" severity="error" className="text-center">
                          {error}
                        </Alert>
                      </>
                    )}

                    <br />
                    <Box>
                      <Button
                        color="primary"
                        variant="contained"
                        size="large"
                        fullWidth
                        onClick={handleLogin}
                        disabled={isLoading}
                      >
                        {isLoading ? "Signing In..." : "Sign In"}
                      </Button>
                    </Box>
                  </Stack>
                }
              />
            </Card>
          </Grid>
        </Grid>
      </Box>
    </PageContainer>
  );
}
