import {
  Alert,
  Box,
  Button,
  Card,
  FormControl,
  FormLabel,
  Input,
  Tab,
  TabList,
  TabPanel,
  Tabs,
  Typography,
} from "@mui/joy";
import { useState } from "react";
import { Navigate, useLocation } from "react-router";
import { useAuth } from "../context/auth-context";
import { AxiosError } from "axios";

type AuthMode = "login" | "register";

export function Login() {
  const location = useLocation();
  const { login, register, loading, isAuthenticated } = useAuth();
  const [mode, setMode] = useState<AuthMode>("login");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [registerUsername, setRegisterUsername] = useState("");
  const [registerPassword, setRegisterPassword] = useState("");
  const [registerConfirm, setRegisterConfirm] = useState("");
  const [loginError, setLoginError] = useState<string | null>(null);
  const [registerError, setRegisterError] = useState<string | null>(null);

  const redirectTo = (location.state as { from?: string } | null)?.from ?? "/";

  if (isAuthenticated) {
    return <Navigate to={redirectTo} replace />;
  }

  const handleLoginSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoginError(null);

    try {
      await login({ username, password });
    } catch (err) {
      if (err instanceof AxiosError && err.response?.status === 401) {
        setLoginError("Invalid username or password");
      } else if (err instanceof Error) {
        setLoginError(err.message);
      } else {
        setLoginError("Login failed");
      }
    }
  };

  const handleRegisterSubmit = async (
    event: React.FormEvent<HTMLFormElement>
  ) => {
    event.preventDefault();
    setRegisterError(null);

    if (registerPassword.length < 8) {
      setRegisterError("Password must be at least 8 characters long");
      return;
    }

    if (registerPassword !== registerConfirm) {
      setRegisterError("Passwords do not match");
      return;
    }

    try {
      await register({
        username: registerUsername,
        password: registerPassword,
      });
    } catch (err) {
      if (err instanceof AxiosError && err.response?.status === 409) {
        setRegisterError("Username already exists");
      } else if (err instanceof Error) {
        setRegisterError(err.message);
      } else {
        setRegisterError("Registration failed");
      }
    }
  };

  return (
    <Box
      sx={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        backgroundColor: "background.level1",
        px: 2,
      }}
    >
      <Card sx={{ width: "100%", maxWidth: 420, p: 3, gap: 2 }}>
        <Box>
          <Typography level="title-lg" fontWeight={600}>
            {mode === "login" ? "Welcome back" : "Create an account"}
          </Typography>
          <Typography level="body-sm" textColor="neutral.500">
            {mode === "login"
              ? "Sign in to manage your AWS Sigma functions"
              : "Register a new operator account for AWS Sigma"}
          </Typography>
        </Box>
        <Tabs
          value={mode}
          onChange={(_event, value) => setMode(value as AuthMode)}
          sx={{ mt: 1 }}
        >
          <TabList
            sx={{
              px: 1,
            }}
          >
            <Tab value="login">Sign in</Tab>
            <Tab value="register">Register</Tab>
          </TabList>
          <TabPanel value="login" sx={{ px: 0 }}>
            <form onSubmit={handleLoginSubmit}>
              <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
                <FormControl required>
                  <FormLabel>Username</FormLabel>
                  <Input
                    type="text"
                    placeholder="ogurechek"
                    value={username}
                    onChange={(event) => setUsername(event.target.value)}
                  />
                </FormControl>
                <FormControl required>
                  <FormLabel>Password</FormLabel>
                  <Input
                    type="password"
                    placeholder="••••••••"
                    value={password}
                    onChange={(event) => setPassword(event.target.value)}
                  />
                </FormControl>
                {loginError && (
                  <Alert color="danger" variant="soft">
                    {loginError}
                  </Alert>
                )}
                <Button
                  type="submit"
                  loading={loading && mode === "login"}
                  disabled={!username || !password}
                >
                  Sign in
                </Button>
              </Box>
            </form>
          </TabPanel>
          <TabPanel value="register" sx={{ px: 0 }}>
            <form onSubmit={handleRegisterSubmit}>
              <Box sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
                <FormControl required>
                  <FormLabel>Username</FormLabel>
                  <Input
                    type="text"
                    placeholder="ogurechek"
                    value={registerUsername}
                    onChange={(event) =>
                      setRegisterUsername(event.target.value)
                    }
                  />
                </FormControl>
                <FormControl required>
                  <FormLabel>Password</FormLabel>
                  <Input
                    type="password"
                    placeholder="Minimum 8 characters"
                    value={registerPassword}
                    onChange={(event) =>
                      setRegisterPassword(event.target.value)
                    }
                  />
                </FormControl>
                <FormControl required>
                  <FormLabel>Confirm password</FormLabel>
                  <Input
                    type="password"
                    placeholder="Repeat your password"
                    value={registerConfirm}
                    onChange={(event) => setRegisterConfirm(event.target.value)}
                  />
                </FormControl>
                {registerError && (
                  <Alert color="danger" variant="soft">
                    {registerError}
                  </Alert>
                )}
                <Button
                  type="submit"
                  loading={loading && mode === "register"}
                  disabled={
                    !registerUsername || !registerPassword || !registerConfirm
                  }
                >
                  Create account
                </Button>
              </Box>
            </form>
          </TabPanel>
        </Tabs>
      </Card>
    </Box>
  );
}
