import React from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  useTheme,
  Skeleton,
  Grid,
} from '@mui/material';
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  PieChart,
  Pie,
  Cell,
  ResponsiveContainer,
} from 'recharts';
import { EinsatzStats, EINSATZ_ART_LABELS, EinsatzArt } from '../../services/incidents';

// ---------------------------------------------------------------------------
// MONTH LABELS (German locale — avoids date-fns dependency for short labels)
// ---------------------------------------------------------------------------
const MONAT_KURZ = [
  '', // 1-indexed
  'Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun',
  'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez',
];

// ---------------------------------------------------------------------------
// PIE CHART COLORS — keyed by EinsatzArt
// Uses MUI theme palette where possible, fallback to a curated palette
// ---------------------------------------------------------------------------
const ART_COLORS: Record<EinsatzArt, string> = {
  Brand: '#d32f2f',
  THL: '#1976d2',
  ABC: '#7b1fa2',
  BMA: '#f57c00',
  Hilfeleistung: '#388e3c',
  Fehlalarm: '#757575',
  Brandsicherheitswache: '#0288d1',
};

// ---------------------------------------------------------------------------
// HELPERS
// ---------------------------------------------------------------------------

/** Build a full 12-month array from sparse MonthlyStatRow data */
function buildMonthlyData(
  thisYear: { monat: number; anzahl: number }[],
  prevYear: { monat: number; anzahl: number }[],
  currentYear: number
) {
  const map = new Map<number, { thisYear: number; prevYear: number }>();
  for (let m = 1; m <= 12; m++) {
    map.set(m, { thisYear: 0, prevYear: 0 });
  }
  for (const row of thisYear) {
    const existing = map.get(row.monat)!;
    map.set(row.monat, { ...existing, thisYear: row.anzahl });
  }
  for (const row of prevYear) {
    const existing = map.get(row.monat)!;
    map.set(row.monat, { ...existing, prevYear: row.anzahl });
  }
  return Array.from(map.entries()).map(([monat, counts]) => ({
    monat: MONAT_KURZ[monat],
    [String(currentYear)]: counts.thisYear,
    [String(currentYear - 1)]: counts.prevYear,
  }));
}

// ---------------------------------------------------------------------------
// COMPONENT
// ---------------------------------------------------------------------------

interface IncidentStatsChartProps {
  stats: EinsatzStats | null;
  loading?: boolean;
}

const IncidentStatsChart: React.FC<IncidentStatsChartProps> = ({ stats, loading = false }) => {
  const theme = useTheme();

  if (loading || !stats) {
    return (
      <Grid container spacing={3}>
        <Grid item xs={12} md={7}>
          <Card>
            <CardContent>
              <Skeleton variant="text" width={200} height={28} sx={{ mb: 2 }} />
              <Skeleton variant="rectangular" height={260} />
            </CardContent>
          </Card>
        </Grid>
        <Grid item xs={12} md={5}>
          <Card>
            <CardContent>
              <Skeleton variant="text" width={160} height={28} sx={{ mb: 2 }} />
              <Skeleton variant="circular" width={220} height={220} sx={{ mx: 'auto' }} />
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    );
  }

  const monthlyData = buildMonthlyData(
    stats.monthly ?? [],
    stats.prev_year_monthly ?? [],
    stats.jahr
  );

  const pieData = (stats.by_art ?? []).map((row) => ({
    name: EINSATZ_ART_LABELS[row.einsatz_art],
    value: row.anzahl,
    art: row.einsatz_art,
  }));

  const thisYearKey = String(stats.jahr);
  const prevYearKey = String(stats.jahr - 1);

  return (
    <Grid container spacing={3}>
      {/* BAR CHART: Incidents per month (year-over-year) */}
      <Grid item xs={12} md={7}>
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Einsätze pro Monat — {stats.jahr} vs. {stats.jahr - 1}
            </Typography>
            <Box sx={{ width: '100%', height: 280 }}>
              <ResponsiveContainer width="100%" height="100%">
                <BarChart
                  data={monthlyData}
                  margin={{ top: 4, right: 16, left: -8, bottom: 0 }}
                >
                  <CartesianGrid
                    strokeDasharray="3 3"
                    stroke={theme.palette.divider}
                  />
                  <XAxis
                    dataKey="monat"
                    tick={{ fontSize: 12, fill: theme.palette.text.secondary }}
                  />
                  <YAxis
                    allowDecimals={false}
                    tick={{ fontSize: 12, fill: theme.palette.text.secondary }}
                  />
                  <Tooltip
                    contentStyle={{
                      backgroundColor: theme.palette.background.paper,
                      border: `1px solid ${theme.palette.divider}`,
                      borderRadius: 8,
                      fontSize: 13,
                    }}
                  />
                  <Legend
                    wrapperStyle={{ fontSize: 13 }}
                  />
                  <Bar
                    dataKey={thisYearKey}
                    name={thisYearKey}
                    fill={theme.palette.primary.main}
                    radius={[4, 4, 0, 0]}
                  />
                  <Bar
                    dataKey={prevYearKey}
                    name={prevYearKey}
                    fill={theme.palette.secondary.light}
                    radius={[4, 4, 0, 0]}
                    opacity={0.7}
                  />
                </BarChart>
              </ResponsiveContainer>
            </Box>
          </CardContent>
        </Card>
      </Grid>

      {/* PIE CHART: Incidents by Einsatzart */}
      <Grid item xs={12} md={5}>
        <Card>
          <CardContent>
            <Typography variant="h6" gutterBottom>
              Einsatzarten {stats.jahr}
            </Typography>
            {pieData.length === 0 ? (
              <Box
                sx={{
                  height: 260,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <Typography variant="body2" color="text.secondary">
                  Keine Daten für dieses Jahr
                </Typography>
              </Box>
            ) : (
              <Box sx={{ width: '100%', height: 280 }}>
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Pie
                      data={pieData}
                      cx="50%"
                      cy="45%"
                      innerRadius={60}
                      outerRadius={100}
                      paddingAngle={2}
                      dataKey="value"
                      label={({ percent }: { percent: number }) =>
                        percent > 0.05 ? `${(percent * 100).toFixed(0)}%` : ''
                      }
                      labelLine={false}
                    >
                      {pieData.map((entry) => (
                        <Cell
                          key={entry.art}
                          fill={ART_COLORS[entry.art as EinsatzArt] ?? theme.palette.grey[500]}
                        />
                      ))}
                    </Pie>
                    <Tooltip
                      formatter={(value: number, name: string) => [
                        `${value} Einsätze`,
                        name,
                      ]}
                      contentStyle={{
                        backgroundColor: theme.palette.background.paper,
                        border: `1px solid ${theme.palette.divider}`,
                        borderRadius: 8,
                        fontSize: 13,
                      }}
                    />
                    <Legend
                      iconType="circle"
                      iconSize={10}
                      wrapperStyle={{ fontSize: 12, paddingTop: 8 }}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </Box>
            )}
          </CardContent>
        </Card>
      </Grid>
    </Grid>
  );
};

export default IncidentStatsChart;
