import React, { useEffect, useState } from 'react';
import { StyleSheet, Pressable } from 'react-native';
import CustomText from '@/components/common/CustomText.jsx';
import { useTranslation } from '@/node_modules/react-i18next';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, Easing, runOnJS } from 'react-native-reanimated';
import Svg, { Path } from 'react-native-svg';
import { wp } from '@/utils/ui/screenUtils';
import { getList } from '@/api/toolbox';
import { router } from 'expo-router';
import { useToolboxStore } from '@/stores';
const AnimatedPressable = Animated.createAnimatedComponent(Pressable);
const D_IN = 220;
const D_OUT = 160;

export default function ReportModal({ visible, onClose }) {
  const { t } = useTranslation('toolbox');
  const [mounted, setMounted] = useState(false);
  const overlayOpacity = useSharedValue(0);
  const cardTranslateY = useSharedValue(wp(16));
  const cardScale = useSharedValue(0.96);
  const [list, setList] = useState([]);
  const { setReportSites } = useToolboxStore();
  const normalizeList = (arr) => Array.isArray(arr) ? arr.map(({ ID, Name }) => ({ ID, Name })).sort((a, b) => a.ID - b.ID) : [];
  const isSameList = (a, b) => {
    const aa = normalizeList(a);
    const bb = normalizeList(b);
    if (aa.length !== bb.length) return false;
    for (let i = 0; i < aa.length; i++) {
      if (aa[i].ID !== bb[i].ID || aa[i].Name !== bb[i].Name) return false;
    }
    return true;
  };
  useEffect(() => {
    let active = true;
    if (visible) {
      // 优先显示本地缓存
      const cached = useToolboxStore.getState().reportSites;
      setList(Array.isArray(cached) ? cached : []);
      // 仍然请求接口，若数据变化则覆盖本地并更新视图
      getList({})
        .then((res) => {
          if (!active) return;
          const arr = Array.isArray(res?.data?.List) ? res.data.List : [];
          const latestCached = useToolboxStore.getState().reportSites;
          if (!isSameList(latestCached, arr)) {
            setReportSites(arr);
          }
          setList(arr);
        })
        .catch(() => {
          const cached2 = useToolboxStore.getState().reportSites;
          if (active) setList(Array.isArray(cached2) ? cached2 : []);
        });
    }
    return () => {
      active = false;
    };
  }, [visible]);
  useEffect(() => {
    if (visible) {
      setMounted(true);
      overlayOpacity.value = 0;
      cardTranslateY.value = wp(16);
      cardScale.value = 0.96;
      overlayOpacity.value = withTiming(1, { duration: D_IN, easing: Easing.out(Easing.quad) });
      cardTranslateY.value = withTiming(0, { duration: D_IN, easing: Easing.out(Easing.quad) });
      cardScale.value = withTiming(1, { duration: D_IN, easing: Easing.out(Easing.quad) });
    } else if (mounted) {
      overlayOpacity.value = withTiming(0, { duration: D_OUT, easing: Easing.in(Easing.quad) }, (fin) => {
        if (fin) runOnJS(setMounted)(false);
      });
      cardTranslateY.value = withTiming(wp(8), { duration: D_OUT, easing: Easing.in(Easing.quad) });
      cardScale.value = withTiming(0.98, { duration: D_OUT, easing: Easing.in(Easing.quad) });
    }
  }, [visible, mounted]);

  const overlayStyle = useAnimatedStyle(() => ({
    opacity: overlayOpacity.value,
  }));

  const cardStyle = useAnimatedStyle(() => ({
    transform: [
      { translateY: cardTranslateY.value },
      { scale: cardScale.value },
    ],
  }));
  const handleSelect = (item) => {
    router.push({
      pathname: '/webview',
      params: {
        url: `${process.env.EXPO_PUBLIC_H5_APPROVAL_URL}/#/pages/Toolbox/report`,
        departmentId: item.ID,
        departmentName: item.Name,
      },
    });
  };
  if (!mounted) return null;

  return (
    <AnimatedPressable style={[styles.modalOverlay, overlayStyle]} onPress={onClose}>
      <AnimatedPressable style={[styles.modalCard, cardStyle]} onPress={() => {}}>
        <CustomText style={styles.modalTitle}>{t('report.selectSiteTitle')}</CustomText>
{list.map(item=>
   (
        <Pressable style={styles.modalRow} onPress={handleSelect} key={item.ID}>
          <CustomText style={styles.modalRowText}>{item.Name}</CustomText>
          <Svg width={wp(12)} height={wp(12)} viewBox="0 0 24 24">
            <Path d="M8 5l8 7-8 7" fill="none" stroke="#C7CDD4" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </Svg>
        </Pressable>
  )
)}

      </AnimatedPressable>
    </AnimatedPressable>
  );
}

const styles = StyleSheet.create({
  modalOverlay: {
    position: 'absolute',
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.45)',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: wp(24),
  },
  modalCard: {
    width: '100%',
    backgroundColor: '#fff',
    borderRadius: wp(12),
    paddingHorizontal: wp(16),
    paddingTop: wp(16),
    paddingBottom: wp(8),
  },
  modalTitle: {
    fontSize: wp(14),
    color: '#333',
    marginBottom: wp(10),
  },
  modalRow: {
    height: wp(48),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    borderTopWidth: StyleSheet.hairlineWidth,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderColor: '#EEF0F3',
    paddingHorizontal: wp(4),
  },
  modalRowText: {
    color: '#192838',
    fontSize: wp(14),
  },
});