import React, { useRef } from 'react';
import { Alert, Modal, Pressable, StyleSheet } from 'react-native';
import { useTheme } from '../theme';
import { useT } from '../i18n';
import { NumpadSheet } from './NumpadSheet';
import { useNumpadUiStore } from '../store/numpadUiStore';

/** 全局记账面板宿主：挂载于根布局，任意页面可唤起（不丢上下文）。 */
export function NumpadSheetHost() {
  const { theme } = useTheme();
  const t = useT();
  const visible = useNumpadUiStore(s => s.visible);
  const prefill = useNumpadUiStore(s => s.prefill);
  const close = useNumpadUiStore(s => s.close);
  // 表单脏状态（NumpadSheet 每次渲染后上报），遮罩/返回键关闭前据此弹未保存确认
  const dirtyRef = useRef(false);

  const requestClose = () => {
    if (!dirtyRef.current) { close(); return; }
    Alert.alert(t('transaction.unsavedTitle'), t('transaction.unsavedMessage'), [
      { text: t('common.cancel'), style: 'cancel' },
      { text: t('common.discard'), style: 'destructive', onPress: close },
    ]);
  };

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={requestClose}>
      <Pressable style={[styles.overlay, { backgroundColor: theme.colors.overlay }]} onPress={requestClose}>
        <Pressable style={styles.sheetWrap} onPress={e => e.stopPropagation()}>
          <NumpadSheet
            presentation="modal"
            editId={prefill?.editId}
            draftJson={prefill?.draftJson}
            autoOcr={prefill?.autoOcr}
            onClose={close}
            onDirtyChange={d => { dirtyRef.current = d; }}
          />
        </Pressable>
      </Pressable>
    </Modal>
  );
}

const styles = StyleSheet.create({
  overlay: { flex: 1, justifyContent: 'flex-end' },
  sheetWrap: { maxHeight: '94%' },
});
