import React, { useEffect, useMemo, useState, useCallback, useRef } from 'react';
import { StyleSheet, Pressable } from 'react-native';
import { CustomSafeArea } from '@/components/common/CustomSafeArea';
import { View, XStack, Input, YStack, Image } from 'tamagui';
import { Image as ExpoImage } from 'expo-image';
import CustomText from '@/components/common/CustomText.jsx';
import { Easing } from 'react-native-reanimated'
import TabsPager from '@/components/ui/TabsPager';
import { wp } from '@/utils/ui/screenUtils';
import { useTabBarHeight } from '@/hooks/useTabBarHeight';
import SubmittedTab from '@/components/approve/SubmittedTab';
import PendingTab from '@/components/approve/PendingTab';
import ReviewedTab from '@/components/approve/ReviewedTab';
import CcMeTab from '@/components/approve/CcMeTab';
import { useApproveStore } from '@/stores/approve';
import { checkAuth } from '@/api/approve';
import { useAuthStore } from '@/stores/auth';
import { router } from 'expo-router';
import { CustomHeader } from '@/components/common/CustomHeader';
import { useTranslation } from 'react-i18next';
import { useFocusEffect } from '@react-navigation/native'
import { useAppStore } from '@/stores';
// 统一动画配置（UI 线程）
const TAB_TIMING = { duration: 240, easing: Easing.out(Easing.cubic) };

// 模块级 memo，避免在渲染期间创建新组件导致子树重挂载
const MemoSubmitted = React.memo(SubmittedTab);
const MemoPending = React.memo(PendingTab);
const MemoReviewed = React.memo(ReviewedTab);
const MemoCcMe = React.memo(CcMeTab);

function createTabs(doingTotal, t) {
  return [
    { key: 'submitted', label: t('approve:tabs.submitted') },
    { key: 'pending', label: t('approve:tabs.pending'), badge: doingTotal || 0 },
    { key: 'reviewed', label: t('approve:tabs.reviewed') },
    { key: 'ccme', label: t('approve:tabs.ccme') },
  ];
}

