import React, { useEffect, useRef, useState } from "react";
import {
  ActivityIndicator,
  Pressable,
  StyleSheet,
  Text,
  View,
} from "react-native";
import SignatureCanvas, { type SignatureViewRef } from "react-native-signature-canvas";
import { useSafeAreaInsets } from "react-native-safe-area-context";

/**
 * Finalisation d'une intervention : wizard 3 etapes plein ecran pour
 * ne PAS mettre les signature pads dans un ScrollView (le scroll
 * intercepterait les touches et empecherait de dessiner).
 *
 *   1) Signature technicien (obligatoire)
 *   2) Client present / absent (radio)
 *   3) Signature client (si present, sinon skip) + bouton Confirmer
 *
 * A chaque pad, l'utilisateur dessine puis clique "Valider" dans le
 * footer du SignatureCanvas (onOK fire -> on stocke la data URL).
 * Le bouton "Suivant" du wizard verifie que la signature courante
 * est capturee avant de passer a l'etape suivante.
 */
type Props = {
  brandColor: string;
  saving: boolean;
  errorMessage: string | null;
  /**
   * Valeurs initiales hydratees depuis le parent pour survivre au
   * unmount/remount (ex: le user clique "Revenir" puis revient : retrouve
   * ses signatures au lieu de devoir resigner).
   */
  initialTechData?: string;
  initialClientData?: string;
  initialClientPresent?: boolean;
  /**
   * Callback appele a chaque modif d'un champ du wizard (signature
   * capturee, radio presence change). Permet au parent de persister
   * en state et retransmettre au prochain mount.
   */
  onDraftChange?: (draft: {
    techData?: string;
    clientData?: string;
    clientPresent?: boolean;
  }) => void;
  onCancel: () => void;
  onConfirm: (signatures: {
    signature_technicien: string;
    signature_client: string;
    client_present: boolean;
  }) => void;
};

type WizardStep = "tech" | "client_presence" | "client_sig";

