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

/** 全局记账面板宿主：挂载于根布局，任意页面可唤起（不丢上下文）。 */
export function NumpadSheetHost() {
  const visible = useNumpadUiStore(s => s.visible);
  // 通过 ref 共享 Inner 内的关闭逻辑，让 Modal 的 onRequestClose 也能触发未保存守卫
  const requestCloseRef = useRef<() => void>(() => {});
  return (
    <Modal
      visible={visible}
      transparent
      animationType="slide"
      onRequestClose={() => requestCloseRef.current()}
    >
      <SafeAreaProvider>
        <NumpadSheetHostInner requestCloseRef={requestCloseRef} />
      </SafeAreaProvider>
    </Modal>
  );
}

interface NumpadSheetHostInnerProps {
  requestCloseRef: React.MutableRefObject<() => void>;
}

function NumpadSheetHostInner({ requestCloseRef }: NumpadSheetHostInnerProps) {
  const { theme } = useTheme();
  const t = useT();
  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 },
    ]);
  };
  // 把关闭逻辑暴露给外层 Modal 的 onRequestClose（Android 返回键）
  requestCloseRef.current = requestClose;

  return (
    <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>
  );
}

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