import { authClient } from "@code/auth/native";
import { api } from "@code/backend/convex/_generated/api";
import { useQuery } from "convex/react";
import { Button, Spinner, Surface } from "heroui-native";
import { Text, View } from "react-native";

import { Container } from "@/components/container";

export default function Home() {
  const healthCheck = useQuery(api.healthCheck.get);
  const user = useQuery(api.auth.getCurrentUser);

  return (
    <Container className="px-4 pb-4">
      <View className="mb-5 py-6">
        <Text className="text-3xl font-semibold tracking-tight text-foreground">Zopu</Text>
        <Text className="mt-1 text-sm text-muted">Your authenticated workspace</Text>
      </View>

      <Surface className="mb-4 rounded-xl p-4" variant="secondary">
        {user === undefined ? (
          <Spinner size="sm" />
        ) : (
          <View className="flex-row items-center justify-between gap-4">
            <View className="flex-1">
              <Text className="font-medium text-foreground">{user?.name ?? "Signed in"}</Text>
              <Text className="mt-0.5 text-xs text-muted">{user?.email}</Text>
            </View>
            <Button onPress={() => void authClient.signOut()} size="sm" variant="danger">
              <Button.Label>Sign out</Button.Label>
            </Button>
          </View>
        )}
      </Surface>

      <Surface className="rounded-xl p-4" variant="secondary">
        <Text className="mb-2 font-medium text-foreground">API status</Text>
        <View className="flex-row items-center gap-2">
          <View
            className={`h-2 w-2 rounded-full ${healthCheck === "OK" ? "bg-success" : "bg-danger"}`}
          />
          <Text className="text-xs text-muted">
            {healthCheck === undefined
              ? "Checking…"
              : healthCheck === "OK"
                ? "Connected to Convex"
                : "Convex unavailable"}
          </Text>
        </View>
      </Surface>
    </Container>
  );
}
