import { wp } from '@/utils/ui/screenUtils';
import React, { useMemo, useCallback, useRef } from 'react';
import { StyleSheet, Pressable, TextInput, Animated, Keyboard, TouchableWithoutFeedback } from 'react-native';
import { View, XStack, YStack } from 'tamagui';
import { listSend, approvalRemove, approvalV2Status,approvalRevoke } from '@/api/approve';
import dialogService from '@/utils/ui/dialogService.js';
import { showSuccess, showError } from '@/utils/ui/toast';
import { router } from 'expo-router';
import loadingService from '@/utils/ui/loadingService.js';
import { useTranslation } from '@/node_modules/react-i18next';
import { useAppStore } from '@/stores';
import CustomText from '@/components/common/CustomText.jsx';
import { Image } from 'expo-image';

const TAG_DICT = Object.freeze({
  color: Object.freeze({
    1: '#1F80F0',
    2: '#18A058',
    3: '#CF3050',
    4: '#DE428C',
    5: '#DE428C',
    6: '#F09F1F',
    7: '#BCBCBC',
  }),
});

const ApproveCardItem = ({ item, onApprove, onReject, hideActions = false, onDeleted, isMyPending = false, isMeCheck = false, hideRevokeExpedite = false, simulateActions = false }) => {
  const primaryColor = useAppStore(s => s.primary);
  const tag = TAG_DICT;
  const { t } = useTranslation();

  // 解构并计算派生值，逻辑更清晰
  const {
    SubmitterName,
    TypeName,
    NowUserId,
    NowUserName,
    CreatedAt,
    AllStatus,
    Domain,
    ID,
    Type,
    ApprovalOA,
    IsCustom,
    NowLevel,
  } = item || {};

  const statusColor = useMemo(() => tag.color[AllStatus], [AllStatus]);
  const statusText = useMemo(() => t(`approve:status.${AllStatus}`), [AllStatus, t]);
  const createdDate = useMemo(() => CreatedAt?.slice(0, 10) ?? '', [CreatedAt]);
  const headerTitle = useMemo(() => t('approve:card.header', { submitter: SubmitterName, typeName: TypeName }), [t, SubmitterName, TypeName]);
  const isTurnover = useMemo(() => Boolean(Type?.includes('turnover')), [Type]);
  const matchesOA = useMemo(
    () => Boolean(ApprovalOA || IsCustom == 1 || Type === 'exhibition' || Type?.includes('employ') || Type === 'staffSupply'),
    [ApprovalOA, IsCustom, Type]
  );
  const canDelete = useMemo(() => NowLevel === 1 && AllStatus === 1, [NowLevel, AllStatus]);
  const canExpedite = useMemo(() => AllStatus === 1, [AllStatus]);
  const canRevoke = useMemo(() => {
    if (isTurnover) return NowLevel > 1 && AllStatus !== 2 && AllStatus !== 3;
    return ((AllStatus === 1 && NowLevel !== 1) || AllStatus === 2) && matchesOA;
  }, [isTurnover, NowLevel, AllStatus, matchesOA]);

  const summaryText = useMemo(() => {
    const row = item || {};
    const type = row?.Type;
    let result;
    if (type === 'artExhibitionReward' || type === 'exhibition') {
      result = row?.Exhibition?.ApprovalExhibitions?.[0]?.PackageName;
    } else if (type === 'bundlePayPrice') {
      result = row?.BundlePayPrice?.ShowName;
    } else if (row?.ApprovalOA) {
      const char = type ? type.charAt(0).toUpperCase() + type.slice(1) : '';
      result = row?.ApprovalOA?.[char]?.Reason ?? row?.ApprovalOA?.Leave?.Reason;
    } else {
      const src = Array.isArray(row?.ApprovalMark) && row?.ApprovalMark?.length > 0
        ? row?.ApprovalMark
        : Array.isArray(row?.CustomizeInfo)
          ? row?.CustomizeInfo
          : [];
      const list = src
        .filter(v => (v?.ApprovalMark ?? true) && (v?.ApprovalType === 'string' || v?.ApprovalType === 'number'))
        .map(v => `${v?.ApprovalName ?? ''}: ${v?.ApprovalValue ?? ''}`.trim())
        .filter(Boolean);
      result = list.length > 0 ? list.join('，') : row?.maskArr;
    }
    if (Array.isArray(result)) result = result.filter(Boolean).join(' ');
    const txt = typeof result === 'string' ? result.trim() : (result ?? '').toString().trim();
    return txt || '';
  }, [item]);

  // 进入详情
  const handlePressCard = useCallback(() => {
    if (!item?.ID) return;
    router.push({
      pathname: '/webview',
      params: {
        url: `${process.env.EXPO_PUBLIC_H5_APPROVAL_URL}/#/pages/applyfor/components/details/index`,
        ID: item.ID,
        isMeCheck,
      },
    });
  }, [item?.ID, isMeCheck]);

  // 按压动画
  const pressAnim = useRef(new Animated.Value(0)).current; // 0: 未按压, 1: 按压中
  const handlePressIn = useCallback(() => {
    Animated.timing(pressAnim, { toValue: 1, duration: 140, useNativeDriver: true }).start();
  }, [pressAnim]);
  const handlePressOut = useCallback(() => {
    Animated.timing(pressAnim, { toValue: 0, duration: 220, useNativeDriver: true }).start();
  }, [pressAnim]);

  // 事件处理
  const handleExpedite = useCallback(() => {
    dialogService.confirm({
      content: t('approve:dialogs.expedite.confirm'),
      onConfirm: async () => {
        // 防重入
        if (expediteBusyRef.current) return;
        expediteBusyRef.current = true;
        loadingService.show('正在提交');
        let ok = false;
        try {
          const res = await listSend({
            ApprovalStatus: 1,
            ApprovedBossId: NowUserId,
            Title: TypeName,
          });
          if (res.status === 0) {
            loadingService.success(t('approve:toasts.expediteSuccess'));
            ok = true;
          }
        } catch (err) {
          showError(err?.message || t('approve:errors.network'));
        } finally {
          if (!ok) loadingService.hide();
          expediteBusyRef.current = false;
        }
      },
      buttons: [t('approve:buttons.cancel'), t('approve:buttons.confirm')],
    });
  }, [NowUserId, TypeName, t]);

  const expediteBusyRef = useRef(false);
  const deleteBusyRef = useRef(false);
  const approveBusyRef = useRef(false);
  const rejectBusyRef = useRef(false);
  const revokeBusyRef = useRef(false);

  const handleDelete = useCallback(() => {
    dialogService.confirm({
      content: t('approve:dialogs.delete.confirm'),
      onConfirm: async () => {
        if (deleteBusyRef.current) return;
        deleteBusyRef.current = true;
        loadingService.show('正在提交');
        let ok = false;
        try {
          const res = await approvalRemove({ Domain, IDs: [ID] });
          if (res.status === 0) {
            console.log('删除成功', res);
            loadingService.success(t('approve:toasts.deleteSuccess'));
            const maybe = onDeleted && onDeleted();
            if (maybe && typeof maybe.then === 'function') {
              await maybe;
            }
            ok = true;
          }
        } catch (err) {
          showError(err?.message || t('approve:errors.network'));
        } finally {
          if (!ok) loadingService.hide();
          deleteBusyRef.current = false;
        }
      },
      buttons: [t('approve:buttons.cancel'), t('approve:buttons.confirm')],
    });
  }, [Domain, ID, onDeleted, t]);

  const handleReject = useCallback(() => {
    const reasonRef = { current: '' };
    const inputRef = { current: null };
    const Content = () => (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <YStack gap={wp(12)}>
          <CustomText style={{ fontSize: wp(16), fontFamily: 'Bold', textAlign: 'center' }}>
            {t('approve:dialogs.reject.title')}
          </CustomText>
          <TextInput
            ref={(r) => { inputRef.current = r; }}
            placeholder={t('approve:input.placeholder')}
            multiline
            numberOfLines={5}
            returnKeyType="done"
            onSubmitEditing={() => inputRef.current?.blur?.()}
            onChangeText={(tx) => { reasonRef.current = tx; }}
            style={{
              height: wp(120),
              borderWidth: wp(1),
              borderColor: '#E6E6E6',
              borderRadius: wp(6),
              padding: wp(10),
              textAlignVertical: 'top',
              backgroundColor: '#fff',
              width: wp(240),
            }}
          />
        </YStack>
      </TouchableWithoutFeedback>
    );

    dialogService.custom({
      content: <Content />,
      buttons: [t('approve:buttons.cancel'), t('approve:buttons.confirm')],
      closeOnConfirm: false,
      onConfirm: () => {
        if (rejectBusyRef.current) return;
        // 同步操作：立刻收起键盘并关闭弹窗
        Keyboard.dismiss();
        inputRef.current?.blur?.();
        const reason = (reasonRef.current || '').trim();
        if (!reason) {
          showError(t('approve:errors.rejectRequired'));
          return;
        }
        // 立即关闭弹窗，随后异步发送请求
        dialogService.hide();
        if (simulateActions) {
          loadingService.show('正在提交');
          (async () => {
            rejectBusyRef.current = true;
            let ok = false;
            try {
              await new Promise((r) => setTimeout(r, 400));
              loadingService.success(t('approve:toasts.rejectSuccess'));
              const maybe = onReject && onReject(reason, item.ID);
              if (maybe && typeof maybe.then === 'function') {
                await maybe;
              }
              ok = true;
            } catch (err) {
            } finally {
              if (!ok) loadingService.hide();
              rejectBusyRef.current = false;
            }
          })();
          return;
        }
        loadingService.show('正在提交');
        (async () => {
          rejectBusyRef.current = true;
          let ok = false;
          try {
            const res = await approvalV2Status([
              { leaveBalance: null, ID: Number(item.ID), Status: 3, Tips: reason, Title: item.TypeName, Domain: null }
            ]);
            if (res.status === 0) {
              loadingService.success(t('approve:toasts.rejectSuccess'));
              const maybe = onReject && onReject(reason);
              if (maybe && typeof maybe.then === 'function') {
                await maybe;
              }
              ok = true;
            }
          } catch (err) {
            showError(err?.message || t('approve:errors.network'));
          } finally {
            if (!ok) loadingService.hide();
            rejectBusyRef.current = false;
          }
        })();
      },
    });
  }, [onReject, t, item, simulateActions]);

  const handleApprove = useCallback(() => {
    dialogService.confirm({
      content: t('approve:dialogs.approve.confirm'),
      onConfirm: async () => {
        if (approveBusyRef.current) return;
        approveBusyRef.current = true;
        if (simulateActions) {
          loadingService.show('正在提交');
          let ok = false;
          try {
            await new Promise((r) => setTimeout(r, 400));
            loadingService.success(t('approve:toasts.approveSuccess'));
            const maybe = onApprove && onApprove(item.ID);
            if (maybe && typeof maybe.then === 'function') {
              await maybe;
            }
            ok = true;
          } catch (err) {
          } finally {
            if (!ok) loadingService.hide();
            approveBusyRef.current = false;
          }
          return;
        }
        loadingService.show('正在提交');
        let ok = false;
        try {
          const res = await approvalV2Status([
            { leaveBalance: null, ID: Number(item.ID), Status: 2, Tips: '', Title: item.TypeName, Domain: null }
          ]);
          if (res.status === 0) {
            loadingService.success(t('approve:toasts.approveSuccess'));
            const maybe = onApprove && onApprove();
            if (maybe && typeof maybe.then === 'function') {
              await maybe;
            }
            ok = true;
          }
        } catch (err) {
          showError(err?.message || t('approve:errors.network'));
        } finally {
          if (!ok) loadingService.hide();
          approveBusyRef.current = false;
        }
      },
      buttons: [t('approve:buttons.cancel'), t('approve:buttons.confirm')],
    });
  }, [onApprove, item, t, simulateActions]);

  const handleRevoke = useCallback(() => {
    const reasonRef = { current: '' };
    const inputRef = { current: null };
    const Content = () => (
      <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <YStack gap={wp(12)}>
          <CustomText style={{ fontSize: wp(16), fontFamily: 'Bold', textAlign: 'center' }}>
            {t('approve:dialogs.revoke.title')}
          </CustomText>
          <TextInput
            ref={(r) => { inputRef.current = r; }}
            placeholder={t('approve:input.placeholder')}
            multiline
            numberOfLines={5}
          
            returnKeyType="done"
            onSubmitEditing={() => inputRef.current?.blur?.()}
            onChangeText={(tx) => { reasonRef.current = tx; }}
            style={{
              height: wp(120),
              borderWidth: wp(1),
              borderColor: '#E6E6E6',
              borderRadius: wp(6),
              padding: wp(10),
              textAlignVertical: 'top',
              backgroundColor: '#fff',
              width: wp(240),
            }}
          />
        </YStack>
      </TouchableWithoutFeedback>
    );

    dialogService.custom({
      content: <Content />,
      buttons: [t('approve:buttons.cancel'), t('approve:buttons.confirm')],
      closeOnConfirm: false,
      onConfirm: () => {
        if (revokeBusyRef.current) return;
        // 同步操作：立刻收起键盘并关闭弹窗
        Keyboard.dismiss();
        inputRef.current?.blur?.();
        const reason = (reasonRef.current || '').trim();
        if (!reason) {
          showError(t('approve:errors.revokeRequired'));
          return;
        }
        // 立即关闭弹窗，随后异步发送请求
        dialogService.hide();
        loadingService.show('正在提交');
        (async () => {
          revokeBusyRef.current = true;
          let ok = false;
          try {
            const res = await approvalRevoke({ ID: Number(item.ID), RevokeReason: reason });
            if (res.status === 0) {
              loadingService.success(t('approve:toasts.revokeSuccess'));
              const maybe = onDeleted && onDeleted();
              if (maybe && typeof maybe.then === 'function') {
                await maybe;
              }
              ok = true;
            }
          } catch (err) {
            console.error(err);
            showError(err.message);
          } finally {
            if (!ok) loadingService.hide();
            revokeBusyRef.current = false;
          }
        })();
      },
    });
  }, [item, onDeleted, t]);
  return (
    <Pressable onPress={handlePressCard} onPressIn={handlePressIn} onPressOut={handlePressOut} hitSlop={wp(6)} style={{ borderRadius: wp(8) }}>
      <YStack
        backgroundColor="#fff"
        borderRadius={wp(8)}
        paddingInline={wp(8)}
        shadowColor="#00000020"
        shadowOffset={{ width: wp(0), height: wp(1) }}
        paddingBottom={wp(11)}
        shadowOpacity={0.1}
        shadowRadius={wp(3)}
        position="relative"
        overflow="hidden"
      >
        {/* 渐进的按压过渡层：浅灰背景 */}
        <Animated.View
          pointerEvents="none"
          style={[StyleSheet.absoluteFillObject, { backgroundColor: '#F7F7FA', opacity: pressAnim }]}
        />
        {/* 内容区 */}
        <XStack
          paddingInline={wp(7)}
         borderBottomWidth={wp(0.5)}
          borderColor={'#F0F0F0'}
          alignItems="center"
          justifyContent="space-between"
          marginBottom={wp(8)}
        >
          <XStack alignItems="flex-start" paddingVertical={wp(11)}>
            <CustomText style={styles.headerText}>
              {headerTitle}
            </CustomText>
            <View
              justifyContent="center"
              alignItems="center"
              paddingInline={wp(8)}
              height={wp(20)}
              borderRadius={wp(3)}
              borderWidth={wp(1)}
              borderColor={statusColor}
              flexShrink={0}
              // marginTop={(wp(20) - wp(19)) / 2}
            >
              <CustomText style={[styles.statusText, { color: statusColor }]}>
                {statusText}
              </CustomText>
            </View>
          </XStack>
          <CustomText style={styles.dateText}>
            {createdDate}
          </CustomText>
        </XStack>

        <XStack
          paddingInline={wp(7)}
          alignItems="center"
          justifyContent="flex-start"
          marginBottom={summaryText ? wp(8) : 0}
          paddingBottom={summaryText ? wp(11) : 0}
          position="relative"
          paddingRight={wp(150)}
          borderBottomWidth={summaryText ? wp(0.5) : 0}
          borderColor={'#F0F0F0'}
        >
          <YStack gap={wp(4)}>
            <CustomText style={styles.labelText}>{t('approve:card.fields.sn')}{ID}</CustomText>
            <CustomText style={styles.labelText}>{t('approve:card.fields.type')}{TypeName}</CustomText>
            <CustomText style={styles.labelText}>{t('approve:card.fields.approver')}{NowUserName}</CustomText>
          </YStack>
          {!hideActions && (
            <View position="absolute" right={wp(15)} bottom={wp(10)}>
              {isMyPending ? (
                <XStack gap={wp(7)}>
                  <Pressable onPress={handleReject} style={({pressed}) => [styles.actionBtn, styles.actionDanger, pressed && { opacity: 0.85 }]}> 
                    <CustomText style={{ color: '#fff' }}>{t('approve:actions.reject')}</CustomText>
                  </Pressable>
                  <Pressable onPress={handleApprove} style={({pressed}) => [styles.actionBtn, { backgroundColor: primaryColor }, pressed && { opacity: 0.85 }]}> 
                    <CustomText style={{ color: '#fff' }}>{t('approve:actions.approve')}</CustomText>
                  </Pressable>
                </XStack>
              ) : (
                <XStack gap={wp(7)}>
                  {!hideRevokeExpedite && canRevoke && (
                    <Pressable onPress={handleRevoke} style={({pressed}) => [styles.actionBtn, styles.actionNeutral, pressed && { opacity: 0.85 }]}> 
                      <CustomText style={{ color: primaryColor }}>{t('approve:actions.revoke')}</CustomText>
                    </Pressable>
                  )}

                  {canDelete && (
                    <Pressable onPress={handleDelete} style={({pressed}) => [styles.actionBtn, styles.actionNeutral, pressed && { opacity: 0.85 }]}> 
                      <CustomText style={{ color: primaryColor }}>{t('approve:actions.delete')}</CustomText>
                    </Pressable>
                  )}

                  {!hideRevokeExpedite && canExpedite && (
                    <Pressable onPress={handleExpedite} style={({pressed}) => [styles.actionBtn, { backgroundColor: primaryColor }, pressed && { opacity: 0.85 }]}> 
                      <CustomText style={{ color: '#fff' }}>{t('approve:actions.expedite')}</CustomText>
                    </Pressable>
                  )}
                </XStack>
              )}
            </View>
          )}
        </XStack>

        {summaryText ? (
          <XStack flex={1} paddingLeft={wp(10)} paddingRight={wp(10)}>
            <Image source={require('@/assets/images/icon/abstract.png')} style={styles.summaryIcon} />
            <CustomText style={styles.summaryText} numberOfLines={2}>
              {summaryText}
            </CustomText>
          </XStack>
        ) : null}
      </YStack>
    </Pressable>
  );
};

