import React, { useMemo } from "react";
import {
  ActivityIndicator,
  FlatList,
  Pressable,
  StyleSheet,
  Text,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import type { MobileIntervention } from "../../types/intervention";
import {
  detailValue,
  formatInterventionDate,
  getFluideLabel,
  getStatusStyle,
  getTypeLabel,
  isDoneStatus,
  isTodoStatus,
} from "../../shared/interventionUtils";

type Props = {
  interventions: MobileIntervention[];
  loadingInterventions: boolean;
  interventionsError: string | null;
  isOnline: boolean;
  syncingQueue: boolean;
  brandColor: string;
  activeTab: "todo" | "done";
  onChangeTab: (tab: "todo" | "done") => void;
  onRefresh: () => void;
  onOpenDetail: (id: number) => void;
};

function InterventionCard({
  intervention,
  brandColor,
  onOpenDetail,
}: Readonly<{
  intervention: MobileIntervention;
  brandColor: string;
  onOpenDetail: (id: number) => void;
}>) {
  const status = getStatusStyle(intervention.statut);
  return (
    <View style={styles.historyCard}>
      <View style={styles.historyHeader}>
        <Text style={styles.historyTitle}>
          {intervention.titre || `Intervention #${intervention.id}`}
        </Text>
        <View
          style={[
            styles.statusChip,
            { backgroundColor: status.backgroundColor, borderColor: status.borderColor },
          ]}
        >
          <Text style={[styles.statusChipText, { color: status.color }]}>{status.label}</Text>
        </View>
      </View>

      <View style={styles.infoGrid}>
        <View style={styles.infoItem}>
          <Text style={styles.infoLabel}>Date</Text>
          <Text style={styles.infoValue}>{formatInterventionDate(intervention.date_prevue)}</Text>
        </View>
        <View style={styles.infoItem}>
          <Text style={styles.infoLabel}>Site</Text>
          <Text style={styles.infoValue}>{detailValue(intervention.site_nom)}</Text>
        </View>
        <View style={styles.infoItem}>
          <Text style={styles.infoLabel}>Machine</Text>
          <Text style={styles.infoValue}>{detailValue(intervention.machine_nom)}</Text>
        </View>
        <View style={styles.infoItem}>
          <Text style={styles.infoLabel}>Type mission</Text>
          <Text style={styles.infoValue}>{getTypeLabel(intervention.type_intervention)}</Text>
        </View>
        <View style={styles.infoItem}>
          <Text style={styles.infoLabel}>Type fluide</Text>
          <Text style={styles.infoValue}>{getFluideLabel(intervention)}</Text>
        </View>
        <View style={styles.infoItem}>
          <Text style={styles.infoLabel}>Numero R</Text>
          <Text style={styles.infoValue}>{detailValue(intervention.numero_r)}</Text>
        </View>
      </View>

      <Pressable
        style={[styles.openDetailButton, { backgroundColor: brandColor }]}
        onPress={() => onOpenDetail(intervention.id)}
      >
        <Text style={styles.openDetailText}>Voir le detail mission</Text>
      </Pressable>
    </View>
  );
}

function ConnectivityBadge({ isOnline }: Readonly<{ isOnline: boolean }>) {
  return (
    <View
      style={[styles.connectivityBadge, isOnline ? styles.connectivityOnline : styles.connectivityOffline]}
    >
      <Text
        style={[styles.connectivityText, isOnline ? styles.connectivityTextOnline : styles.connectivityTextOffline]}
      >
        {isOnline ? "Etat reseau: en ligne" : "Etat reseau: hors ligne"}
      </Text>
    </View>
  );
}

function TabsRow({
  activeTab,
  brandColor,
  todoCount,
  doneCount,
  onSwitch,
}: Readonly<{
  activeTab: "todo" | "done";
  brandColor: string;
  todoCount: number;
  doneCount: number;
  onSwitch: (tab: "todo" | "done") => void;
}>) {
  return (
    <View style={styles.tabsRow}>
      <Pressable
        style={[
          styles.tab,
          activeTab === "todo" && { backgroundColor: brandColor, borderColor: brandColor },
        ]}
        onPress={() => onSwitch("todo")}
      >
        <Text style={[styles.tabText, activeTab === "todo" && styles.tabTextActive]}>
          À faire ({todoCount})
        </Text>
      </Pressable>
      <Pressable
        style={[
          styles.tab,
          activeTab === "done" && { backgroundColor: "#16a34a", borderColor: "#16a34a" },
        ]}
        onPress={() => onSwitch("done")}
      >
        <Text style={[styles.tabText, activeTab === "done" && styles.tabTextActive]}>
          Terminées ({doneCount})
        </Text>
      </Pressable>
    </View>
  );
}

function InterventionsList({
  loading,
  activeTab,
  visibleList,
  renderItem,
  contentBottomPadding,
}: Readonly<{
  loading: boolean;
  activeTab: "todo" | "done";
  visibleList: MobileIntervention[];
  renderItem: ({ item }: { item: MobileIntervention }) => React.ReactElement;
  contentBottomPadding: number;
}>) {
  if (loading) {
    return (
      <View style={styles.inlineLoader}>
        <ActivityIndicator size="small" />
        <Text style={styles.mutedText}>Chargement des interventions...</Text>
      </View>
    );
  }
  if (visibleList.length === 0) {
    const emptyMsg =
      activeTab === "todo"
        ? "Aucune mission a faire pour cette periode."
        : "Aucune mission terminee pour cette periode.";
    return <Text style={styles.mutedText}>{emptyMsg}</Text>;
  }
  return (
    <FlatList
      data={visibleList}
      keyExtractor={(item) => String(item.id)}
      renderItem={renderItem}
      contentContainerStyle={[styles.listContent, { paddingBottom: contentBottomPadding }]}
      showsVerticalScrollIndicator={false}
    />
  );
}

export default function MissionsDashboard(props: Readonly<Props>) {
  const {
    interventions,
    loadingInterventions,
    interventionsError,
    isOnline,
    syncingQueue,
    brandColor,
    activeTab,
    onChangeTab,
    onRefresh,
    onOpenDetail,
  } = props;
  const insets = useSafeAreaInsets();

  // activeTab remonte au parent (App.tsx) pour survivre aux remounts du
  // dashboard declenches par les re-renders de App. Sans ca, un refresh
  // declenche par switch d'onglet re-mountait MissionsDashboard et remettait
  // localement le tab a la valeur initiale, ce qui cassait l'UX quand
  // l'utilisateur cliquait sur l'onglet Terminees apres un refresh.
  const switchTab = (tab: "todo" | "done") => {
    if (tab === activeTab) {
      return;
    }
    onChangeTab(tab);
    onRefresh();
  };

  const todoList = useMemo(
    () => interventions.filter((i) => isTodoStatus(i.statut)),
    [interventions]
  );
  const doneList = useMemo(
    () => interventions.filter((i) => isDoneStatus(i.statut)),
    [interventions]
  );
  const visibleList = activeTab === "todo" ? todoList : doneList;

  const renderIntervention = ({ item: intervention }: { item: MobileIntervention }) => (
    <InterventionCard
      intervention={intervention}
      brandColor={brandColor}
      onOpenDetail={onOpenDetail}
    />
  );

  return (
    <View style={styles.wrapper}>
      <ConnectivityBadge isOnline={isOnline} />

      {syncingQueue ? (
        <Text style={styles.syncText}>Synchronisation de la file en cours...</Text>
      ) : null}

      <Pressable
        style={[styles.refreshButton, loadingInterventions && styles.buttonDisabled]}
        onPress={onRefresh}
        disabled={loadingInterventions}
      >
        <Text style={styles.refreshText}>
          {loadingInterventions ? "Rafraichissement..." : "Rafraichir les missions"}
        </Text>
      </Pressable>

      {interventionsError ? <Text style={styles.error}>{interventionsError}</Text> : null}

      <TabsRow
        activeTab={activeTab}
        brandColor={brandColor}
        todoCount={todoList.length}
        doneCount={doneList.length}
        onSwitch={switchTab}
      />

      <InterventionsList
        loading={loadingInterventions}
        activeTab={activeTab}
        visibleList={visibleList}
        renderItem={renderIntervention}
        contentBottomPadding={insets.bottom + 24}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    flex: 1,
    gap: 10,
  },
  listContent: {
    paddingBottom: 12,
  },
  connectivityBadge: {
    borderRadius: 999,
    paddingVertical: 6,
    paddingHorizontal: 10,
    alignSelf: "flex-start",
    borderWidth: 1,
  },
  connectivityOnline: {
    backgroundColor: "#dcfce7",
    borderColor: "#86efac",
  },
  connectivityOffline: {
    backgroundColor: "#fee2e2",
    borderColor: "#fca5a5",
  },
  connectivityText: {
    fontSize: 12,
    fontWeight: "700",
  },
  connectivityTextOnline: {
    color: "#166534",
  },
  connectivityTextOffline: {
    color: "#991b1b",
  },
  syncText: {
    color: "#6a7a96",
  },
  refreshButton: {
    backgroundColor: "#edf3ff",
    borderRadius: 10,
    alignItems: "center",
    paddingVertical: 10,
  },
  refreshText: {
    color: "#1e56a8",
    fontWeight: "600",
  },
  buttonDisabled: {
    opacity: 0.5,
  },
  error: {
    color: "#b00020",
  },
  sectionTitle: {
    fontSize: 17,
    fontWeight: "700",
    color: "#16325c",
    marginBottom: 2,
  },
  tabsRow: {
    flexDirection: "row",
    gap: 8,
    marginBottom: 4,
  },
  tab: {
    flex: 1,
    paddingVertical: 10,
    paddingHorizontal: 10,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#ffffff",
    alignItems: "center",
  },
  tabText: { fontSize: 13, fontWeight: "700", color: "#334155" },
  tabTextActive: { color: "#ffffff" },
  inlineLoader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  mutedText: {
    color: "#6a7a96",
  },
  historyCard: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#f8fbff",
    borderRadius: 12,
    padding: 12,
    gap: 10,
  },
  historyHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    gap: 8,
  },
  historyTitle: {
    flex: 1,
    color: "#16325c",
    fontWeight: "700",
    fontSize: 15,
  },
  statusChip: {
    borderWidth: 1,
    borderRadius: 999,
    paddingVertical: 3,
    paddingHorizontal: 8,
  },
  statusChipText: {
    fontSize: 11,
    fontWeight: "700",
  },
  infoGrid: {
    flexDirection: "row",
    flexWrap: "wrap",
    gap: 8,
  },
  infoItem: {
    minWidth: "47%",
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#e3ebf8",
    borderRadius: 10,
    padding: 8,
  },
  infoLabel: {
    fontSize: 11,
    color: "#66748f",
    fontWeight: "600",
    marginBottom: 2,
  },
  infoValue: {
    fontSize: 13,
    color: "#1f2f4f",
    fontWeight: "600",
  },
  openDetailButton: {
    borderRadius: 8,
    paddingVertical: 8,
    alignItems: "center",
  },
  openDetailText: {
    color: "#ffffff",
    fontWeight: "700",
  },
});
