import React, { useMemo, useState } from 'react';
import { Pressable, StyleSheet, Text, View } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useTheme, createCommonStyles } from '../../theme';
import { useT } from '../../i18n';
import { BottomSheet } from '../ui/BottomSheet';
import { buildMonthGrid } from '../stats/dateGrid';

interface DatePickerFieldProps {
  /** YYYY-MM-DD，空串表示未选。 */
  value: string;
  onChange: (date: string) => void;
  placeholder?: string;
}

/** 日期选择字段：输入框外观 + 底部弹层月历（终结手输 YYYY-MM-DD）。 */
export function DatePickerField({ value, onChange, placeholder }: DatePickerFieldProps) {
  const { theme } = useTheme();
  const t = useT();
  // 星期头周一起（与 buildMonthGrid 网格一致），文案走 i18n
  const weekdays = useMemo(() => t('datepicker.weekdays').split(','), [t]);
  const commonStyles = useMemo(() => createCommonStyles(theme), [theme]);
  const [open, setOpen] = useState(false);
  const [viewYear, setViewYear] = useState(new Date().getFullYear());
  const [viewMonth, setViewMonth] = useState(new Date().getMonth() + 1);

  const grid = useMemo(() => buildMonthGrid(viewYear, viewMonth), [viewYear, viewMonth]);

  const openPicker = () => {
    const y = Number(value.slice(0, 4));
    const m = Number(value.slice(5, 7));
    if (y) {
      setViewYear(y);
      setViewMonth(m || 1);
    }
    setOpen(true);
  };

  const shiftMonth = (delta: number) => {
    const m = viewMonth - 1 + delta;
    setViewYear(viewYear + Math.floor(m / 12));
    setViewMonth(((m % 12) + 12) % 12 + 1);
  };

  const pick = (date: string) => {
    onChange(date);
    setOpen(false);
  };

  return (
    <>
      <Pressable style={commonStyles.input} onPress={openPicker} accessibilityRole="button" accessibilityLabel={value || placeholder || '选择日期'}>
        <Text style={{ color: value ? theme.colors.fgPrimary : theme.colors.fgSecondary }}>
          {value || placeholder || 'YYYY-MM-DD'}
        </Text>
      </Pressable>
      <BottomSheet visible={open} onClose={() => setOpen(false)}>
        {/* 月份导航 */}
        <View style={styles.navRow}>
          <Pressable onPress={() => shiftMonth(-1)} hitSlop={8} accessibilityRole="button" accessibilityLabel="上一月">
            <Ionicons name="chevron-back" size={22} color={theme.colors.fgPrimary} />
          </Pressable>
          <Text style={[theme.typography.h3, { color: theme.colors.fgPrimary, fontVariant: ['tabular-nums'] }]}>
            {viewYear}-{String(viewMonth).padStart(2, '0')}
          </Text>
          <Pressable onPress={() => shiftMonth(1)} hitSlop={8} accessibilityRole="button" accessibilityLabel="下一月">
            <Ionicons name="chevron-forward" size={22} color={theme.colors.fgPrimary} />
          </Pressable>
        </View>
        {/* 星期头 */}
        <View style={styles.weekRow}>
          {weekdays.map(w => (
            <Text key={w} style={[styles.weekCell, theme.typography.caption, { color: theme.colors.fgSecondary }]}>{w}</Text>
          ))}
        </View>
        {/* 日期网格 */}
        {grid.map((week, wi) => (
          <View key={wi} style={styles.weekRow}>
            {week.map(cell => {
              const selected = cell.date === value;
              return (
                <Pressable
                  key={cell.date}
                  onPress={() => pick(cell.date)}
                  accessibilityRole="button"
                  accessibilityLabel={cell.date}
                  accessibilityState={{ selected }}
                  style={[styles.dayCell, {
                    backgroundColor: selected ? theme.colors.accent : 'transparent',
                    borderRadius: theme.radii.full,
                  }]}
                >
                  <Text style={[theme.typography.bodySmall, {
                    color: selected
                      ? theme.colors.fgInverse
                      : cell.inMonth ? theme.colors.fgPrimary : theme.colors.fgSecondary,
                    opacity: cell.inMonth ? 1 : 0.5,
                    fontVariant: ['tabular-nums'],
                  }]}>
                    {Number(cell.date.slice(8, 10))}
                  </Text>
                </Pressable>
              );
            })}
          </View>
        ))}
      </BottomSheet>
    </>
  );
}

const styles = StyleSheet.create({
  navRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingVertical: 8 },
  weekRow: { flexDirection: 'row' },
  weekCell: { flex: 1, textAlign: 'center', paddingVertical: 6 },
  dayCell: { flex: 1, aspectRatio: 1, alignItems: 'center', justifyContent: 'center', margin: 1 },
});