function areEqual(prevProps, nextProps) {
  const p = prevProps.item || {};
  const n = nextProps.item || {};
  return (
    prevProps.hideActions === nextProps.hideActions &&
    prevProps.hideRevokeExpedite === nextProps.hideRevokeExpedite &&
    prevProps.isMyPending === nextProps.isMyPending &&
    prevProps.simulateActions === nextProps.simulateActions &&
    prevProps.onApprove === nextProps.onApprove &&
    prevProps.onReject === nextProps.onReject &&
    prevProps.onDeleted === nextProps.onDeleted &&
    p.ID === n.ID &&
    p.AllStatus === n.AllStatus &&
    p.NowLevel === n.NowLevel &&
    p.NowUserId === n.NowUserId &&
    p.NowUserName === n.NowUserName &&
    p.SubmitterName === n.SubmitterName &&
    p.TypeName === n.TypeName &&
    p.CreatedAt === n.CreatedAt &&
    p.Type === n.Type &&
    p.ApprovalOA === n.ApprovalOA &&
    p.IsCustom === n.IsCustom &&
    p.Domain === n.Domain &&
    p.Exhibition === n.Exhibition &&
    p.BundlePayPrice === n.BundlePayPrice &&
    p.maskArr === n.maskArr &&
    p.ApprovalMark === n.ApprovalMark &&
    p.CustomizeInfo === n.CustomizeInfo
  );
}

export default React.memo(ApproveCardItem, areEqual);

const styles = StyleSheet.create({
  actionBtn: {
    width: wp(53),
    height: wp(30),
    borderRadius: wp(3),
    justifyContent: 'center',
    alignItems: 'center',
  },
  actionNeutral: {
    backgroundColor: '#FEEAF5',
  },
  actionDanger: {
    backgroundColor: '#CF3050',
  },
  headerText: {
    color: '#191919',
    fontSize: wp(14),
    lineHeight: wp(20),
    fontFamily: 'Bold',
    marginRight: wp(6),
    maxWidth: wp(150),
  },
  statusText: {
    fontSize: wp(12),
    fontFamily: 'Bold',
    textAlign: 'center',
    includeFontPadding: false,
    textAlignVertical: 'center',
    paddingVertical: 0,
  },
  dateText: {
    color: '#828282',
    fontSize: wp(14),
  },
  labelText: {
    color: '#191919',
    fontSize: wp(12),
  },
  summaryIcon: {
    width: wp(14),
    height: wp(14),
    marginRight: wp(6),
    marginTop: wp(2),
  },
  summaryText: {
    color: '#191919',
    fontSize: wp(12),
    flex: 1,
    lineHeight: wp(15),
  },
});
