import React from 'react';
import {
  Alert,
  AlertTitle,
  Box,
  Link,
  Typography,
} from '@mui/material';
import { NotificationsActive as NotificationsActiveIcon } from '@mui/icons-material';
import { Link as RouterLink } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { atemschutzApi } from '../../services/atemschutz';
import type { User } from '../../types/auth.types';
import type { AtemschutzUebersicht } from '../../types/atemschutz.types';
import { WidgetCard } from '../templates/WidgetCard';

// ── Constants ─────────────────────────────────────────────────────────────────

/** Show a warning banner if a deadline is within this many days. */
const WARNING_THRESHOLD_DAYS = 60;

// ── Types ─────────────────────────────────────────────────────────────────────

interface PersonalWarning {
  key: string;
  /** Negative = overdue, 0 = today, positive = days remaining. */
  tageRest: number;
  label: string;
  /** Short description of what the user should do */
  action: string;
}

// ── Helpers ───────────────────────────────────────────────────────────────────

function buildWarnings(record: AtemschutzUebersicht): PersonalWarning[] {
  const warnings: PersonalWarning[] = [];

  if (record.untersuchung_tage_rest !== null && record.untersuchung_tage_rest <= WARNING_THRESHOLD_DAYS) {
    warnings.push({
      key: 'untersuchung',
      tageRest: record.untersuchung_tage_rest,
      label: 'Atemschutz-Untersuchung',
      action: 'Termin beim Betriebsarzt vereinbaren',
    });
  }

  if (record.leistungstest_tage_rest !== null && record.leistungstest_tage_rest <= WARNING_THRESHOLD_DAYS) {
    warnings.push({
      key: 'leistungstest',
      tageRest: record.leistungstest_tage_rest,
      label: 'Leistungstest',
      action: 'Atemschutzwart kontaktieren',
    });
  }

  return warnings;
}

function tageText(tage: number): string {
  if (tage < 0) {
    const abs = Math.abs(tage);
    return `seit ${abs} Tag${abs === 1 ? '' : 'en'} überfällig`;
  }
  if (tage === 0) return 'heute fällig';
  return `fällig in ${tage} Tag${tage === 1 ? '' : 'en'}`;
}

// ── Component ─────────────────────────────────────────────────────────────────

interface PersonalWarningsBannerProps {
  user: User;
  /** Called with the number of active warnings (for badge display) */
  onWarningCount?: (count: number) => void;
}

const PersonalWarningsBanner: React.FC<PersonalWarningsBannerProps> = ({ user: _user, onWarningCount }) => {
  const { data: record, isLoading } = useQuery<AtemschutzUebersicht | null>({
    queryKey: ['atemschutz-my-status'],
    queryFn: () => atemschutzApi.getMyStatus(),
  });

  // ── Loading state ──────────────────────────────────────────────────────────

  if (isLoading) {
    return (
      <WidgetCard
        title="Persönliche Warnungen"
        icon={<NotificationsActiveIcon fontSize="small" />}
        isLoading
      />
    );
  }

  // ── No atemschutz record for this user ─────────────────────────────────────

  if (!record) return null;

  // ── Build warnings list ────────────────────────────────────────────────────

  const warnings = buildWarnings(record);

  if (warnings.length === 0) {
    onWarningCount?.(0);
    return null;
  }

  onWarningCount?.(warnings.length);

  // ── Render ─────────────────────────────────────────────────────────────────

  // Split into overdue (error) and upcoming (warning) groups.
  const overdue  = warnings.filter((w) => w.tageRest < 0);
  const upcoming = warnings.filter((w) => w.tageRest >= 0);

  return (
    <WidgetCard
      title={`Persönliche Warnungen (${warnings.length})`}
      icon={
        <NotificationsActiveIcon
          fontSize="small"
          sx={{ color: overdue.length > 0 ? 'error.dark' : 'warning.dark' }}
        />
      }
      sx={{
        border: '1px solid',
        borderColor: overdue.length > 0 ? 'error.main' : 'warning.main',
      }}
    >
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1.5 }}>
        {overdue.length > 0 && (
          <Alert severity="error" variant="outlined">
            <AlertTitle sx={{ fontWeight: 600 }}>Überfällig — Handlungsbedarf</AlertTitle>
            <Box component="ul" sx={{ m: 0, pl: 2 }}>
              {overdue.map((w) => (
                <Box key={w.key} component="li" sx={{ mb: 0.5 }}>
                  <Link
                    component={RouterLink}
                    to="/atemschutz"
                    color="inherit"
                    underline="hover"
                    sx={{ fontWeight: 500 }}
                  >
                    {w.label}
                  </Link>
                  {' — '}
                  <Typography component="span" variant="body2">
                    {tageText(w.tageRest)}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" sx={{ mt: 0.25 }}>
                    → {w.action}
                  </Typography>
                </Box>
              ))}
            </Box>
          </Alert>
        )}

        {upcoming.length > 0 && (
          <Alert severity="warning" variant="outlined">
            <AlertTitle sx={{ fontWeight: 600 }}>Frist läuft bald ab</AlertTitle>
            <Box component="ul" sx={{ m: 0, pl: 2 }}>
              {upcoming.map((w) => (
                <Box key={w.key} component="li" sx={{ mb: 0.5 }}>
                  <Link
                    component={RouterLink}
                    to="/atemschutz"
                    color="inherit"
                    underline="hover"
                    sx={{ fontWeight: 500 }}
                  >
                    {w.label}
                  </Link>
                  {' — '}
                  <Typography component="span" variant="body2">
                    {tageText(w.tageRest)}
                  </Typography>
                  <Typography variant="body2" color="text.secondary" sx={{ mt: 0.25 }}>
                    → {w.action}
                  </Typography>
                </Box>
              ))}
            </Box>
          </Alert>
        )}
      </Box>
    </WidgetCard>
  );
};

export default PersonalWarningsBanner;
