import { useCallback, useState } from 'react';
import {
  ActionIcon,
  Button,
  Group,
  Paper,
  RingProgress,
  Stack,
  Text,
  Tooltip,
} from '@mantine/core';
import { IconX } from '@tabler/icons-react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { PROFILE_FIELD_SECTION, useCurrentProfile } from '@ema-platform/auth';

const DISMISS_KEY = 'ema-portal-profile-nudge-dismissed';

/** Nothing below this is worth interrupting anyone about. */
const NUDGE_THRESHOLD = 100;

/** How many gaps to name before falling back to a count. */
const MAX_LISTED_GAPS = 3;

function readDismissed(): boolean {
  try {
    return localStorage.getItem(DISMISS_KEY) === 'true';
  } catch {
    // Private mode — treat as not dismissed rather than hiding the nudge.
    return false;
  }
}

/**
 * A prompt to finish the profile. Explicitly not a gate.
 *
 * The applicant can dismiss it, and dismissing it persists. It never prevents
 * navigation and never appears on top of anything — replacing the wizard with
 * a modal would just be the same wall in a smaller box.
 */
export function ProfileCompletionNudge() {
  const { t } = useTranslation();
  const { completeness, missing, isLoading } = useCurrentProfile();
  const [dismissed, setDismissed] = useState(readDismissed);

  const dismiss = useCallback(() => {
    setDismissed(true);
    try {
      localStorage.setItem(DISMISS_KEY, 'true');
    } catch {
      // Not persisting a dismissal is a smaller problem than crashing here.
    }
  }, []);

  if (isLoading || dismissed || completeness >= NUDGE_THRESHOLD) return null;

  const topGaps = missing.slice(0, MAX_LISTED_GAPS);
  const remaining = missing.length - topGaps.length;
  const firstSection = topGaps.length ? PROFILE_FIELD_SECTION[topGaps[0]] : 'personal';

  return (
    <Paper withBorder radius="md" p="md">
      <Group justify="space-between" wrap="nowrap" align="flex-start">
        <Group wrap="nowrap" gap="md" align="center">
          <RingProgress
            size={64}
            thickness={6}
            roundCaps
            sections={[{ value: completeness, color: 'emaPrimary' }]}
            label={
              <Text ta="center" fw={700} size="xs">
                {completeness}%
              </Text>
            }
          />
          <Stack gap={2}>
            <Text fw={600} size="sm">
              {t('profileNudge.title', 'Finish setting up your profile')}
            </Text>
            <Text size="xs" c="dimmed">
              {t('profileNudge.body', {
                fields: topGaps
                  .map((field) => t(`profileFields.${field}`, { defaultValue: field }))
                  .join(', '),
                defaultValue: 'Still needed: {{fields}}',
              })}
              {remaining > 0 &&
                ` ${t('profileNudge.andMore', {
                  count: remaining,
                  defaultValue: 'and {{count}} more',
                })}`}
            </Text>
          </Stack>
        </Group>

        <Group gap="xs" wrap="nowrap">
          <Button
            component={Link}
            to={`/profile#${firstSection}`}
            size="xs"
            variant="light"
          >
            {t('profileNudge.action', 'Complete profile')}
          </Button>
          <Tooltip label={t('profileNudge.dismiss', 'Dismiss')}>
            <ActionIcon
              variant="subtle"
              color="gray"
              onClick={dismiss}
              aria-label={t('profileNudge.dismiss', 'Dismiss')}
            >
              <IconX size={16} />
            </ActionIcon>
          </Tooltip>
        </Group>
      </Group>
    </Paper>
  );
}
