import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {  View, StyleSheet, Platform } from 'react-native';
import ApproveCardItem from '@/components/approve/ApproveCardItem';
import { fetchApprovalList } from '@/api/approve';
import { wp } from '@/utils/ui/screenUtils';
import ApproveEmpty from '@/components/approve/ApproveEmpty';
import ApproveSkeleton from '@/components/approve/ApproveSkeleton';
import useCrossFadeSkeleton from '@/hooks/approve/useCrossFadeSkeleton';
import Animated from 'react-native-reanimated';
import useApprovalTabLogic from '@/hooks/approve/useApprovalTabLogic';
import ListFooter from '@/components/approve/ListFooter';
import { useTheme } from 'tamagui'
import { useAppStore } from '@/stores';
import { FlashList } from '@shopify/flash-list';
import { useApproveStore } from '@/stores/approve';
import CustomRefreshControl from '@/components/ui/CustomRefreshControl';
const PAGE_SIZE = 10;
const ReviewedTab = ({ primaryColor, tabBarInset = 0, isActive = false, searchValue = '', resetKey = 0 }) => {
  const listRef = useRef(null);
  const primaryColorStore = useAppStore(s => s.primary);

  const theme = useTheme();

  // 读取持久化缓存与首次加载标记，控制骨架屏
  const getTabCache = useApproveStore((s) => s.getTabCache);
  const isTabFirstLoad = useApproveStore((s) => s.isTabFirstLoad);
  const markTabLoaded = useApproveStore((s) => s.markTabLoaded);
  const reviewedCache = getTabCache('reviewed');
  const initiallyLoading = isTabFirstLoad('reviewed') && (!reviewedCache || ((Array.isArray(reviewedCache.list) ? reviewedCache.list.length : (reviewedCache.list?.length ?? 0)) === 0));

  const { skeletonVisible, contentAnimatedStyle, skeletonAnimatedStyle, setLoading } = useCrossFadeSkeleton({ initiallyLoading });
  const setLoadingRef = useRef(setLoading);
  setLoadingRef.current = setLoading;

  const fetchList = useCallback(async (nextPage, pageSize) => {
    return fetchApprovalList('reviewed', { Page: nextPage, PageSize: pageSize, Status: 0, Type: '', domain: 'all', menuType: 3, title: '' }, searchValue);
  }, [searchValue]);

  const onNonAppendFinally = useCallback(() => {
    markTabLoaded('reviewed');
    setLoadingRef.current(false);
  }, [markTabLoaded]);

  const { data, page, refreshing, loadingMore, hasMore, fetchPage, onRefresh, onEndReached, onMomentumScrollBegin, error, retry } = useApprovalTabLogic({
    pageSize: PAGE_SIZE,
    fetchList,
    onNonAppendFinally,
    tabKey: 'reviewed',
  });

  // 静默刷新：不触发下拉刷新动画，仅重新加载第一页
  const refreshSilently = useCallback(() => {
    fetchPage(1, false);
  }, [fetchPage]);

  useEffect(() => {
    if (isActive) fetchPage(1, false);
  }, [isActive, fetchPage]);

  // 搜索变化时刷新第一页
  useEffect(() => {
    if (isActive) {
      fetchPage(1, false);
    }
  }, [searchValue, isActive, fetchPage]);

  useEffect(() => {
    if (isActive && listRef.current) {
      try {
        listRef.current.scrollToOffset({ offset: 0, animated: false });
      } catch (e) {}
    }
  }, [isActive]);

  useEffect(() => {
    if (isActive && listRef.current) {
      try {
        listRef.current.scrollToOffset({ offset: 0, animated: true });
      } catch (e) {}
    }
  }, [resetKey, isActive]);

  const noop = useCallback(() => {}, []);

  const keyExtractor = useCallback((item, idx) => String(item?.ID ?? idx), []);

  const renderItem = useCallback(({ item }) => (
    <ApproveCardItem 
      item={item} 
      onApprove={noop} 
      onReject={noop} 
      primaryColor={primaryColor} 
      onDeleted={refreshSilently}
      isMeCheck={true}
      hideRevokeExpedite={true}
    />
  ), [primaryColor, refreshSilently, noop]);

  const itemSeparator = useMemo(() => () => <View style={styles.separator12} />, []);

  const listFooter = useMemo(() => (
    <ListFooter loadingMore={loadingMore} hasMore={hasMore} dataLength={data.length} primaryColor={primaryColor} error={!!error} onRetry={retry} />
  ), [loadingMore, hasMore, data.length, primaryColor, error, retry]);

  const emptyComponent = useMemo(() => (<ApproveEmpty />), []);
  const skeleton = useMemo(() => (<ApproveSkeleton variant="list" />), []);
  const contentContainerStyle = useMemo(() => ({ paddingBottom: tabBarInset, paddingTop: wp(8), paddingHorizontal: wp(16) }), [tabBarInset]);

  return (
    <View style={styles.container}>
      {skeletonVisible && (
        <Animated.View style={[styles.overlay, skeletonAnimatedStyle]}>
          {skeleton}
        </Animated.View>
      )}

      <Animated.View style={[styles.flex1, contentAnimatedStyle]}>
        <FlashList
          ref={listRef}
          style={styles.flex1}
          data={data}
          renderItem={renderItem}
          keyExtractor={keyExtractor}
          refreshing={refreshing}
          onRefresh={onRefresh}
          onEndReached={onEndReached}
          onEndReachedThreshold={0.2}
          onMomentumScrollBegin={onMomentumScrollBegin}
          ItemSeparatorComponent={itemSeparator}
          ListFooterComponent={listFooter}
          ListEmptyComponent={emptyComponent}
          contentContainerStyle={contentContainerStyle}
          removeClippedSubviews
          windowSize={7}
          initialNumToRender={10}
          maxToRenderPerBatch={10}
          refreshControl={
            <CustomRefreshControl
              refreshing={refreshing}
              onRefresh={onRefresh}
              tintColor={primaryColorStore}
            />
          }
        />
      </Animated.View>
    </View>
  );
};

export default React.memo(ReviewedTab);

const styles = StyleSheet.create({
  container: { flex: 1, position: 'relative' },
  overlay: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, zIndex: 2 },
  flex1: { flex: 1 },
  separator12: { height: wp(12) },
  center12: { paddingVertical: wp(12), alignItems: 'center', justifyContent: 'center' },
  center16: { paddingVertical: wp(16), alignItems: 'center', justifyContent: 'center' },
  allLoadedText: { color: '#9AA0A6', fontSize: wp(12) },
  tinySpacer: { height: wp(4) },
});