export default function ApproveScreen() {
  const primaryColor = useAppStore(s => s.primary);
  const { t } = useTranslation();
  const tabBarHeight = useTabBarHeight();
  const doingTotal = useApproveStore((s) => s.doingTotal);
  const fetchDoingTotal = useApproveStore((s) => s.fetchDoingTotal);
  const user = useAuthStore((s) => s.user);

  const tabs = useMemo(() => createTabs(doingTotal, t), [doingTotal, t]);
  const [activeIndex, setActiveIndex] = useState(0);
  const [submittedResetKey, setSubmittedResetKey] = useState(0);
  const [pendingResetKey, setPendingResetKey] = useState(0);
  const [reviewedResetKey, setReviewedResetKey] = useState(0);
  const [ccmeResetKey, setCcmeResetKey] = useState(0);
  const [searchValue, setSearchValue] = useState('');
  const [debouncedSearch, setDebouncedSearch] = useState('');

  // 搜索防抖：仅在输入停止 300ms 后更新传递给各 Tab 的值
  useEffect(() => {
    const v = (searchValue || '').trim();
    const timer = setTimeout(() => {
      setDebouncedSearch(v);
    }, 300);
    return () => clearTimeout(timer);
  }, [searchValue]);
  const authLoadedRef = useRef(false);

  // 新增：页面聚焦时触发刷新信号（用于从 WebView 返回后刷新列表和角标）
  const [refreshKey, setRefreshKey] = useState(0)
  useFocusEffect(
    useCallback(() => {
      setRefreshKey((k) => k + 1)
      if (user?.ID) fetchDoingTotal(user.ID)
    }, [fetchDoingTotal, user?.ID])
  )

  // 新增：根据 checkAuth 恢复待我审批的展示模式（网格/列表）- 延迟到进入待我审批时触发
  const [pendingMode, setPendingMode] = useState('list'); // 'grid' | 'list'
  useEffect(() => {
    if (activeIndex !== 1 || authLoadedRef.current) return;
    let cancelled = false;
    (async () => {
      try {
        const res = await checkAuth({ url: 'moceapp/mywork/category/', type: 'button' });
        if (cancelled) return;
        const isGrid = res?.data;
        setPendingMode(isGrid ? 'grid' : 'list');
        authLoadedRef.current = true;
      } catch (e) {
        if (!cancelled) setPendingMode('list');
        authLoadedRef.current = true;
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [activeIndex]);

  // 切换子 Tab 时刷新角标（委派给 store 异步动作）
  useEffect(() => {
    if (!user?.ID) return;
    fetchDoingTotal(user.ID);
  }, [activeIndex, user?.ID, fetchDoingTotal]);
  const handlePressApprovalCard = useCallback(() => {
    router.push({ pathname: '/webview', params: { url: `${process.env.EXPO_PUBLIC_H5_APPROVAL_URL}/#/pages/applyfor/app-record/index`, type: 'approval' } });
  }, []);
  const handlePressAttendanceCard = useCallback(() => {
    router.push({ pathname: '/webview', params: { url: `${process.env.EXPO_PUBLIC_H5_APPROVAL_URL}/#/pages/applyfor/app-record/index`, type: 'attendance' } });
  }, []);

  const segmentHeight = wp(34);
  const GAP = wp(8); // 胶囊之间的间距
  return (
    <View flex={1}>
      <ExpoImage
        source={require('@/assets/images/backgrounds/home-bg.webp')}
        style={StyleSheet.absoluteFill}
        contentFit="cover"
        transition={0}
        pointerEvents="none"
        cachePolicy="memory-disk"
      />
      
        <CustomHeader title={t('approve:header.title')} leftContent={''} />
        <YStack  paddingTop={wp(9)} flex={1}>
          <View paddingHorizontal={wp(16)}>
  <XStack  backgroundColor="#fff" paddingInline={wp(9)} paddingVertical={wp(10)} borderRadius={wp(4)} marginBottom={wp(17)}>
            <XStack  alignItems="center" style={styles.searchContainer} flex={1}>
              <Image source={require('@/assets/images/icon/search.png')} style={styles.searchIcon} />
              <Input
                fontSize={wp(14)}
                placeholder={t('approve:search.placeholder')}
                borderWidth={wp(0)}
                backgroundColor="#F9F9FD"
                flex={1}
                height={wp(33)}
                style={styles.inputInner}
                placeholderTextColor="#999"
                value={searchValue}
                onChangeText={setSearchValue}
              />
            </XStack>
          </XStack>
          </View>
        

          <XStack paddingHorizontal={wp(16)} justifyContent="space-between">
            <Pressable onPress={handlePressApprovalCard} style={({ pressed }) => [{ transform: [{ scale: pressed ? 0.98 : 1 }], opacity: pressed ? 0.9 : 1 }]}>
              <View style={styles.cardBg}>
                <ExpoImage
                  source={require('@/assets/images/approve/4486.png')}
                  style={StyleSheet.absoluteFill}
                  contentFit="cover"
                  transition={0}
                  pointerEvents="none"
                />
                <YStack paddingTop={wp(16)} paddingLeft={wp(16)}>
                  <XStack alignItems="center" marginBottom={wp(3)}>
                    <CustomText style={{ color: '#191919', fontSize: wp(16), fontFamily: 'Bold', marginRight: wp(14) }}>
                      {t('approve:cards.approvalApply.title')}
                    </CustomText>
                    <Image source={require('@/assets/images/approve/chevron-down.png')} style={styles.chevronIcon} />
                  </XStack>
                  <CustomText style={{ color: '#BABABA', fontSize: wp(12) }}>{t('approve:cards.approvalApply.subtitle')}</CustomText>
                </YStack>
              </View>
            </Pressable>
            <Pressable onPress={handlePressAttendanceCard} style={({ pressed }) => [{ transform: [{ scale: pressed ? 0.98 : 1 }], opacity: pressed ? 0.9 : 1 }]}>
              <View style={styles.cardBg}>
                <ExpoImage
                  source={require('@/assets/images/approve/4487.png')}
                  style={StyleSheet.absoluteFill}
                  contentFit="cover"
                  transition={0}
                  pointerEvents="none"
                />
                <YStack paddingTop={wp(16)} paddingLeft={wp(16)}>
                  <XStack alignItems="center" marginBottom={wp(3)}>
                    <CustomText style={{ color: '#191919', fontSize: wp(16), fontFamily: 'Bold', marginRight: wp(14) }}>
                      {t('approve:cards.attendanceApply.title')}
                    </CustomText>
                    <Image source={require('@/assets/images/approve/chevron-down.png')} style={styles.chevronIcon} />
                  </XStack>
                  <CustomText style={{ color: '#BABABA', fontSize: wp(12) }}>{t('approve:cards.attendanceApply.subtitle')}</CustomText>
                </YStack>
              </View>
            </Pressable>
          </XStack>

          <YStack  marginTop={wp(16)} flex={1}>
            <TabsPager
              tabs={tabs}
              activeIndex={activeIndex}
              onIndexChange={(i) => {
                if (i === activeIndex) {
                  if (i === 0) setSubmittedResetKey((k) => k + 1);
                  else if (i === 1) setPendingResetKey((k) => k + 1);
                  else if (i === 2) setReviewedResetKey((k) => k + 1);
                  else if (i === 3) setCcmeResetKey((k) => k + 1);
                  return;
                }
                setActiveIndex(i);
              }}
              primaryColor={primaryColor}
              height={segmentHeight}
              gap={GAP}
              timing={TAB_TIMING}
              renderScene={(i, tItem, { containerWidth, isActive }) => (
                tItem.key === 'pending' ? (
                  <MemoPending
                    containerWidth={containerWidth}
                    primaryColor={primaryColor}
                    tabBarInset={tabBarHeight}
                    isActive={isActive}
                    mode={pendingMode}
                    refreshKey={refreshKey}
                    searchValue={debouncedSearch}
                    resetKey={pendingResetKey}
                  />
                ) : tItem.key === 'submitted' ? (
                  <MemoSubmitted
                    primaryColor={primaryColor}
                    tabBarInset={tabBarHeight}
                    isActive={isActive}
                    searchValue={debouncedSearch}
                    resetKey={submittedResetKey}
                  />
                ) : tItem.key === 'reviewed' ? (
                  <MemoReviewed
                    primaryColor={primaryColor}
                    tabBarInset={tabBarHeight}
                    isActive={isActive}
                    searchValue={debouncedSearch}
                    resetKey={reviewedResetKey}
                  />
                ) : (
                  <MemoCcMe
                    primaryColor={primaryColor}
                    tabBarInset={tabBarHeight}
                    isActive={isActive}
                    searchValue={debouncedSearch}
                    resetKey={ccmeResetKey}
                  />
                )
              )}
            />
          </YStack>
        </YStack>
    </View>
  );
}

const styles = StyleSheet.create({
  bg: { width: '100%', height: '100%' },
  searchContainer: { backgroundColor: '#F9F9FD', borderRadius: wp(4), paddingHorizontal: wp(15), height: wp(33) },
  searchIcon: { width: wp(18), height: wp(18.43) },
  inputInner: { textAlignVertical: 'center', paddingTop: wp(0), paddingBottom: wp(0) },
  cardBg: { width: wp(167), height: wp(101) },
  chevronIcon: { width: wp(6.03), height: wp(10) },

  segmentContainer: {
    position: 'relative',
    backgroundColor: 'transparent',
    borderRadius: wp(0),
    padding: wp(0),
    flexDirection: 'row',
    alignItems: 'center',
  },
  segmentRail: {
    position: 'absolute',
    top: wp(0),
    left: wp(0),
    backgroundColor: '#F3F0FF',
    borderRadius: wp(6),
    zIndex: 0,
  },
  segmentIndicator: {
    position: 'absolute',
    top: wp(0),
    left: wp(0),
    backgroundColor: '#6A4CFF',
    borderRadius: wp(6),
    zIndex: 1,
  },

  gridWrap: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  gridItem: {
    backgroundColor: '#FFFFFF',
    borderRadius: wp(10),
    height: wp(96),
    alignItems: 'center',
    justifyContent: 'center',
  },
  segmentItem: {
    flex: 1,
    height: '100%',
    position: 'relative',
    zIndex: 2,
  },
  segmentPill: {
    height: '100%',
    borderRadius: wp(6),
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
    zIndex: 2,
  },
  segmentText: {
    fontSize: wp(14),
    fontFamily: 'Bold',
  },
  maskClip: {
    position: 'absolute',
    top: wp(0),
    height: '100%',
    overflow: 'hidden',
    zIndex: 3,
    borderRadius: wp(6),
  },
  maskInner: {
    position: 'absolute',
    top: wp(0),
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
