import { Alert, Button, Card, Center, Loader, Stack, Text } from "@mantine/core";
import { MessageSquare, TriangleAlert } from "lucide-react";

import { PageContainer, PageHeader } from "@/components/page";
import { useChatSso } from "@/features/chat/useChatSso";

/**
 * Chat itself lives at chat.edr.et (Element), not in this app — this page's
 * only job is a fresh one-click sign-in link into it. A real `<a>` (not
 * `window.open()` in a click handler) so the browser never treats it as a
 * blocked popup, and no iframe: Element's own CSP refuses to be framed.
 */
export default function ChatLaunchPage() {
  const { data: url, isLoading, isError, refetch } = useChatSso();

  return (
    <PageContainer>
      <PageHeader title="Chat" subtitle="Internal messaging for EDR staff" />
      <Card withBorder radius="md" p="xl">
        <Center>
          <Stack align="center" gap="md" py="xl">
            {isLoading && <Loader />}

            {isError && (
              <Stack align="center" gap="sm">
                <Alert
                  icon={<TriangleAlert size={18} />}
                  color="red"
                  title="Couldn't get a sign-in link"
                  variant="light"
                >
                  Something went wrong reaching chat. Try again.
                </Alert>
                <Button variant="light" onClick={() => refetch()}>
                  Retry
                </Button>
              </Stack>
            )}

            {url && (
              <Stack align="center" gap="sm">
                <MessageSquare size={40} strokeWidth={1.5} />
                <Text c="dimmed" ta="center" maw={360}>
                  Opens EDR Chat in a new tab, already signed in as you.
                </Text>
                <Button
                  component="a"
                  href={url}
                  target="_blank"
                  rel="noopener noreferrer"
                  leftSection={<MessageSquare size={16} />}
                >
                  Open EDR Chat
                </Button>
              </Stack>
            )}
          </Stack>
        </Center>
      </Card>
    </PageContainer>
  );
}
