/**
 * Mobile eSign — touch-optimized document signing.
 * DocuSign replacement: pinch-to-zoom, finger signature, type signature.
 */

import React, { useState, useRef, useCallback, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Alert,
  ScrollView,
  PanResponder,
  Dimensions,
} from 'react-native';
import { useTheme } from '../../themes/ThemeProvider';
import { getEnvelope, signDocument } from '../../services/api';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

type SignMode = 'draw' | 'type';

interface SignatureField {
  id: string;
  type: 'signature' | 'initials' | 'date' | 'text';
  label: string;
  required: boolean;
  page: number;
  x: number;
  y: number;
}

interface EnvelopeData {
  id: number;
  document_url: string;
  fields: SignatureField[];
  signer_name: string;
  signer_email: string;
}

export default function SignDocument({ route, navigation }: any) {
  const { theme } = useTheme();
  const { envelopeId } = route.params;
  const [envelope, setEnvelope] = useState<EnvelopeData | null>(null);
  const [signMode, setSignMode] = useState<SignMode>('draw');
  const [typedSignature, setTypedSignature] = useState('');
  const [drawnPath, setDrawnPath] = useState<{ x: number; y: number }[]>([]);
  const [currentField, setCurrentField] = useState<string | null>(null);
  const [signedFields, setSignedFields] = useState<Record<string, string>>({});
  const [submitting, setSubmitting] = useState(false);
  const [showSignPad, setShowSignPad] = useState(false);

  useEffect(() => {
    (async () => {
      const res = await getEnvelope(envelopeId);
      if (res.success && res.data) {
        setEnvelope(res.data as EnvelopeData);
      }
    })();
  }, [envelopeId]);

  const panResponder = useRef(
    PanResponder.create({
      onStartShouldSetPanResponder: () => true,
      onMoveShouldSetPanResponder: () => true,
      onPanResponderMove: (_, gesture) => {
        setDrawnPath((prev) => [...prev, { x: gesture.moveX - 20, y: gesture.moveY }]);
      },
      onPanResponderRelease: () => {},
    })
  ).current;

  const handleFieldTap = (fieldId: string) => {
    const field = envelope?.fields.find((f) => f.id === fieldId);
    if (!field) return;

    if (field.type === 'date') {
      setSignedFields((prev) => ({
        ...prev,
        [fieldId]: new Date().toLocaleDateString('en-US'),
      }));
      return;
    }

    setCurrentField(fieldId);
    setShowSignPad(true);
    setDrawnPath([]);
    setTypedSignature('');
  };

  const applySignature = () => {
    if (!currentField) return;

    const value = signMode === 'type'
      ? typedSignature
      : drawnPath.length > 5 ? '[drawn_signature]' : '';

    if (!value) {
      Alert.alert('Required', 'Please provide a signature');
      return;
    }

    setSignedFields((prev) => ({ ...prev, [currentField]: value }));
    setShowSignPad(false);
    setCurrentField(null);
  };

  const handleSubmit = async () => {
    if (!envelope) return;

    const requiredFields = envelope.fields.filter((f) => f.required);
    const missing = requiredFields.filter((f) => !signedFields[f.id]);

    if (missing.length > 0) {
      Alert.alert('Incomplete', `${missing.length} required field(s) still need your signature.`);
      return;
    }

    Alert.alert('Confirm Signing', 'By signing, you agree this constitutes your legal signature under the ESIGN Act.', [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Sign & Submit',
        onPress: async () => {
          setSubmitting(true);
          const res = await signDocument(envelopeId, {
            signatures: signedFields,
            signed_at: new Date().toISOString(),
          });
          setSubmitting(false);
          if (res.success) {
            Alert.alert('Signed', 'Document signed successfully.', [
              { text: 'OK', onPress: () => navigation.goBack() },
            ]);
          } else {
            Alert.alert('Error', res.error ?? 'Signing failed');
          }
        },
      },
    ]);
  };

  if (!envelope) {
    return (
      <View style={[styles.loading, { backgroundColor: theme.colors.background }]}>
        <Text style={{ color: theme.colors.textSecondary }}>Loading document...</Text>
      </View>
    );
  }

  const completedCount = Object.keys(signedFields).length;
  const totalFields = envelope.fields.length;

  return (
    <View style={[styles.container, { backgroundColor: theme.colors.background }]}>
      {/* Progress Bar */}
      <View style={[styles.progressBar, { backgroundColor: theme.colors.card }]}>
        <View style={styles.progressInfo}>
          <Text style={[styles.progressText, { color: theme.colors.text }]}>
            {completedCount}/{totalFields} fields signed
          </Text>
          <Text style={[styles.signerName, { color: theme.colors.textSecondary }]}>
            Signer: {envelope.signer_name}
          </Text>
        </View>
        <View style={[styles.progressTrack, { backgroundColor: theme.colors.border }]}>
          <View style={[styles.progressFill, {
            width: totalFields > 0 ? `${(completedCount / totalFields) * 100}%` : '0%',
            backgroundColor: theme.colors.success,
          }]} />
        </View>
      </View>

      {/* Document View with Sign Fields */}
      <ScrollView style={styles.documentArea}>
        <View style={styles.documentPage}>
          <Text style={[styles.docPlaceholder, { color: theme.colors.textSecondary }]}>
            Document preview loads here
          </Text>

          {/* Signature Fields */}
          {envelope.fields.map((field) => {
            const isSigned = !!signedFields[field.id];
            return (
              <TouchableOpacity
                key={field.id}
                style={[
                  styles.signField,
                  {
                    borderColor: isSigned ? theme.colors.success : theme.colors.warning,
                    backgroundColor: isSigned ? theme.colors.success + '10' : theme.colors.warning + '10',
                  },
                ]}
                onPress={() => !isSigned && handleFieldTap(field.id)}
              >
                {isSigned ? (
                  <Text style={[styles.signedValue, { color: theme.colors.success }]}>
                    {signedFields[field.id] === '[drawn_signature]' ? '✓ Signed' : signedFields[field.id]}
                  </Text>
                ) : (
                  <Text style={[styles.fieldLabel, { color: theme.colors.warning }]}>
                    {field.required ? '* ' : ''}Tap to {field.type === 'signature' ? 'sign' : field.type}
                  </Text>
                )}
              </TouchableOpacity>
            );
          })}
        </View>
      </ScrollView>

      {/* Signature Pad Modal */}
      {showSignPad && (
        <View style={[styles.signPadOverlay, { backgroundColor: 'rgba(0,0,0,0.5)' }]}>
          <View style={[styles.signPad, { backgroundColor: theme.colors.card }]}>
            <Text style={[styles.signPadTitle, { color: theme.colors.text }]}>Your Signature</Text>

            {/* Mode Toggle */}
            <View style={styles.modeToggle}>
              <TouchableOpacity
                style={[styles.modeBtn, signMode === 'draw' && { backgroundColor: theme.colors.primary }]}
                onPress={() => setSignMode('draw')}
              >
                <Text style={[styles.modeBtnText, { color: signMode === 'draw' ? '#FFF' : theme.colors.textSecondary }]}>
                  Draw
                </Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.modeBtn, signMode === 'type' && { backgroundColor: theme.colors.primary }]}
                onPress={() => setSignMode('type')}
              >
                <Text style={[styles.modeBtnText, { color: signMode === 'type' ? '#FFF' : theme.colors.textSecondary }]}>
                  Type
                </Text>
              </TouchableOpacity>
            </View>

            {signMode === 'draw' ? (
              <View style={styles.drawArea} {...panResponder.panHandlers}>
                <View style={[styles.drawCanvas, { borderColor: theme.colors.border }]}>
                  {drawnPath.length === 0 && (
                    <Text style={[styles.drawHint, { color: theme.colors.textSecondary }]}>
                      Draw your signature here
                    </Text>
                  )}
                </View>
                <TouchableOpacity onPress={() => setDrawnPath([])}>
                  <Text style={[styles.clearBtn, { color: theme.colors.error }]}>Clear</Text>
                </TouchableOpacity>
              </View>
            ) : (
              <View>
                <TextInput
                  style={[styles.typeInput, { color: theme.colors.text, borderColor: theme.colors.border }]}
                  value={typedSignature}
                  onChangeText={setTypedSignature}
                  placeholder="Type your full name"
                  placeholderTextColor={theme.colors.textSecondary}
                  autoFocus
                />
                {typedSignature.length > 0 && (
                  <Text style={[styles.signaturePreview, { color: theme.colors.primary }]}>
                    {typedSignature}
                  </Text>
                )}
              </View>
            )}

            <View style={styles.signPadActions}>
              <TouchableOpacity
                style={[styles.cancelBtn, { borderColor: theme.colors.border }]}
                onPress={() => setShowSignPad(false)}
              >
                <Text style={[styles.cancelBtnText, { color: theme.colors.textSecondary }]}>Cancel</Text>
              </TouchableOpacity>
              <TouchableOpacity
                style={[styles.applyBtn, { backgroundColor: theme.colors.primary }]}
                onPress={applySignature}
              >
                <Text style={styles.applyBtnText}>Apply</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      )}

      {/* Submit Button */}
      <View style={[styles.footer, { backgroundColor: theme.colors.card }]}>
        <TouchableOpacity
          style={[styles.submitBtn, {
            backgroundColor: completedCount >= totalFields ? theme.colors.success : theme.colors.textSecondary,
            opacity: submitting ? 0.6 : 1,
          }]}
          onPress={handleSubmit}
          disabled={submitting || completedCount < totalFields}
        >
          <Text style={styles.submitBtnText}>
            {submitting ? 'Submitting...' : 'Sign & Submit Document'}
          </Text>
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  container: { flex: 1 },
  progressBar: { padding: 14 },
  progressInfo: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 6 },
  progressText: { fontSize: 14, fontWeight: '600' },
  signerName: { fontSize: 12 },
  progressTrack: { height: 4, borderRadius: 2, overflow: 'hidden' },
  progressFill: { height: '100%', borderRadius: 2 },
  documentArea: { flex: 1 },
  documentPage: {
    minHeight: 600,
    margin: 16,
    padding: 20,
    backgroundColor: '#FFF',
    borderRadius: 8,
    gap: 16,
  },
  docPlaceholder: { textAlign: 'center', paddingVertical: 40, fontSize: 14 },
  signField: {
    borderWidth: 2,
    borderStyle: 'dashed',
    borderRadius: 8,
    paddingVertical: 14,
    paddingHorizontal: 16,
    alignItems: 'center',
  },
  fieldLabel: { fontSize: 14, fontWeight: '600' },
  signedValue: { fontSize: 16, fontWeight: '600', fontStyle: 'italic' },
  signPadOverlay: {
    position: 'absolute',
    top: 0, left: 0, right: 0, bottom: 0,
    justifyContent: 'center',
    padding: 20,
  },
  signPad: { borderRadius: 16, padding: 20 },
  signPadTitle: { fontSize: 18, fontWeight: '700', marginBottom: 16, textAlign: 'center' },
  modeToggle: { flexDirection: 'row', gap: 8, marginBottom: 16 },
  modeBtn: { flex: 1, paddingVertical: 10, borderRadius: 8, alignItems: 'center' },
  modeBtnText: { fontSize: 15, fontWeight: '600' },
  drawArea: { marginBottom: 16 },
  drawCanvas: { height: 120, borderWidth: 1, borderRadius: 8, justifyContent: 'center', alignItems: 'center' },
  drawHint: { fontSize: 14 },
  clearBtn: { textAlign: 'center', fontSize: 14, fontWeight: '600', marginTop: 8 },
  typeInput: { height: 48, borderWidth: 1, borderRadius: 8, paddingHorizontal: 14, fontSize: 16 },
  signaturePreview: { fontSize: 28, fontStyle: 'italic', textAlign: 'center', marginTop: 12 },
  signPadActions: { flexDirection: 'row', gap: 12, marginTop: 16 },
  cancelBtn: { flex: 1, height: 44, borderRadius: 8, borderWidth: 1, justifyContent: 'center', alignItems: 'center' },
  cancelBtnText: { fontSize: 15, fontWeight: '600' },
  applyBtn: { flex: 1, height: 44, borderRadius: 8, justifyContent: 'center', alignItems: 'center' },
  applyBtnText: { color: '#FFF', fontSize: 15, fontWeight: '700' },
  footer: { padding: 16, paddingBottom: 32 },
  submitBtn: { height: 52, borderRadius: 12, justifyContent: 'center', alignItems: 'center' },
  submitBtnText: { color: '#FFF', fontSize: 17, fontWeight: '700' },
});
