import React, { useRef, useState } from "react";
import { ActivityIndicator, Modal, Pressable, StyleSheet, Text, View } from "react-native";
import SignatureCanvas, { type SignatureViewRef } from "react-native-signature-canvas";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { saveSignatureBase64ToPermanentFile } from "../core/fileStorage";

type Props = {
  interventionId: number;
  stepId: string;
  brandColor: string;
  onCaptured: (uri: string) => void;
};

function stripDataUrlPrefix(data: string): string {
  const marker = "base64,";
  const idx = data.indexOf(marker);
  if (idx === -1) {
    return data;
  }
  return data.slice(idx + marker.length);
}

export default function SignatureCapture({ interventionId, stepId, brandColor, onCaptured }: Readonly<Props>) {
  const [visible, setVisible] = useState(false);
  const [saving, setSaving] = useState(false);
  const signatureRef = useRef<SignatureViewRef>(null);
  const insets = useSafeAreaInsets();

  const handleOk = async (signatureDataUrl: string) => {
    setSaving(true);
    try {
      const base64 = stripDataUrlPrefix(signatureDataUrl);
      const uri = await saveSignatureBase64ToPermanentFile(interventionId, stepId, base64);
      onCaptured(uri);
      setVisible(false);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <Pressable style={[styles.openButton, { borderColor: brandColor }]} onPress={() => setVisible(true)}>
        <Text style={[styles.openButtonText, { color: brandColor }]}>Signer</Text>
      </Pressable>

      <Modal visible={visible} animationType="slide" onRequestClose={() => setVisible(false)}>
        <View style={styles.modalRoot}>
          <View style={styles.canvasWrap}>
            <SignatureCanvas
              ref={signatureRef}
              onOK={(data) => {
                handleOk(data);
              }}
              onEmpty={() => {}}
              descriptionText=""
              clearText="Effacer"
              confirmText="Valider"
              webStyle={`
                .m-signature-pad--footer { display: flex; justify-content: space-between; }
                body,html { height:100%; }
              `}
            />
          </View>

          <View style={[styles.actions, { paddingBottom: insets.bottom + 16 }]}>
            <Pressable style={styles.secondaryButton} onPress={() => setVisible(false)}>
              <Text style={styles.secondaryButtonText}>Annuler</Text>
            </Pressable>
            <Pressable
              style={[styles.primaryButton, { backgroundColor: brandColor }, saving && styles.disabled]}
              onPress={() => signatureRef.current?.readSignature()}
              disabled={saving}
            >
              {saving ? (
                <ActivityIndicator size="small" color="#ffffff" />
              ) : (
                <Text style={styles.primaryButtonText}>Enregistrer</Text>
              )}
            </Pressable>
          </View>
        </View>
      </Modal>
    </>
  );
}

const styles = StyleSheet.create({
  openButton: {
    borderWidth: 1,
    borderRadius: 8,
    backgroundColor: "#ffffff",
    paddingVertical: 10,
    alignItems: "center",
  },
  openButtonText: {
    fontWeight: "700",
  },
  modalRoot: {
    flex: 1,
    backgroundColor: "#ffffff",
  },
  canvasWrap: {
    flex: 1,
    backgroundColor: "#ffffff",
  },
  actions: {
    flexDirection: "row",
    gap: 10,
    padding: 16,
    borderTopWidth: 1,
    borderTopColor: "#e2e8f0",
  },
  secondaryButton: {
    flex: 1,
    borderRadius: 10,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "#e2e8f0",
    paddingVertical: 12,
  },
  secondaryButtonText: {
    color: "#334155",
    fontWeight: "700",
  },
  primaryButton: {
    flex: 1,
    borderRadius: 10,
    alignItems: "center",
    justifyContent: "center",
    paddingVertical: 12,
  },
  primaryButtonText: {
    color: "#ffffff",
    fontWeight: "700",
  },
  disabled: {
    opacity: 0.6,
  },
});
