import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Modal, ScrollView, Text, View } from 'react-native';
import { useTheme } from '../../theme';
import { useT } from '../../i18n';
import { Touchable } from './Touchable';

/** 滚轮单项高度（dp） */
const ITEM_H = 44;
/** 滚轮可视项数（奇数，居中一项高亮） */
const VISIBLE = 3;

interface WheelProps {
  items: string[];
  selectedIndex: number;
  onSelectIndex: (index: number) => void;
}

/** 单列滚轮：snap 吸附 + 居中高亮条。 */
function Wheel({ items, selectedIndex, onSelectIndex }: WheelProps) {
  const { theme } = useTheme();
  const ref = useRef<ScrollView>(null);

  // 选中项变化（含打开时同步外部值）时滚动定位
  useEffect(() => {
    const id = setTimeout(() => ref.current?.scrollTo({ y: selectedIndex * ITEM_H, animated: false }), 0);
    return () => clearTimeout(id);
  }, [selectedIndex]);

  const pad = ITEM_H * ((VISIBLE - 1) / 2);

  return (
    <View>
      {/* 居中选中高亮条 */}
      <View
        pointerEvents="none"
        style={{
          position: 'absolute',
          left: 0,
          right: 0,
          top: pad,
          height: ITEM_H,
          borderRadius: theme.radii.md,
          backgroundColor: theme.colors.bgTertiary,
        }}
      />
      <ScrollView
        ref={ref}
        style={{ height: ITEM_H * VISIBLE, width: 72 }}
        contentContainerStyle={{ paddingVertical: pad }}
        snapToInterval={ITEM_H}
        decelerationRate="fast"
        showsVerticalScrollIndicator={false}
        onMomentumScrollEnd={e => onSelectIndex(Math.round(e.nativeEvent.contentOffset.y / ITEM_H))}
      >
        {items.map((it, i) => (
          <View key={i} style={{ height: ITEM_H, alignItems: 'center', justifyContent: 'center' }}>
            <Text
              style={{
                fontSize: theme.typography.h3.fontSize,
                fontVariant: ['tabular-nums'],
                color: i === selectedIndex ? theme.colors.fgPrimary : theme.colors.fgSecondary,
                fontWeight: i === selectedIndex ? '700' : '400',
              }}
            >
              {it}
            </Text>
          </View>
        ))}
      </ScrollView>
    </View>
  );
}

interface TimePickerProps {
  visible: boolean;
  /** 当前小时 0-23 */
  hour: number;
  /** 当前分钟 0-59 */
  minute: number;
  /** 分钟步长，默认 5 */
  minuteStep?: number;
  title?: string;
  onConfirm: (hour: number, minute: number) => void;
  onCancel: () => void;
}

/**
 * 时间选择器（主题化）。
 * 时 / 分双滚轮替代简陋的 +/- 按钮：snap 吸附选择，底部确认 / 取消。
 */
export function TimePicker({ visible, hour, minute, minuteStep = 5, title, onConfirm, onCancel }: TimePickerProps) {
  const { theme } = useTheme();
  const t = useT();

  const hours = useMemo(() => Array.from({ length: 24 }, (_, i) => String(i).padStart(2, '0')), []);
  const minutes = useMemo(
    () => Array.from({ length: Math.max(1, Math.floor(60 / minuteStep)) }, (_, i) => String(i * minuteStep).padStart(2, '0')),
    [minuteStep],
  );
  const clampM = (m: number) => Math.max(0, Math.min(Math.round(m / minuteStep), minutes.length - 1));

  const [hIdx, setHIdx] = useState(hour);
  const [mIdx, setMIdx] = useState(() => clampM(minute));

  // 每次打开时同步外部当前值
  useEffect(() => {
    if (visible) {
      setHIdx(hour);
      setMIdx(clampM(minute));
    }
  }, [visible, hour, minute]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <Modal visible={visible} transparent animationType="slide" onRequestClose={onCancel}>
      <View style={{ flex: 1, justifyContent: 'flex-end', backgroundColor: theme.colors.overlay }}>
        <View
          style={{
            backgroundColor: theme.colors.bgSecondary,
            borderTopLeftRadius: theme.radii.xl,
            borderTopRightRadius: theme.radii.xl,
            padding: theme.spacing.lg,
            ...theme.shadows.lg,
          }}
        >
          {title ? (
            <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary, textAlign: 'center' }]}>{title}</Text>
          ) : null}
          <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginTop: theme.spacing.lg }}>
            <Wheel items={hours} selectedIndex={hIdx} onSelectIndex={setHIdx} />
            <Text style={[theme.typography.h2, { color: theme.colors.fgPrimary, marginHorizontal: theme.spacing.xs }]}>:</Text>
            <Wheel items={minutes} selectedIndex={mIdx} onSelectIndex={setMIdx} />
          </View>
          <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 }]}>{t('common.cancel')}</Text>
            </Touchable>
            <Touchable
              onPress={() => onConfirm(hIdx, mIdx * minuteStep)}
              accessibilityRole="button"
              style={{
                flex: 1,
                alignItems: 'center',
                justifyContent: 'center',
                paddingVertical: theme.spacing.sm + theme.spacing.xs,
                borderRadius: theme.radii.md,
                backgroundColor: theme.colors.accent,
              }}
            >
              <Text style={[theme.typography.body, { color: theme.colors.fgInverse, fontWeight: '600' }]}>{t('common.confirm')}</Text>
            </Touchable>
          </View>
        </View>
      </View>
    </Modal>
  );
}