'use client'

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

// components
import Logo from "@/app/(DashboardLayout)/layout/shared/logo/Logo";
import PageContainer from "@/app/components/container/PageContainer";
import AuthLogin from "./AuthLogin";
import { loginType } from "@/app/(DashboardLayout)/types/auth/auth";
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";

export default function Login2() {
  const [isLoading, setIsLoading] = useState<any>(false);
  const [username, setUsername] = useState<any>('');
  const [password, setPassword] = useState<any>('');
  const [error, setError] = useState<any>('')
  const [sessionData, setSessionData] = useState<any>('')
  const router = useRouter();

  const handleLogin = async () => {
    setError('');

    // Basic validation
    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;
    }

    setIsLoading(true);
    try {
      const result = await axios.post('/api/login', { username, password }, {
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (result?.data?.status === 'error') {
        setError(result?.data?.message || 'Login failed.');
      } else {
        setSession({
          token: result?.data?.token,
          admin_id: result?.data?.admin_id,
          role: result?.data?.role,
          username: result?.data?.username,
        })
        setTimeout(() => {
          router.push('/dashboard');
        }, 750)

      }
    } catch (err: any) {
      setError(err.response?.data?.message || 'Something went wrong.');
    } finally {
      setIsLoading(false);
    }
  };
  const fetchSession = async () => {
    const sessionData = getSession()
    setSessionData(sessionData)
  }
  useEffect(() => {
    fetchSession()
  }, [])
  useEffect(() => {
    if (sessionData?.token && sessionData?.admin_id) {
      router.push('/dashboard')
    }
  }, [sessionData])
  return (
    (<PageContainer title="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">
                {/* <Logo /> */}
                <Typography
                  color="textSecondary"
                  variant="h2"
                  fontWeight="600"
                >
                  Kiosk Admin
                </Typography>
              </Box>
              <AuthLogin
                // title={"Login"}
                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>

                    {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 >)
  );
}
