import {
  Anchor,
  Button,
  Center,
  Paper,
  PasswordInput,
  Stack,
  Text,
  TextInput,
  Title,
} from "@mantine/core";
import { IconLayoutKanban } from "@tabler/icons-react";
import { useEffect, useState } from "react";
import { useAuth } from "../auth";
import * as api from "../api";

type Mode = "login" | "register";

export function LoginPage() {
  const auth = useAuth();
  const [mode, setMode] = useState<Mode>("login");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [registrationEnabled, setRegistrationEnabled] = useState(false);
  const [appVersion, setAppVersion] = useState<string>("");

  useEffect(() => {
    api
      .getFlags()
      .then((f) => setRegistrationEnabled(!!f["registration-enabled"]))
      .catch(() => setRegistrationEnabled(false));
    api
      .getVersion()
      .then((v) => setAppVersion(v.version))
      .catch(() => setAppVersion(""));
  }, []);

  useEffect(() => {
    if (!registrationEnabled && mode === "register") setMode("login");
  }, [registrationEnabled, mode]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setSubmitting(true);
    try {
      if (mode === "login") {
        await auth.login(username.trim(), password);
      } else {
        await auth.register(username.trim(), password, displayName.trim() || username.trim());
      }
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Center style={{ minHeight: "100vh" }} p="md">
      <Paper p="xl" withBorder radius="md" shadow="md" style={{ width: 360, maxWidth: "100%" }}>
        <form onSubmit={submit}>
          <Stack gap="md">
            <Stack gap={4} align="center">
              <IconLayoutKanban size={36} />
              <Title order={3}>Kanban</Title>
              {appVersion && (
                <Text size="xs" c="dimmed" ff="monospace">v{appVersion}</Text>
              )}
              <Text size="sm" c="dimmed">
                {mode === "login" ? "Inicia sesion" : "Crea una cuenta"}
              </Text>
            </Stack>
            <TextInput
              label="Usuario"
              value={username}
              onChange={(e) => setUsername(e.currentTarget.value)}
              required
              autoFocus
              autoComplete="username"
            />
            {mode === "register" && (
              <TextInput
                label="Nombre (opcional)"
                value={displayName}
                onChange={(e) => setDisplayName(e.currentTarget.value)}
                autoComplete="name"
              />
            )}
            <PasswordInput
              label="Contrasena"
              value={password}
              onChange={(e) => setPassword(e.currentTarget.value)}
              required
              autoComplete={mode === "login" ? "current-password" : "new-password"}
            />
            {error && (
              <Text size="sm" c="red">
                {error}
              </Text>
            )}
            <Button type="submit" loading={submitting} fullWidth>
              {mode === "login" ? "Entrar" : "Registrar"}
            </Button>
            {registrationEnabled ? (
              <Text size="xs" c="dimmed" ta="center">
                {mode === "login" ? "No tienes cuenta?" : "Ya tienes cuenta?"}{" "}
                <Anchor
                  component="button"
                  type="button"
                  size="xs"
                  onClick={() => {
                    setError(null);
                    setMode(mode === "login" ? "register" : "login");
                  }}
                >
                  {mode === "login" ? "Registrate" : "Inicia sesion"}
                </Anchor>
              </Text>
            ) : (
              <Text size="xs" c="dimmed" ta="center">
                Registro de nuevos usuarios deshabilitado.
              </Text>
            )}
          </Stack>
        </form>
      </Paper>
    </Center>
  );
}
