import React, { useMemo } from 'react';
import { Modal, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { createCommonStyles } from '../../theme/commonStyles';
import { useT } from '../../i18n';
import { Touchable } from './Touchable';

interface ConfirmDialogProps {
  visible: boolean;
  title: string;
  message?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  /** 危险操作（如删除）：确认按钮使用语义错误色。 */
  destructive?: boolean;
  onConfirm: () => void;
  onCancel: () => void;
}

/**
 * 可定制确认弹窗（主题化）。
 * 替代系统 Alert.alert：统一视觉风格，支持危险操作语义色与自定义按钮文案。
 */
export function ConfirmDialog({
  visible,
  title,
  message,
  confirmLabel,
  cancelLabel,
  destructive,
  onConfirm,
  onCancel,
}: ConfirmDialogProps) {
  const { theme } = useTheme();
  const commonStyles = useMemo(() => createCommonStyles(theme), [theme]);
  const t = useT();
  const confirmBg = destructive ? theme.colors.error : theme.colors.accent;

  return (
    <Modal visible={visible} transparent animationType="fade" onRequestClose={onCancel}>
      <View style={commonStyles.modalOverlay}>
        <View style={commonStyles.modalCard}>
          <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary }]}>{title}</Text>
          {message ? (
            <Text style={[theme.typography.bodySmall, { color: theme.colors.fgSecondary, marginTop: theme.spacing.sm }]}>
              {message}
            </Text>
          ) : null}
          <View style={{ flexDirection: 'row', gap: theme.spacing.sm, marginTop: theme.spacing.lg }}>
            <Touchable
              onPress={onCancel}
              accessibilityRole="button"
              style={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: theme.spacing.sm + theme.spacing.xs,
                borderRadius: theme.radii.md,
                backgroundColor: theme.colors.bgTertiary,
              }}
            >
              <Text style={[theme.typography.body, { color: theme.colors.fgSecondary }]}>
                {cancelLabel ?? t('common.cancel')}
              </Text>
            </Touchable>
            <Touchable
              onPress={onConfirm}
              accessibilityRole="button"
              style={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: theme.spacing.sm + theme.spacing.xs,
                borderRadius: theme.radii.md,
                backgroundColor: confirmBg,
              }}
            >
              <Text style={[theme.typography.body, { color: theme.colors.fgInverse, fontWeight: '600' }]}>
                {confirmLabel ?? t('common.confirm')}
              </Text>
            </Touchable>
          </View>
        </View>
      </View>
    </Modal>
  );
}