import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Badge,
  Button,
  Card,
  Center,
  Container,
  Group,
  Loader,
  SegmentedControl,
  Stack,
  Text,
  Title,
} from '@mantine/core';
import { IconBellOff, IconCheck } from '@tabler/icons-react';
import {
  localized,
  useGetNotificationsQuery,
  useGetUnseenNotificationsQuery,
  useMarkNotificationReadMutation,
} from '@ema-platform/api';
import { useDateDisplayer } from '@ema-platform/shared';

type Tab = 'all' | 'unseen' | 'seen';

const EMPTY_COPY: Record<Tab, string> = {
  all: 'No notifications yet.',
  unseen: 'Nothing unread.',
  seen: 'No read notifications.',
};

/**
 * The applicant's notification inbox.
 *
 * Backed by the real notification records the licensing workflow writes at
 * every transition — this previously listed a fixed array of invented alerts.
 */
export function NotificationsPage() {
  const navigate = useNavigate();
  const showDate = useDateDisplayer();
  const [tab, setTab] = useState<Tab>('all');
  const all = useGetNotificationsQuery(undefined, { skip: tab === 'unseen' });
  const unseen = useGetUnseenNotificationsQuery(undefined, { skip: tab !== 'unseen' });
  const [markRead] = useMarkNotificationReadMutation();

  const { data, isLoading } = tab === 'unseen' ? unseen : all;
  const items =
    tab === 'seen' ? (data?.items ?? []).filter((n) => n.isSeen) : (data?.items ?? []);
  const unread = all.data?.items.filter((n) => !n.isSeen).length ?? 0;

  async function open(id: string, seen: boolean, link?: string) {
    if (!seen) await markRead(id);
    if (link) navigate(link);
  }

  return (
    <Container size="md" py="md">
      <Title order={3}>Notifications</Title>
      <Text size="sm" c="dimmed" mb="md">
        {unread > 0 ? `${unread} unread` : 'You are all caught up'}
      </Text>

      <SegmentedControl
        size="xs"
        mb="md"
        value={tab}
        onChange={(v) => setTab(v as Tab)}
        data={[
          { label: 'All', value: 'all' },
          { label: 'Unseen', value: 'unseen' },
          { label: 'Seen', value: 'seen' },
        ]}
      />

      {isLoading ? (
        <Center h={300}>
          <Loader />
        </Center>
      ) : items.length === 0 ? (
        <Card withBorder padding="xl">
          <Stack align="center" gap="xs">
            <IconBellOff size={32} stroke={1.4} color="var(--mantine-color-gray-5)" />
            <Text c="dimmed">{EMPTY_COPY[tab]}</Text>
            <Text size="sm" c="dimmed">
              You will be notified as your applications progress.
            </Text>
          </Stack>
        </Card>
      ) : (
        <Stack gap="xs">
          {items.map((n) => {
            const link = (n.metadata?.['callbackUrl'] as string) ?? undefined;
            return (
              <Card
                key={n.id}
                withBorder
                padding="md"
                radius="md"
                style={{
                  cursor: link ? 'pointer' : 'default',
                  borderLeft: n.isSeen ? undefined : '3px solid var(--mantine-color-blue-5)',
                }}
                onClick={() => open(n.id, n.isSeen, link)}
              >
                <Group justify="space-between" wrap="nowrap" align="flex-start">
                  <div style={{ minWidth: 0 }}>
                    <Group gap="xs" mb={2}>
                      <Text fw={600} size="sm">
                        {localized(n.subject)}
                      </Text>
                      {!n.isSeen && (
                        <Badge size="xs" variant="light">
                          new
                        </Badge>
                      )}
                    </Group>
                    <Text size="sm" c="dimmed">
                      {localized(n.content)}
                    </Text>
                    <Text size="xs" c="dimmed" mt={4}>
                      {showDate(n.createdAt)}
                    </Text>
                  </div>
                  {!n.isSeen && (
                    <Button
                      size="compact-xs"
                      variant="subtle"
                      leftSection={<IconCheck size={12} />}
                      onClick={(e) => {
                        e.stopPropagation();
                        markRead(n.id);
                      }}
                    >
                      Mark read
                    </Button>
                  )}
                </Group>
              </Card>
            );
          })}
        </Stack>
      )}
    </Container>
  );
}

export default NotificationsPage;
