import React, { useState, useRef, useMemo, useCallback, useEffect } from 'react'
import { View, Text, TouchableOpacity, TextInput, Keyboard } from 'react-native'
import BottomSheet, {
  BottomSheetBackdrop,
  BottomSheetView,
} from '@gorhom/bottom-sheet'
import appColors from '../../../theme/appColors'
import Icons from '../../../utils/icons/icons'
import styles from './styles'
import { Button } from '../../../commonComponents'
import { useTheme } from '@react-navigation/native'
import { useValues } from '../../../utils/context'
import { userReview } from '../../../api/store/action'
import { useDispatch, useSelector } from 'react-redux'
import { ReviewInterface } from '../../../api/interface/reviewInterface'
import { fontSizes, windowHeight } from '../../../theme/appConstant'
import { AppDispatch } from '../../../api/store'
import appFonts from '../../../theme/appFonts'

export function RateCustomer({ bottomSheetRef }: any) {
  const [rating, setRating] = useState<number>(0)
  const [reviewText, setReviewText] = useState<string>('')
  const { colors } = useTheme()
  const { viewRtlStyle, textRtlStyle, isDark } = useValues()
  const dispatch = useDispatch<AppDispatch>()
  const { rideGet } = useSelector((state: any) => state.ride)
  const { translateData } = useSelector((state: any) => state.setting)
  const [isKeyboardVisible, setKeyboardVisible] = useState<boolean>(false)

  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener(
      'keyboardDidShow',
      () => {
        setKeyboardVisible(true)
        bottomSheetRef?.current?.expand()
      },
    )
    const keyboardDidHideListener = Keyboard.addListener(
      'keyboardDidHide',
      () => {
        setKeyboardVisible(false)
        bottomSheetRef?.current?.close()
      },
    )

    return () => {
      keyboardDidShowListener.remove()
      keyboardDidHideListener.remove()
    }
  }, [])
  const snapPoints = useMemo(() => ['37%', '70%'], [])

  const handleClose = () => {
    bottomSheetRef.current?.close()
  }

  const handleStarPress = (selectedRating: number) => {
    setRating(selectedRating)
  }

  const reviewSubmit = () => {
    let payload: ReviewInterface = {
      ride_id: rideGet?.id,
      rating: rating,
      description: reviewText,
    }

    dispatch(userReview(payload))
      .unwrap()
      .then((res: any) => {
        bottomSheetRef.current?.close()
      })
  }

  const renderBackdrop = useCallback(
    (props: any) => (
      <BottomSheetBackdrop
        {...props}
        pressBehavior="close"
        appearsOnIndex={0}
        disappearsOnIndex={-1}
        onPress={handleClose}
      />
    ),
    [],
  )

  return (
    <BottomSheet
      ref={bottomSheetRef}
      index={-1}
      snapPoints={snapPoints}
      enablePanDownToClose
      backdropComponent={renderBackdrop}
      handleIndicatorStyle={{
        backgroundColor: appColors.primary,
        width: '13%',
      }}
      onClose={handleClose}
      backgroundStyle={{
        backgroundColor: isDark ? appColors.bgDark : appColors.white,
      }}
    >
      <BottomSheetView style={styles.contentContainer}>
        <View>
          <View
            style={[
              styles.rateview,
              { backgroundColor: colors.card, borderColor: colors.border },
            ]}
          >
            <Text
              style={[
                styles.title,
                {
                  color: isDark ? appColors.white : appColors.black,
                  textAlign: textRtlStyle,
                },
              ]}
            >
              {translateData.rateaCustomer}
            </Text>

            <View>
              <View
                style={[styles.round, { backgroundColor: colors.text }]}
              >
                <Text
                  style={{
                    fontFamily: appFonts.semiBold,
                    fontSize: fontSizes.FONT5,
                    color: isDark ? appColors.black : appColors.white,
                  }}
                >
                  {rideGet?.rider?.name?.charAt(0)?.toUpperCase()}
                </Text>
              </View>
              <Text
                style={{
                  color: colors.text,
                  alignSelf: 'center',
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT4,
                  marginVertical: windowHeight(1),
                  marginBottom: windowHeight(0.5),
                }}
              >
                {rideGet?.rider?.name}
              </Text>
              <Text
                style={{
                  color: appColors.iconColor,
                  alignSelf: 'center',
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT3HALF,
                }}
              >
                {rideGet?.rider?.email}
              </Text>
            </View>

            <View
              style={[
                styles.boldLine,
                { backgroundColor: colors.background },
              ]}
            />
            <Text
              style={[
                styles.message,
                {
                  color: colors.text,
                  textAlign: textRtlStyle,
                  marginBottom: windowHeight(2),
                  marginTop: 0,
                },
              ]}
            >
              {translateData?.raterider}
            </Text>
            <View
              style={[
                styles.container,
                {
                  flexDirection: viewRtlStyle,
                  borderColor: colors.border,
                  backgroundColor: colors.background,
                },
              ]}
            >
              {[1, 2, 3, 4, 5].map(index => (
                <TouchableOpacity
                  key={index}
                  onPress={() => handleStarPress(index)}
                  style={styles.starIcon}
                >
                  {index <= rating ? (
                    <Icons.StarFill />
                  ) : (
                    <Icons.StarEmpty fill={colors.card} />
                  )}
                </TouchableOpacity>
              ))}

              <View
                style={[styles.ratingView, { flexDirection: viewRtlStyle }]}
              >
                <Text
                  style={[
                    styles.rating,
                    {
                      color: isDark
                        ? appColors.white
                        : appColors.primaryFont,
                    },
                  ]}
                >
                  {rating}/5
                </Text>
              </View>
            </View>

            <Text
              style={[
                styles.message,
                {
                  color: colors.text,
                  textAlign: textRtlStyle,
                  marginTop: windowHeight(2),
                },
              ]}
            >
              {translateData.customMessage}
            </Text>

            <TextInput
              style={[
                styles.input,
                {
                  backgroundColor: colors.card,
                  borderColor: colors.border,
                  color: isDark ? appColors.white : appColors.primaryFont,
                  textAlign: textRtlStyle,
                },
              ]}
              placeholder={translateData.writeHere}
              placeholderTextColor={appColors.secondaryFont}
              multiline
              numberOfLines={2}
              value={reviewText}
              onChangeText={setReviewText}
            />
          </View>
          <View
            style={{
              width: '110%',
              alignSelf: 'center',
              marginTop: windowHeight(3),
              marginBottom: windowHeight(3),
            }}
          >
            <Button
              title={translateData.submit}
              color={isDark ? appColors.black : appColors.white}
              backgroundColor={colors.text}
              onPress={reviewSubmit}
            />
          </View>
        </View>
      </BottomSheetView>
    </BottomSheet>
  )
}
