import React, { useMemo } from "react";
import { ScrollView, StyleSheet, Text, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { MobileIntervention } from "../../types/intervention";
import { formatInterventionDate, isDoneStatus, isTodoStatus } from "../../shared/interventionUtils";

type Props = {
  interventions: MobileIntervention[];
  brandColor: string;
};

function parseDate(value: string | undefined): Date | null {
  if (!value) {
    return null;
  }
  const parsed = new Date(value.replace(" ", "T"));
  return Number.isNaN(parsed.getTime()) ? null : parsed;
}

function StatTile({
  value,
  label,
  brandColor,
}: Readonly<{ value: string | number; label: string; brandColor: string }>) {
  return (
    <View style={styles.tile}>
      <Text style={[styles.tileValue, { color: brandColor }]}>{value}</Text>
      <Text style={styles.tileLabel}>{label}</Text>
    </View>
  );
}

// Statistiques calculees cote mobile a partir des interventions deja chargees
// (aucun appel reseau). Equivalent allege de la carte "Statistiques" du
// dashboard coolcare. Le "temps moyen" cote web n'est pas reproductible ici car
// les dates debut/fin ne figurent pas dans la liste mobile : on s'en tient aux
// compteurs reellement disponibles.
export default function StatsScreen({ interventions, brandColor }: Readonly<Props>) {
  const insets = useSafeAreaInsets();

  const stats = useMemo(() => {
    const now = new Date();
    const month = now.getMonth();
    const year = now.getFullYear();
    const todayStr = now.toDateString();

    let todo = 0;
    let done = 0;
    let thisMonth = 0;
    let today = 0;
    let last: Date | null = null;

    for (const intervention of interventions) {
      if (isTodoStatus(intervention.statut)) {
        todo += 1;
      }
      if (isDoneStatus(intervention.statut)) {
        done += 1;
      }

      // Les compteurs "ce mois" / "aujourd'hui" ne comptent que les
      // interventions a faire ou terminees, jamais les annulees (ni un statut
      // inconnu) : sinon les chiffres divergent du reste de l'app qui exclut
      // 'annulee' (cf. interventionUtils).
      const counts = isTodoStatus(intervention.statut) || isDoneStatus(intervention.statut);
      const date = parseDate(intervention.date_prevue);
      if (date) {
        if (counts && date.getMonth() === month && date.getFullYear() === year) {
          thisMonth += 1;
        }
        if (counts && date.toDateString() === todayStr) {
          today += 1;
        }
        if (isDoneStatus(intervention.statut) && (!last || date > last)) {
          last = date;
        }
      }
    }

    return {
      total: interventions.length,
      todo,
      done,
      thisMonth,
      today,
      lastLabel: last ? formatInterventionDate(last.toISOString()) : "Aucune",
    };
  }, [interventions]);

  return (
    <ScrollView
      style={styles.screen}
      contentContainerStyle={[styles.content, { paddingBottom: insets.bottom + 24 }]}
      showsVerticalScrollIndicator={false}
    >
      <Text style={styles.heading}>Activite</Text>
      <View style={styles.grid}>
        <StatTile value={stats.today} label="Aujourd'hui" brandColor={brandColor} />
        <StatTile value={stats.thisMonth} label="Ce mois" brandColor={brandColor} />
        <StatTile value={stats.todo} label="A faire" brandColor={brandColor} />
        <StatTile value={stats.done} label="Terminees" brandColor={brandColor} />
      </View>

      <View style={styles.row}>
        <Text style={styles.rowLabel}>Total interventions</Text>
        <Text style={styles.rowValue}>{stats.total}</Text>
      </View>
      <View style={styles.row}>
        <Text style={styles.rowLabel}>Derniere intervention terminee</Text>
        <Text style={styles.rowValue}>{stats.lastLabel}</Text>
      </View>

      <Text style={styles.note}>
        Statistiques calculees a partir des missions chargees sur cet appareil.
      </Text>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    backgroundColor: "#edf2f8",
  },
  content: {
    padding: 16,
    gap: 12,
  },
  heading: {
    fontSize: 16,
    fontWeight: "700",
    color: "#16325c",
  },
  grid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 12,
  },
  tile: {
    flexBasis: "47%",
    flexGrow: 1,
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#d8e4f6",
    borderRadius: 14,
    paddingVertical: 18,
    alignItems: "center",
    gap: 4,
  },
  tileValue: {
    fontSize: 30,
    fontWeight: "800",
  },
  tileLabel: {
    fontSize: 12,
    color: "#6a7a96",
    fontWeight: "700",
  },
  row: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#e3ebf8",
    borderRadius: 12,
    padding: 14,
  },
  rowLabel: {
    flex: 1,
    color: "#334155",
    fontWeight: "600",
  },
  rowValue: {
    color: "#16325c",
    fontWeight: "800",
  },
  note: {
    color: "#6a7a96",
    fontSize: 12,
    marginTop: 4,
  },
});
