import { useState } from "react";
import {
  Button,
  Card,
  Center,
  Stack,
  Text,
  Title,
  Code,
  Alert,
} from "@mantine/core";
import { IconBrandMatrix, IconAlertCircle } from "@tabler/icons-react";
import { Login } from "../wailsjs/go/main/MatrixService";

export default function LoginScreen({ onLogin }: { onLogin: (uid: string) => void }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleClick() {
    setBusy(true);
    setError(null);
    try {
      const uid = await Login();
      onLogin(uid);
    } catch (e: any) {
      setError(String(e?.message ?? e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <Center mih="100vh" p="lg">
      <Card shadow="md" padding="xl" radius="lg" withBorder maw={480} w="100%">
        <Stack gap="lg" align="center">
          <IconBrandMatrix size={48} color="var(--mantine-color-violet-5)" />
          <Stack gap={4} align="center">
            <Title order={2}>matrix_client_pc</Title>
            <Text size="sm" c="dimmed">
              Cliente Matrix nativo PC
            </Text>
          </Stack>
          <Text size="sm" ta="center" c="dimmed" maw={360}>
            Inicia sesion en <Code>matrix-af2f3d.organic-machine.com</Code> via{" "}
            Matrix Authentication Service. Se abrira tu navegador para autorizar.
          </Text>
          {error && (
            <Alert
              icon={<IconAlertCircle size={16} />}
              color="red"
              variant="light"
              w="100%"
            >
              {error}
            </Alert>
          )}
          <Button
            size="md"
            color="violet"
            loading={busy}
            onClick={handleClick}
            fullWidth
          >
            Sign in with Matrix
          </Button>
          <Text size="xs" c="dimmed">
            v0.1.0 (issue 0147)
          </Text>
        </Stack>
      </Card>
    </Center>
  );
}
