import {
  View,
  Text,
  TouchableOpacity,
  Image,
  ScrollView,
  RefreshControl,
} from 'react-native'
import React, { useCallback, useState } from 'react'
import {
  BackButton,
  Header,
  notificationHelper,
} from '../../../commonComponents'
import appColors from '../../../theme/appColors'
import styles from './styles'
import {
  fontSizes,
  windowHeight,
  windowWidth,
} from '../../../theme/appConstant'
import Icons from '../../../utils/icons/icons'
import Images from '../../../utils/images/images'
import appFonts from '../../../theme/appFonts'
import { useAppNavigation } from '../../../utils/navigation'
import { useValues } from '../../../utils/context'
import { DELETE_API } from '../../../api/methods'
import { fleetDriverDelete } from '../../../api/endpoints/fleetEndpoint'
import { fleetDriverList } from '../../../api/store/action'
import { useDispatch, useSelector } from 'react-redux'
import { useTheme } from '@react-navigation/native'
import FastImage from 'react-native-fast-image'
import { AppDispatch } from '../../../api/store'

type UserCardType = {
  name: string
  email: string
  status: string
  statusColor: string
  bgColor: string
  isDark: boolean
  rtl?: boolean
  driverId: number
  driverData: object
}

const DriverCard = ({ name, email, status, driverId, driverData }: any) => {
  const dispatch = useDispatch()
  const { navigate } = useAppNavigation()
  const { isDark, rtl, viewRtlStyle } = useValues()
  const { colors } = useTheme()
  const { translateData } = useSelector((state: any) => state.setting)

  const handleDeleteDriver = async id => {
    return DELETE_API(`${fleetDriverDelete}/${id}`)
      .then(res => {
        if (res?.status == 200) {
          notificationHelper('', translateData?.vehicleDeletedSuccessfully, 'success')
          dispatch(fleetDriverList())
        }
      })
      .catch(e => {
        return e?.response
      })
  }

  const handleEditDriver = () => {
    navigate('AddDriverDetails', { driverData, type: 'edit' })
  }
  const statusColor =
    driverData?.status === 'pending'
      ? appColors.pending
      : driverData?.status === 'rejected'
        ? appColors.reject
        : appColors.approv

  const statusBgColor =
    driverData?.status === 'pending'
      ? appColors.pendingBg
      : driverData?.status === 'rejected'
        ? appColors.rejectBg
        : appColors.approvBg

  return (
    <View
      style={{
        backgroundColor: isDark ? appColors.primaryFont : appColors.white,
        borderWidth: windowWidth(0.45),
        borderColor: isDark ? appColors.darkborder : appColors.loader,
        width: '90%',
        marginTop: windowHeight(3),
        alignSelf: 'center',
        borderRadius: windowWidth(5),
        paddingVertical: windowHeight(2),
      }}
    >
      <View
        style={{
          flexDirection: viewRtlStyle,
          alignItems: 'center',
          justifyContent: 'space-between',
          marginHorizontal: windowWidth(4),
          marginBottom: windowHeight(0.5),
        }}
      >
        <View
          style={{
            backgroundColor: statusBgColor,
            height: windowHeight(3.5),
            borderRadius: windowHeight(2),
            paddingHorizontal: windowWidth(4),
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <Text
            style={{
              color: statusColor,
              fontFamily: appFonts.medium,
              fontSize: fontSizes.FONT3HALF,
            }}
          >
            {status}
          </Text>
        </View>

        <View
          style={{
            flexDirection: rtl ? 'row-reverse' : 'row',
            justifyContent: 'space-between',
          }}
        >
          <View
            style={{
              alignItems: 'flex-end',
              flexDirection: rtl ? 'row-reverse' : 'row',
              justifyContent: 'space-between',
              gap: 8,
            }}
          >
            <TouchableOpacity onPress={handleEditDriver}>
              <Icons.edit color="#60A5FA" />
            </TouchableOpacity>{' '}
            <View
              style={{
                height: windowHeight(2),
                borderColor: isDark ? appColors.darkborder : appColors.border,
                borderWidth: windowHeight(0.1),
              }}
            />
            <TouchableOpacity onPress={() => handleDeleteDriver(driverId)}>
              <Icons.Delete />
            </TouchableOpacity>
          </View>
        </View>
      </View>

      <View
        style={{
          height: windowHeight(0.6),
          backgroundColor: colors.background,
          width: '100%',
          alignSelf: 'center',
          marginVertical: windowHeight(1),
        }}
      />

      <View style={{ marginTop: windowHeight(0.5) }}>
        <View
          style={{
            flexDirection: rtl ? 'row-reverse' : 'row',
            marginHorizontal: windowHeight(2),
            alignItems: 'center',
          }}
        >
          <Image
            source={Images.user}
            resizeMode="contain"
            style={{ height: windowHeight(5.5), width: windowHeight(5.5) }}
          />

          <View>
            <View
              style={{
                flexDirection: viewRtlStyle,
                alignItems: 'center',
                marginHorizontal: windowWidth(2),
              }}
            >
              <View>
                <Text
                  style={{
                    color: isDark ? appColors.white : appColors.black,
                    fontFamily: appFonts.medium,
                    fontSize: fontSizes.FONT3SMALL,
                    textAlign: rtl ? 'left' : 'right',
                  }}
                >
                  {name}
                </Text>
              </View>
              <View style={{ marginHorizontal: windowWidth(1) }}>
                <Icons.Name />
              </View>
            </View>
            <View
              style={{
                flexDirection: viewRtlStyle,
                alignItems: 'center',
                marginHorizontal: windowWidth(2),
              }}
            >
              {(() => {
                const rating = driverData?.rating_count || 0
                const fullStars = Math.floor(rating)
                const hasHalfStar = rating % 1 >= 0.5
                const totalStars = 5
                const stars = []

                for (let i = 0; i < totalStars; i++) {
                  if (i < fullStars) {
                    stars.push(
                      <View style={{ marginHorizontal: windowWidth(0.3) }}>
                        <Icons.Star key={`full-${i}`} />
                      </View>,
                    )
                  } else if (i === fullStars && hasHalfStar) {
                    stars.push(
                      <View style={{ marginHorizontal: windowWidth(0.3) }}>
                        <Icons.StarHalf key={`half-${i}`} />
                      </View>,
                    )
                  } else {
                    stars.push(
                      <View style={{ marginHorizontal: windowWidth(0.3) }}>
                        <Icons.UnfillStar key={`empty-${i}`} />
                      </View>,
                    )
                  }
                }

                return stars
              })()}

              <Text
                style={{
                  color: isDark ? appColors.darkText : appColors.iconColor,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT3SMALL,
                  marginHorizontal: windowWidth(1.5),
                }}
              >
                {driverData?.rating_count}
              </Text>

              <Text
                style={{
                  color: isDark ? appColors.darkText : appColors.iconColor,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT3SMALL,
                }}
              >
                {`(${driverData?.review_count})`}
              </Text>
            </View>
          </View>
        </View>
      </View>
    </View>
  )
}

const DriverList = () => {
  const { fleetDriver, fleetVehicle } = useSelector((state: any) => state.fleet)
  const { navigate } = useAppNavigation()
  const { colors } = useTheme()
  const { isDark, viewRtlStyle } = useValues()
  const { translateData } = useSelector((state: any) => state.setting)

  const gotoAddDriver = useCallback(() => {
    if (fleetVehicle?.data.length === 0) {
      notificationHelper('', translateData?.driverfleet, 'error')
      return
    } else {
      navigate('AddDriverDetails')
    }
  }, [navigate])
  const [refreshing, setRefreshing] = useState(false)
  const dispatch = useDispatch<AppDispatch>()

  const onRefresh = useCallback(async () => {
    setRefreshing(true)
    try {
      await dispatch(fleetDriverList() as any)
    } catch (error) {
      console.error('Error refreshing driver list:', error)
    } finally {
      setRefreshing(false)
    }
  }, [dispatch])

  return (
    <View style={{ flex: 1, backgroundColor: colors.background }}>
      <Header
        title={translateData?.manageDriver}
        style={styles.gap}
        icon={<Icons.plus color={isDark ? appColors.white : appColors.black} />}
        onPress={gotoAddDriver}
      />

      <ScrollView
        style={{ height: '100%' }}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={isDark ? appColors.white : appColors.black}
            colors={[appColors.primary]}
            progressBackgroundColor={
              isDark ? appColors.bgDark : appColors.white
            }
          />
        }
      >
        {!fleetDriver?.data || fleetDriver?.data?.length === 0 ? (
          <View>
            <View
              style={{
                marginTop: windowHeight(22),
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <FastImage
                source={
                  isDark ? Images.emptyDriverListDark : Images.emptyDriverList
                }
                style={{
                  height: windowHeight(30),
                  width: windowHeight(30),
                }}
                resizeMode="contain"
              />

              <View
                style={{
                  flexDirection: viewRtlStyle,
                  alignItems: 'center',
                  marginTop: windowHeight(2),
                }}
              >
                <Text
                  style={{
                    color: isDark ? appColors.white : appColors.black,
                    fontSize: fontSizes.FONT4HALF,
                    fontFamily: appFonts.medium,
                    textAlign: 'center',
                    marginRight: 6,
                  }}
                >
                  {translateData.EmptyDriverList}
                </Text>
                <FastImage
                  source={Images.infoCircle}
                  style={{
                    height: windowHeight(2.5),
                    width: windowHeight(2.5),
                  }}
                  resizeMode="contain"
                />
              </View>

              <Text
                style={{
                  textAlign: 'center',
                  paddingHorizontal: windowWidth(5),
                  color: appColors.darkBorderBlack,
                  marginTop: windowHeight(1),
                }}
              >
                {translateData.EmptyDriverListNote}
              </Text>
            </View>{' '}
          </View>
        ) : (
          fleetDriver?.data.map((driver: any) => (
            <DriverCard
              key={driver.id}
              {...driver}
              driverId={driver.id}
              driverData={driver}
              status={driver.status}
            />
          ))
        )}
      </ScrollView>
    </View>
  )
}

export default DriverList
