import { useEffect, useState } from "react";
import {
  AppShell,
  Avatar,
  Badge,
  Box,
  Button,
  Code,
  Group,
  Paper,
  Stack,
  Text,
  Title,
} from "@mantine/core";
import { IconLogout, IconUserCircle } from "@tabler/icons-react";
import { GetSession, Logout } from "../wailsjs/go/main/MatrixService";

interface Session {
  user_id: string;
  device_id: string;
  homeserver_url: string;
  has_token: boolean;
  expires_at?: string;
}

export default function HomeScreen({
  userID,
  onLogout,
}: {
  userID: string;
  onLogout: () => void;
}) {
  const [session, setSession] = useState<Session | null>(null);

  useEffect(() => {
    GetSession(userID).then((s) => setSession(s as Session | null));
  }, [userID]);

  async function handleLogout() {
    try {
      await Logout(userID);
    } finally {
      onLogout();
    }
  }

  const initials = userID
    .replace("@", "")
    .split(":")[0]
    .slice(0, 2)
    .toUpperCase();

  return (
    <AppShell header={{ height: 56 }} padding="md">
      <AppShell.Header>
        <Group h="100%" px="md" justify="space-between">
          <Group gap="xs">
            <IconUserCircle size={22} />
            <Text fw={600}>matrix_client_pc</Text>
            <Badge size="sm" variant="light" color="violet">
              v0.1.0
            </Badge>
          </Group>
          <Button
            variant="subtle"
            color="gray"
            leftSection={<IconLogout size={16} />}
            onClick={handleLogout}
          >
            Logout
          </Button>
        </Group>
      </AppShell.Header>
      <AppShell.Main>
        <Box maw={720} mx="auto" mt="xl">
          <Paper p="xl" radius="lg" withBorder>
            <Group gap="lg" align="flex-start">
              <Avatar size={64} color="violet" radius="xl">
                {initials}
              </Avatar>
              <Stack gap={6} flex={1}>
                <Title order={3}>{userID}</Title>
                {session ? (
                  <Stack gap={4}>
                    <Text size="sm" c="dimmed">
                      Device: <Code>{session.device_id || "-"}</Code>
                    </Text>
                    <Text size="sm" c="dimmed">
                      Homeserver: <Code>{session.homeserver_url}</Code>
                    </Text>
                    {session.expires_at && (
                      <Text size="xs" c="dimmed">
                        Token expira: {session.expires_at}
                      </Text>
                    )}
                  </Stack>
                ) : (
                  <Text c="dimmed">Cargando sesion...</Text>
                )}
              </Stack>
            </Group>
          </Paper>
          <Paper p="md" radius="md" withBorder mt="lg">
            <Text size="sm" c="dimmed">
              Login OK. Sync + rooms + timeline llegan en issue 0148.
            </Text>
          </Paper>
        </Box>
      </AppShell.Main>
    </AppShell>
  );
}
