import React, { useMemo, useState } from 'react';
import Box from '@mui/material/Box';
import Card from '@mui/material/Card';
import CardHeader from '@mui/material/CardHeader';
import CardContent from '@mui/material/CardContent';
import Typography from '@mui/material/Typography';
import Chip from '@mui/material/Chip';
import Badge from '@mui/material/Badge';
import Divider from '@mui/material/Divider';
import CircularProgress from '@mui/material/CircularProgress';
import WarningIcon from '@mui/icons-material/Warning';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import { Trans, t } from '@lingui/macro';
import { useLingui } from '@lingui/react';
import { useFeatureFlag } from '../../hooks/useFeatureFlag';
import { useClassSessions } from '../../hooks/useClassSessions';
import { styleForSessionStatus } from '../../utils/classSlice';
import ClassSessionDetailModal from './ClassSessionDetailModal';
import type { ClassSession } from '../../types/class';

interface ClassesAtRiskPanelProps {
  berId: number;
}

function getIsoWeekRange(today: Date): { from: string; to: string } {
  const d: Date = new Date(today);
  d.setHours(0, 0, 0, 0);
  const day: number = d.getDay();
  const diffToMonday: number = day === 0 ? -6 : 1 - day;
  const monday: Date = new Date(d);
  monday.setDate(d.getDate() + diffToMonday);
  const sunday: Date = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  const toIso = (dt: Date): string => {
    const y: string = String(dt.getFullYear());
    const m: string = String(dt.getMonth() + 1).padStart(2, '0');
    const dd: string = String(dt.getDate()).padStart(2, '0');
    return `${y}-${m}-${dd}`;
  };
  return { from: toIso(monday), to: toIso(sunday) };
}

const ClassesAtRiskPanel: React.FC<ClassesAtRiskPanelProps> = ({ berId }) => {
  const { i18n } = useLingui();
  const classesFlag = useFeatureFlag('classes_v1');
  const classesV1Enabled: boolean = classesFlag.enabled;

  const { from, to } = useMemo(() => getIsoWeekRange(new Date()), []);

  const { sessions, loading, reload } = useClassSessions({
    berId,
    from,
    to,
    enabled: classesV1Enabled,
  });

  const [selectedId, setSelectedId] = useState<number | null>(null);

  const atRisk: ClassSession[] = useMemo(
    () =>
      sessions.filter(
        (cs: ClassSession) =>
          cs.zcs_status === 'pending_assignment' || cs.zcs_status === 'unstaffed'
      ),
    [sessions]
  );

  const grouped: Map<string, ClassSession[]> = useMemo(() => {
    const map: Map<string, ClassSession[]> = new Map();
    for (const cs of atRisk) {
      const key: string = cs.becken?.zb_name ?? '—';
      const arr: ClassSession[] = map.get(key) ?? [];
      arr.push(cs);
      map.set(key, arr);
    }
    for (const arr of map.values()) {
      arr.sort((a: ClassSession, b: ClassSession) => {
        if (a.zcs_date !== b.zcs_date) return a.zcs_date.localeCompare(b.zcs_date);
        return a.zcs_start_time.localeCompare(b.zcs_start_time);
      });
    }
    return map;
  }, [atRisk]);

  if (!classesV1Enabled) {
    return null;
  }

  const renderRow = (cs: ClassSession): React.ReactElement => {
    const style = styleForSessionStatus(cs.zcs_status);
    const templateName: string = cs.template?.zct_name ?? `#${cs.zcs_class_template_id}`;
    const startShort: string = cs.zcs_start_time?.substring(0, 5) ?? '';
    const endShort: string = cs.zcs_end_time?.substring(0, 5) ?? '';
    return (
      <Box
        key={cs.zcs_id}
        onClick={() => setSelectedId(cs.zcs_id)}
        sx={{
          display: 'flex',
          alignItems: 'center',
          gap: 1,
          px: 1,
          py: 0.75,
          borderRadius: 1,
          cursor: 'pointer',
          '&:hover': { bgcolor: 'action.hover' },
        }}
      >
        <Typography variant="caption" sx={{ fontWeight: 600, minWidth: 68 }}>
          {cs.zcs_date}
        </Typography>
        <Typography variant="caption" color="text.secondary" sx={{ minWidth: 80 }}>
          {startShort}–{endShort}
        </Typography>
        <Typography variant="body2" sx={{ flex: 1, minWidth: 0 }} noWrap>
          {templateName}
        </Typography>
        <Chip
          size="small"
          label={style.label}
          sx={{
            height: 20,
            fontSize: '0.65rem',
            backgroundColor: style.bg,
            color: style.textColor,
            border: style.border,
          }}
        />
      </Box>
    );
  };

  return (
    <>
      <Card sx={{ mb: 2 }}>
        <CardHeader
          avatar={
            <Badge badgeContent={atRisk.length} color="warning" max={99}>
              <WarningIcon color={atRisk.length > 0 ? 'warning' : 'disabled'} />
            </Badge>
          }
          title={
            <Typography variant="subtitle1" fontWeight={600}>
              <Trans>Klassen at Risk</Trans>
            </Typography>
          }
          subheader={
            <Typography variant="caption" color="text.secondary">
              {i18n._(t`Aktuelle Woche (${from} – ${to})`)}
            </Typography>
          }
          sx={{ pb: 1 }}
        />
        <CardContent sx={{ pt: 0 }}>
          {loading && (
            <Box sx={{ display: 'flex', justifyContent: 'center', py: 2 }}>
              <CircularProgress size={20} />
            </Box>
          )}
          {!loading && atRisk.length === 0 && (
            <Box
              sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 1,
                py: 1.5,
                color: 'text.secondary',
              }}
            >
              <CheckCircleIcon fontSize="small" sx={{ color: 'success.main' }} />
              <Typography variant="body2">
                <Trans>Alle Klassen zugewiesen</Trans>
              </Typography>
            </Box>
          )}
          {!loading &&
            atRisk.length > 0 &&
            Array.from(grouped.entries()).map(([beckenName, rows], idx: number) => (
              <Box key={beckenName} sx={{ mb: idx < grouped.size - 1 ? 1.5 : 0 }}>
                <Typography
                  variant="caption"
                  sx={{
                    fontWeight: 700,
                    color: 'text.secondary',
                    textTransform: 'uppercase',
                    letterSpacing: '0.05em',
                    fontSize: '0.65rem',
                  }}
                >
                  {beckenName}
                </Typography>
                <Divider sx={{ mb: 0.5, mt: 0.25 }} />
                {rows.map(renderRow)}
              </Box>
            ))}
        </CardContent>
      </Card>
      <ClassSessionDetailModal
        open={selectedId !== null}
        sessionId={selectedId}
        berId={berId}
        onClose={() => setSelectedId(null)}
        onChanged={() => {
          reload();
        }}
        canApprove={false}
        canCancel={false}
        canResolve={false}
      />
    </>
  );
};

export default ClassesAtRiskPanel;
