import React, { useCallback, useEffect, useState } from "react";
import {
  ActivityIndicator,
  Alert,
  Modal,
  Pressable,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { getMyBottles, postBottleAction, type BottleAction } from "../../services/bottlesApi";
import type { MobileBottle } from "../../types/bottle";

type Props = {
  brandColor: string;
};

const TYPE_LABELS: Record<string, string> = {
  gaz: "Gaz frigorigene",
  recup: "Recuperation",
  transf: "Transfert",
};

const STATUT_STYLES: Record<
  string,
  { label: string; color: string; backgroundColor: string; borderColor: string }
> = {
  commandee: {
    label: "Commandee",
    color: "#1d4ed8",
    backgroundColor: "#dbeafe",
    borderColor: "#93c5fd",
  },
  en_service: {
    label: "En service",
    color: "#166534",
    backgroundColor: "#dcfce7",
    borderColor: "#86efac",
  },
  retour_demande: {
    label: "Retour demande",
    color: "#92400e",
    backgroundColor: "#ffedd5",
    borderColor: "#fdba74",
  },
};

type ActionDescriptor = {
  action: BottleAction;
  label: string;
  primary: boolean;
  question: string;
  // Action a formulaire (echange) : ouvre une modale au lieu d'un simple
  // Alert de confirmation.
  needsForm?: boolean;
};

// Types valides d'une nouvelle bouteille (echange). Miroir de
// BouteilleGaz::TYPES_VALIDES cote backend.
const EXCHANGE_TYPES: { value: string; label: string }[] = [
  { value: "gaz", label: "Gaz frigorigene" },
  { value: "recup", label: "Recuperation" },
  { value: "transf", label: "Transfert" },
];

// Actions tech disponibles selon le statut — cycle complet, miroir des
// transitions backend (api/bouteilles_gaz.php) :
//   en_service     -> request_return
//   retour_demande -> confirm_drop (depose) | exchange (echange) | drop_to_stock
const ACTIONS_BY_STATUT: Record<string, ActionDescriptor[]> = {
  en_service: [
    {
      action: "request_return",
      label: "Demander le retour",
      primary: true,
      question: "Demander le retour de cette bouteille ?",
    },
  ],
  retour_demande: [
    {
      action: "confirm_drop",
      label: "Confirmer le depot fournisseur",
      primary: true,
      question: "Confirmer le depot de cette bouteille chez le fournisseur ?",
    },
    {
      action: "exchange",
      label: "Echanger chez le fournisseur",
      primary: false,
      question: "",
      needsForm: true,
    },
    {
      action: "drop_to_stock",
      label: "Rendre au stock central",
      primary: false,
      question: "Rendre cette bouteille au stock central ?",
    },
  ],
};

function statutStyle(statut: string) {
  return (
    STATUT_STYLES[statut] || {
      label: statut || "-",
      color: "#374151",
      backgroundColor: "#f3f4f6",
      borderColor: "#d1d5db",
    }
  );
}

function BottleCard({
  bottle,
  brandColor,
  busy,
  onAction,
}: Readonly<{
  bottle: MobileBottle;
  brandColor: string;
  busy: boolean;
  onAction: (descriptor: ActionDescriptor, bottle: MobileBottle) => void;
}>) {
  const status = statutStyle(bottle.statut);
  const actions = ACTIONS_BY_STATUT[bottle.statut] || [];
  return (
    <View style={styles.card}>
      <View style={styles.cardHeader}>
        <Text style={styles.code}>{bottle.code_interne || `#${bottle.id}`}</Text>
        <View
          style={[
            styles.chip,
            { backgroundColor: status.backgroundColor, borderColor: status.borderColor },
          ]}
        >
          <Text style={[styles.chipText, { color: status.color }]}>{status.label}</Text>
        </View>
      </View>
      <Text style={styles.type}>{TYPE_LABELS[bottle.type] || bottle.type}</Text>
      {bottle.numero_serie_fournisseur ? (
        <Text style={styles.meta}>N° serie: {bottle.numero_serie_fournisseur}</Text>
      ) : null}
      {bottle.date_reception ? (
        <Text style={styles.meta}>Recue le {bottle.date_reception}</Text>
      ) : bottle.date_commande ? (
        <Text style={styles.meta}>Commandee le {bottle.date_commande}</Text>
      ) : null}

      {actions.length > 0 ? (
        <View style={styles.actionsRow}>
          {busy ? (
            <View style={styles.inlineLoader}>
              <ActivityIndicator size="small" />
              <Text style={styles.muted}>Action en cours...</Text>
            </View>
          ) : (
            actions.map((descriptor) => (
              <Pressable
                key={descriptor.action}
                style={[
                  styles.actionButton,
                  descriptor.primary
                    ? { backgroundColor: brandColor }
                    : styles.actionButtonNeutral,
                ]}
                onPress={() => onAction(descriptor, bottle)}
              >
                <Text
                  style={[
                    styles.actionText,
                    descriptor.primary ? styles.actionTextPrimary : styles.actionTextNeutral,
                  ]}
                >
                  {descriptor.label}
                </Text>
              </Pressable>
            ))
          )}
        </View>
      ) : null}
    </View>
  );
}

type LoadState =
  | { kind: "loading" }
  | { kind: "unavailable" }
  | { kind: "error"; message: string }
  | { kind: "ready"; bottles: MobileBottle[]; count: number; quota: number };

// Carte "Mes bouteilles de gaz" du dashboard coolcare, version mobile branchee
// sur /api/mobile/bottles.php (liste) + /api/mobile/bottle_action.php (actions
// tech). Tolere l'absence des endpoints (404) pour rester compatible avec une
// instance coolcare/missioflow non mise a jour.
export default function BottlesScreen({ brandColor }: Readonly<Props>) {
  const insets = useSafeAreaInsets();
  const [state, setState] = useState<LoadState>({ kind: "loading" });
  const [busyId, setBusyId] = useState<number | null>(null);
  const [actionMessage, setActionMessage] = useState<string | null>(null);
  // Etat de la modale d'echange (action a formulaire).
  const [exchangeBottle, setExchangeBottle] = useState<MobileBottle | null>(null);
  const [exchangeSerial, setExchangeSerial] = useState("");
  const [exchangeType, setExchangeType] = useState<string | null>(null);
  const [exchangeComment, setExchangeComment] = useState("");
  const [exchangeSubmitting, setExchangeSubmitting] = useState(false);
  const [exchangeError, setExchangeError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setState({ kind: "loading" });
    try {
      const result = await getMyBottles();
      if (!result.available) {
        setState({ kind: "unavailable" });
        return;
      }
      setState({
        kind: "ready",
        bottles: result.payload.bottles,
        count: result.payload.count,
        quota: result.payload.quota,
      });
    } catch (error) {
      setState({
        kind: "error",
        message: error instanceof Error ? error.message : "Erreur de chargement",
      });
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  // Actions simples (confirmation -> appel -> reload). L'erreur metier remonte
  // en Alert. Utilise pour request_return / confirm_drop / drop_to_stock.
  const performSimpleAction = useCallback(
    async (action: BottleAction, bottleId: number) => {
      setBusyId(bottleId);
      setActionMessage(null);
      try {
        await postBottleAction(action, bottleId);
        setActionMessage("Action effectuee.");
        await load();
      } catch (error) {
        Alert.alert("Action impossible", error instanceof Error ? error.message : "Erreur");
      } finally {
        setBusyId(null);
      }
    },
    [load]
  );

  const closeExchange = useCallback(() => {
    setExchangeBottle(null);
    setExchangeSerial("");
    setExchangeType(null);
    setExchangeComment("");
    setExchangeError(null);
    setExchangeSubmitting(false);
  }, []);

  const runAction = useCallback(
    (descriptor: ActionDescriptor, bottle: MobileBottle) => {
      if (descriptor.needsForm) {
        // Echange : on ouvre la modale (n° serie + type de la nouvelle bouteille).
        setExchangeError(null);
        setExchangeSerial("");
        setExchangeType(null);
        setExchangeComment("");
        setExchangeBottle(bottle);
        return;
      }
      Alert.alert(bottle.code_interne || `Bouteille #${bottle.id}`, descriptor.question, [
        { text: "Annuler", style: "cancel" },
        { text: "Confirmer", onPress: () => void performSimpleAction(descriptor.action, bottle.id) },
      ]);
    },
    [performSimpleAction]
  );

  const submitExchange = useCallback(async () => {
    if (!exchangeBottle) {
      return;
    }
    const serial = exchangeSerial.trim();
    if (serial === "") {
      setExchangeError("Le numero de serie de la nouvelle bouteille est requis.");
      return;
    }
    if (!exchangeType) {
      setExchangeError("Choisissez le type de la nouvelle bouteille.");
      return;
    }

    setExchangeSubmitting(true);
    setExchangeError(null);
    try {
      await postBottleAction("exchange", exchangeBottle.id, {
        numero_serie_nouvelle: serial,
        type_nouvelle: exchangeType,
        commentaire: exchangeComment.trim() || undefined,
      });
      closeExchange();
      setActionMessage("Echange effectue.");
      await load();
    } catch (error) {
      setExchangeError(error instanceof Error ? error.message : "Echange impossible");
      setExchangeSubmitting(false);
    }
  }, [exchangeBottle, exchangeSerial, exchangeType, exchangeComment, closeExchange, load]);

  return (
    <>
    <ScrollView
      style={styles.screen}
      contentContainerStyle={[styles.content, { paddingBottom: insets.bottom + 24 }]}
      showsVerticalScrollIndicator={false}
    >
      {state.kind === "loading" ? (
        <View style={styles.inlineLoader}>
          <ActivityIndicator size="small" />
          <Text style={styles.muted}>Chargement des bouteilles...</Text>
        </View>
      ) : null}

      {state.kind === "unavailable" ? (
        <View style={styles.notice}>
          <Text style={styles.noticeIcon}>🛢️</Text>
          <Text style={styles.noticeTitle}>Bientot disponible</Text>
          <Text style={styles.noticeText}>
            Cette instance n'expose pas encore le suivi des bouteilles sur mobile.
            Consultez vos bouteilles depuis l'application web en attendant.
          </Text>
        </View>
      ) : null}

      {state.kind === "error" ? (
        <View style={styles.notice}>
          <Text style={styles.noticeTitle}>Chargement impossible</Text>
          <Text style={styles.noticeText}>{state.message}</Text>
          <Pressable style={[styles.retryButton, { backgroundColor: brandColor }]} onPress={load}>
            <Text style={styles.retryText}>Reessayer</Text>
          </Pressable>
        </View>
      ) : null}

      {state.kind === "ready" ? (
        <>
          <View style={styles.summaryRow}>
            <Text style={styles.summaryText}>
              {state.count} bouteille{state.count > 1 ? "s" : ""} attribuee
              {state.count > 1 ? "s" : ""}
              {state.quota > 0 ? ` / ${state.quota} max` : ""}
            </Text>
            <Pressable onPress={load}>
              <Text style={[styles.refreshLink, { color: brandColor }]}>Rafraichir</Text>
            </Pressable>
          </View>

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

          {state.bottles.length === 0 ? (
            <Text style={styles.muted}>Aucune bouteille active ne vous est attribuee.</Text>
          ) : (
            state.bottles.map((bottle) => (
              <BottleCard
                key={bottle.id}
                bottle={bottle}
                brandColor={brandColor}
                busy={busyId === bottle.id}
                onAction={runAction}
              />
            ))
          )}
        </>
      ) : null}
    </ScrollView>

    <Modal
      visible={exchangeBottle !== null}
      transparent
      animationType="slide"
      onRequestClose={exchangeSubmitting ? undefined : closeExchange}
    >
      <View style={styles.modalOverlay}>
        <View style={[styles.modalCard, { paddingBottom: insets.bottom + 16 }]}>
          <Text style={styles.modalTitle}>
            Echange — {exchangeBottle?.code_interne || `#${exchangeBottle?.id ?? ""}`}
          </Text>
          <Text style={styles.modalSubtitle}>
            Renseignez la nouvelle bouteille recue chez le fournisseur. L'ancienne
            sera marquee comme retournee.
          </Text>

          <Text style={styles.fieldLabel}>Numero de serie (nouvelle bouteille)</Text>
          <TextInput
            style={styles.input}
            value={exchangeSerial}
            onChangeText={setExchangeSerial}
            placeholder="Ex: FR-2024-00123"
            autoCapitalize="characters"
            editable={!exchangeSubmitting}
          />

          <Text style={styles.fieldLabel}>Type</Text>
          <View style={styles.typeRow}>
            {EXCHANGE_TYPES.map((t) => {
              const selected = exchangeType === t.value;
              return (
                <Pressable
                  key={t.value}
                  style={[
                    styles.typeChip,
                    selected
                      ? { backgroundColor: brandColor, borderColor: brandColor }
                      : null,
                  ]}
                  onPress={() => setExchangeType(t.value)}
                  disabled={exchangeSubmitting}
                >
                  <Text style={[styles.typeChipText, selected ? styles.typeChipTextActive : null]}>
                    {t.label}
                  </Text>
                </Pressable>
              );
            })}
          </View>

          <Text style={styles.fieldLabel}>Commentaire (optionnel)</Text>
          <TextInput
            style={[styles.input, styles.inputMultiline]}
            value={exchangeComment}
            onChangeText={setExchangeComment}
            placeholder="Note libre"
            multiline
            editable={!exchangeSubmitting}
          />

          {exchangeError ? <Text style={styles.modalError}>{exchangeError}</Text> : null}

          <View style={styles.modalButtons}>
            <Pressable
              style={[styles.modalButton, styles.modalCancel]}
              onPress={closeExchange}
              disabled={exchangeSubmitting}
            >
              <Text style={styles.modalCancelText}>Annuler</Text>
            </Pressable>
            <Pressable
              style={[styles.modalButton, { backgroundColor: brandColor }, exchangeSubmitting && styles.disabled]}
              onPress={() => void submitExchange()}
              disabled={exchangeSubmitting}
            >
              {exchangeSubmitting ? (
                <ActivityIndicator size="small" color="#ffffff" />
              ) : (
                <Text style={styles.modalValidateText}>Valider l'echange</Text>
              )}
            </Pressable>
          </View>
        </View>
      </View>
    </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  screen: {
    flex: 1,
    backgroundColor: "#edf2f8",
  },
  content: {
    padding: 16,
    gap: 12,
  },
  inlineLoader: {
    flexDirection: "row",
    alignItems: "center",
    gap: 8,
  },
  muted: {
    color: "#6a7a96",
  },
  summaryRow: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
  },
  summaryText: {
    color: "#16325c",
    fontWeight: "700",
  },
  refreshLink: {
    fontWeight: "700",
  },
  actionMessage: {
    color: "#1c7f45",
    fontWeight: "600",
  },
  card: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#ffffff",
    borderRadius: 12,
    padding: 14,
    gap: 6,
  },
  cardHeader: {
    flexDirection: "row",
    justifyContent: "space-between",
    alignItems: "center",
    gap: 8,
  },
  code: {
    fontSize: 16,
    fontWeight: "800",
    color: "#16325c",
    letterSpacing: 1,
  },
  chip: {
    borderWidth: 1,
    borderRadius: 999,
    paddingVertical: 3,
    paddingHorizontal: 8,
  },
  chipText: {
    fontSize: 11,
    fontWeight: "700",
  },
  type: {
    color: "#334155",
    fontWeight: "600",
  },
  meta: {
    color: "#6a7a96",
    fontSize: 12,
  },
  actionsRow: {
    marginTop: 6,
    gap: 8,
  },
  actionButton: {
    borderRadius: 8,
    paddingVertical: 10,
    alignItems: "center",
  },
  actionButtonNeutral: {
    backgroundColor: "#eef3fb",
    borderWidth: 1,
    borderColor: "#d8e4f6",
  },
  actionText: {
    fontWeight: "700",
    fontSize: 13,
  },
  actionTextPrimary: {
    color: "#ffffff",
  },
  actionTextNeutral: {
    color: "#1e56a8",
  },
  notice: {
    backgroundColor: "#ffffff",
    borderWidth: 1,
    borderColor: "#d8e4f6",
    borderRadius: 14,
    padding: 20,
    gap: 10,
    alignItems: "center",
  },
  noticeIcon: {
    fontSize: 44,
  },
  noticeTitle: {
    fontSize: 18,
    fontWeight: "800",
    color: "#16325c",
  },
  noticeText: {
    color: "#475569",
    fontSize: 14,
    lineHeight: 20,
    textAlign: "center",
  },
  retryButton: {
    borderRadius: 8,
    paddingVertical: 10,
    paddingHorizontal: 18,
  },
  retryText: {
    color: "#ffffff",
    fontWeight: "700",
  },
  disabled: {
    opacity: 0.6,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: "rgba(15, 23, 42, 0.45)",
    justifyContent: "flex-end",
  },
  modalCard: {
    backgroundColor: "#ffffff",
    borderTopLeftRadius: 18,
    borderTopRightRadius: 18,
    padding: 20,
    gap: 8,
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: "800",
    color: "#16325c",
  },
  modalSubtitle: {
    color: "#6a7a96",
    fontSize: 13,
    marginBottom: 4,
  },
  fieldLabel: {
    fontSize: 12,
    fontWeight: "700",
    color: "#66748f",
    marginTop: 6,
  },
  input: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    borderRadius: 10,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
    color: "#1f2f4f",
    backgroundColor: "#f8fbff",
  },
  inputMultiline: {
    minHeight: 60,
    textAlignVertical: "top",
  },
  typeRow: {
    flexDirection: "row",
    gap: 8,
    flexWrap: "wrap",
  },
  typeChip: {
    borderWidth: 1,
    borderColor: "#d8e4f6",
    backgroundColor: "#ffffff",
    borderRadius: 999,
    paddingVertical: 8,
    paddingHorizontal: 12,
  },
  typeChipText: {
    fontSize: 13,
    fontWeight: "700",
    color: "#334155",
  },
  typeChipTextActive: {
    color: "#ffffff",
  },
  modalError: {
    color: "#b00020",
    fontWeight: "600",
    marginTop: 6,
  },
  modalButtons: {
    flexDirection: "row",
    gap: 10,
    marginTop: 14,
  },
  modalButton: {
    flex: 1,
    borderRadius: 10,
    paddingVertical: 12,
    alignItems: "center",
    justifyContent: "center",
  },
  modalCancel: {
    backgroundColor: "#eef3fb",
    borderWidth: 1,
    borderColor: "#d8e4f6",
  },
  modalCancelText: {
    color: "#1e56a8",
    fontWeight: "700",
  },
  modalValidateText: {
    color: "#ffffff",
    fontWeight: "800",
  },
});
