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

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

/**
 * 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 { t } = useTranslation();
  const navigate = useNavigate();
  const showDate = useDateDisplayer();
  const localized = useLocalized();
  const [tab, setTab] = useState<Tab>('all');
  const EMPTY_COPY: Record<Tab, string> = {
    all: t('notifications.empty.all'),
    unseen: t('notifications.empty.unseen'),
    seen: t('notifications.empty.seen'),
  };
  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}>{t('notifications.title')}</Title>
      <Text size="sm" c="dimmed" mb="md">
        {unread > 0 ? t('notifications.unread', { count: unread }) : t('notifications.allCaughtUp')}
      </Text>

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

      {isLoading ? (
        <PageLoader label={t('notifications.loading')} height={350} />
      ) : 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">
              {t('notifications.emptyBody')}
            </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">
                          {t('notifications.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);
                      }}
                    >
                      {t('notifications.markRead')}
                    </Button>
                  )}
                </Group>
              </Card>
            );
          })}
        </Stack>
      )}
    </Container>
  );
}

export default NotificationsPage;