export default function SignatureFinishCard(props: Readonly<Props>) {
  const {
    brandColor,
    saving,
    errorMessage,
    initialTechData,
    initialClientData,
    initialClientPresent,
    onDraftChange,
    onCancel,
    onConfirm,
  } = props;
  const insets = useSafeAreaInsets();

  const [step, setStep] = useState<WizardStep>("tech");
  const [techData, setTechData] = useState<string>(initialTechData ?? "");
  const [clientData, setClientData] = useState<string>(initialClientData ?? "");
  const [clientPresent, setClientPresent] = useState<boolean>(
    initialClientPresent ?? true
  );
  const [localError, setLocalError] = useState<string | null>(null);
  // Drapeaux "en attente de capture" : leves quand l'utilisateur clique
  // Suivant/Confirmer. Quand la capture revient (onOK ou onEmpty), on
  // progresse ou on affiche une erreur.
  const [pendingAction, setPendingAction] = useState<null | "tech_next" | "client_confirm">(null);

  const techPadRef = useRef<SignatureViewRef>(null);
  const clientPadRef = useRef<SignatureViewRef>(null);

  // On cache le bouton "Valider" (save) natif du SignatureCanvas car
  // l'utilisateur ne le voyait pas sur certains Android (rendu WebView
  // coupe ou caches). On garde "Effacer" pour corriger une signature.
  // Le "Suivant"/"Confirmer" du wizard declenche lui-meme readSignature()
  // pour capturer la data URL via onOK.
  const padWebStyle = `
    .m-signature-pad { box-shadow: none; border: 1px solid #d8e4f6; border-radius: 8px; }
    .m-signature-pad--body { border: none; }
    .m-signature-pad--footer { display: flex; justify-content: flex-start; padding: 8px 12px; }
    .m-signature-pad--footer .description { display: none; }
    .m-signature-pad--footer .save { display: none; }
    .m-signature-pad--footer .clear { background: #e2e8f0; color: #334155; border-radius: 6px; padding: 8px 18px; border: none; font-weight: 700; font-size: 14px; }
    body, html { height: 100%; margin: 0; }
  `;

  /**
   * "Suivant" depuis l'etape technicien : on demande au pad de remonter
   * sa data URL. Si le pad est vide, onEmpty fire et on affiche une
   * erreur. Sinon onOK fire, techData est set, et l'useEffect ci-dessous
   * progresse l'etape.
   */
  const handleTechNext = () => {
    setLocalError(null);
    setPendingAction("tech_next");
    techPadRef.current?.readSignature();
  };

  // Progression async pilotee par le drapeau pendingAction : on attend
  // le callback onOK (qui set techData) ou onEmpty (qui set pendingAction
  // a null + affiche une erreur) avant d'avancer.
  useEffect(() => {
    if (pendingAction === "tech_next" && techData) {
      setPendingAction(null);
      setStep("client_presence");
    }
    if (pendingAction === "client_confirm" && clientData) {
      setPendingAction(null);
      onConfirm({
        signature_technicien: techData,
        signature_client: clientData,
        client_present: true,
      });
    }
  }, [pendingAction, techData, clientData, onConfirm]);

  // Remonte au parent les changements de draft pour qu'il les persiste
  // et les retransmette au prochain mount (apres un Revenir).
  useEffect(() => {
    onDraftChange?.({ techData, clientData, clientPresent });
  }, [techData, clientData, clientPresent, onDraftChange]);

  const handleClientPresenceNext = () => {
    setLocalError(null);
    if (clientPresent) {
      setStep("client_sig");
    } else {
      // Client absent -> confirmer directement
      onConfirm({
        signature_technicien: techData,
        signature_client: "ABSENT",
        client_present: false,
      });
    }
  };

  /**
   * "Confirmer et terminer" depuis l'etape client signature : meme pattern
   * que handleTechNext — on trigger readSignature et l'useEffect se charge
   * de onConfirm une fois clientData recu via onOK.
   */
  const handleClientSigConfirm = () => {
    setLocalError(null);
    setPendingAction("client_confirm");
    clientPadRef.current?.readSignature();
  };

  const handleBack = () => {
    setLocalError(null);
    if (step === "tech") {
      onCancel();
    } else if (step === "client_presence") {
      setStep("tech");
    } else {
      setStep("client_presence");
    }
  };

  const renderStep = () => {
    if (step === "tech") {
      return (
        <>
          <Text style={styles.title}>Signature du technicien</Text>
          <Text style={styles.subtitle}>
            Signez dans le cadre puis touchez le bouton "Valider" sous le pad.
          </Text>
          <View style={styles.padFullContainer}>
            <SignatureCanvas
              ref={techPadRef}
              /* dataURL permet de re-afficher la signature deja capturee
                 quand on revient sur cette etape (ex: apres un "Revenir").
                 On ne bind PAS a techData en live pour eviter les redraws
                 parasites pendant que le user dessine : initialTechData
                 est stable (vient des props parentes figees au mount). */
              dataURL={initialTechData || undefined}
              onOK={(data) => {
                setTechData(data);
                setLocalError(null);
              }}
              onEmpty={() => {
                setTechData("");
                // Si l'utilisateur a clique Suivant sur un pad vide,
                // l'onEmpty remonte : on annule le pending et on previent.
                if (pendingAction === "tech_next") {
                  setPendingAction(null);
                  setLocalError("Signez dans le cadre avant de passer a l'etape suivante.");
                }
              }}
              descriptionText=""
              clearText="Effacer"
              confirmText="Valider"
              webStyle={padWebStyle}
              autoClear={false}
              imageType="image/png"
            />
          </View>
          <Text style={techData ? styles.padOk : styles.padHint}>
            {techData ? "✓ Signature technicien prete" : "Signez dans le cadre puis touchez 'Suivant →'"}
          </Text>
        </>
      );
    }

    if (step === "client_presence") {
      return (
        <View style={styles.clientPresenceContent}>
          <Text style={styles.title}>Client</Text>
          <Text style={styles.subtitle}>
            Le client est-il present lors de cette intervention ?
          </Text>
          <View style={styles.radioGroup}>
            <Pressable
              style={[
                styles.radioOption,
                clientPresent && { backgroundColor: brandColor, borderColor: brandColor },
              ]}
              onPress={() => setClientPresent(true)}
            >
              <Text style={[styles.radioOptionText, clientPresent && styles.radioOptionTextActive]}>
                ✓ Client present
              </Text>
              <Text style={[styles.radioOptionSubtext, clientPresent && styles.radioOptionTextActive]}>
                Signature du client requise
              </Text>
            </Pressable>
            <Pressable
              style={[
                styles.radioOption,
                !clientPresent && { backgroundColor: brandColor, borderColor: brandColor },
              ]}
              onPress={() => setClientPresent(false)}
            >
              <Text style={[styles.radioOptionText, !clientPresent && styles.radioOptionTextActive]}>
                ✗ Client absent
              </Text>
              <Text style={[styles.radioOptionSubtext, !clientPresent && styles.radioOptionTextActive]}>
                Rapport marque "ABSENT"
              </Text>
            </Pressable>
          </View>
        </View>
      );
    }

    // client_sig
    return (
      <>
        <Text style={styles.title}>Signature du client</Text>
        <Text style={styles.subtitle}>
          Faites signer le client puis touchez "Valider" sous le pad.
        </Text>
        <View style={styles.padFullContainer}>
          <SignatureCanvas
            ref={clientPadRef}
            dataURL={initialClientData || undefined}
            onOK={(data) => {
              setClientData(data);
              setLocalError(null);
            }}
            onEmpty={() => {
              setClientData("");
              if (pendingAction === "client_confirm") {
                setPendingAction(null);
                setLocalError("Le client doit signer dans le cadre avant de confirmer.");
              }
            }}
            descriptionText=""
            clearText="Effacer"
            confirmText="Valider"
            webStyle={padWebStyle}
            autoClear={false}
            imageType="image/png"
          />
        </View>
        <Text style={clientData ? styles.padOk : styles.padHint}>
          {clientData ? "✓ Signature client prete" : "Faites signer le client puis touchez 'Confirmer'"}
        </Text>
      </>
    );
  };

  const renderActions = () => {
    if (step === "tech") {
      return (
        <>
          <Pressable style={styles.backButton} onPress={handleBack} disabled={saving}>
            <Text style={styles.backButtonText}>← Annuler</Text>
          </Pressable>
          <Pressable
            style={[styles.primaryButton, { backgroundColor: brandColor }, saving && styles.buttonDisabled]}
            onPress={handleTechNext}
            disabled={saving}
          >
            <Text style={styles.primaryButtonText}>Suivant →</Text>
          </Pressable>
        </>
      );
    }

    if (step === "client_presence") {
      return (
        <>
          <Pressable style={styles.backButton} onPress={handleBack} disabled={saving}>
            <Text style={styles.backButtonText}>← Revenir</Text>
          </Pressable>
          <Pressable
            style={[
              styles.primaryButton,
              { backgroundColor: clientPresent ? brandColor : "#16a34a" },
              saving && styles.buttonDisabled,
            ]}
            onPress={handleClientPresenceNext}
            disabled={saving}
          >
            {saving ? (
              <ActivityIndicator size="small" color="#ffffff" />
            ) : (
              <Text style={styles.primaryButtonText}>
                {clientPresent ? "Suivant →" : "✅ Terminer (client absent)"}
              </Text>
            )}
          </Pressable>
        </>
      );
    }

    // client_sig
    return (
      <>
        <Pressable style={styles.backButton} onPress={handleBack} disabled={saving}>
          <Text style={styles.backButtonText}>← Revenir</Text>
        </Pressable>
        <Pressable
          style={[styles.primaryButton, { backgroundColor: "#16a34a" }, saving && styles.buttonDisabled]}
          onPress={handleClientSigConfirm}
          disabled={saving}
        >
          {saving ? (
            <ActivityIndicator size="small" color="#ffffff" />
          ) : (
            <Text style={styles.primaryButtonText}>✅ Confirmer et terminer</Text>
          )}
        </Pressable>
      </>
    );
  };

  const stepLabels: Record<WizardStep, string> = {
    tech: "1/3 Technicien",
    client_presence: "2/3 Client",
    client_sig: "3/3 Signature client",
  };
  const stepLabel = stepLabels[step];

  return (
    <View style={[styles.overlay, { paddingTop: insets.top + 8 }]}>
      <View style={styles.header}>
        <Text style={[styles.stepBadge, { color: brandColor }]}>{stepLabel}</Text>
      </View>

      <View style={styles.body}>{renderStep()}</View>

      {localError ? <Text style={styles.errorText}>{localError}</Text> : null}
      {errorMessage ? <Text style={styles.errorText}>{errorMessage}</Text> : null}

      <View style={[styles.actionsBar, { paddingBottom: insets.bottom + 16 }]}>
        {renderActions()}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  overlay: {
    position: "absolute",
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: "#edf2f8",
    zIndex: 100,
    elevation: 100,
  },
  header: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderBottomWidth: 1,
    borderBottomColor: "#d8e4f6",
    backgroundColor: "#ffffff",
  },
  stepBadge: { fontSize: 12, fontWeight: "700", textTransform: "uppercase" },
  body: { flex: 1, padding: 16, gap: 10 },
  title: { fontSize: 20, fontWeight: "700", color: "#16325c" },
  subtitle: { fontSize: 13, color: "#475569", lineHeight: 18 },
  // Le pad prend toute la place disponible : pas de ScrollView,
  // donc les touches vont direct au SignatureCanvas sans conflit.
  padFullContainer: {
    flex: 1,
    backgroundColor: "#ffffff",
    borderRadius: 8,
    overflow: "hidden",
    borderWidth: 1,
    borderColor: "#d8e4f6",
    marginTop: 4,
  },
  padHint: { fontSize: 12, color: "#94a3b8", fontWeight: "600" },
  padOk: { fontSize: 12, color: "#16a34a", fontWeight: "700" },
  clientPresenceContent: { gap: 16 },
  radioGroup: { gap: 12, marginTop: 8 },
  radioOption: {
    paddingVertical: 18,
    paddingHorizontal: 16,
    borderWidth: 2,
    borderColor: "#d8e4f6",
    borderRadius: 10,
    backgroundColor: "#ffffff",
    gap: 4,
  },
  radioOptionText: { fontSize: 16, fontWeight: "700", color: "#334155" },
  radioOptionSubtext: { fontSize: 12, color: "#64748b" },
  radioOptionTextActive: { color: "#ffffff" },
  errorText: {
    color: "#b91c1c",
    fontSize: 13,
    fontWeight: "600",
    paddingHorizontal: 16,
    paddingBottom: 6,
  },
  actionsBar: {
    flexDirection: "row",
    gap: 10,
    padding: 16,
    backgroundColor: "#ffffff",
    borderTopWidth: 1,
    borderTopColor: "#d8e4f6",
  },
  backButton: {
    flex: 1,
    backgroundColor: "#e5e7eb",
    borderRadius: 10,
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 12,
  },
  backButtonText: { color: "#334155", fontWeight: "700" },
  primaryButton: {
    flex: 2,
    borderRadius: 10,
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 12,
  },
  primaryButtonText: { color: "#ffffff", fontWeight: "700", fontSize: 14 },
  buttonDisabled: { opacity: 0.6 },
});
