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

const DriverCard = ({
  name,
  email,
  status,
  isDark,
  rtl,
  driverId,
  vehicleData,
}: any) => {
  const dispatch = useDispatch()
  const { navigate } = useAppNavigation()
  const { colors } = useTheme()

  const handleDeleteVehicle = async id => {
    return DELETE_API(`${fleetVehicle}/${id}`)
      .then(res => {
        if (res?.status == 200) {
          notificationHelper('', 'Vehicle Deleted Successfully', 'success')
          dispatch(fleetVehicleList())
        }
      })
      .catch(e => {
        return e?.response
      })
  }

  const handleEditVehicle = () => {
    navigate('AddVehicleDetails', { vehicleData, type: 'edit' })
  }

  const statusColor =
    vehicleData?.status === 'pending'
      ? appColors.pending
      : vehicleData?.status === 'rejected'
      ? appColors.reject
      : appColors.approv

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

  return (
    <View
      style={{
        backgroundColor: colors.card,
        borderWidth: windowWidth(0.45),
        borderColor: colors.border,
        width: '90%',
        marginTop: windowHeight(2),
        alignSelf: 'center',
        borderRadius: windowWidth(5),
        paddingVertical: windowHeight(2),
      }}
    >
      <View
        style={{
          flexDirection: rtl ? 'row-reverse' : 'row',
          alignItems: 'center',
          justifyContent: 'space-between',
          marginHorizontal: windowWidth(4),
        }}
      >
        <View
          style={{
            backgroundColor: statusBgColor,
            paddingVertical: windowHeight(1),
            borderRadius: windowHeight(2),
            paddingHorizontal: windowHeight(2),
          }}
        >
          <Text
            style={{
              color: statusColor,
              fontFamily: appFonts.medium,
              fontSize: fontSizes.FONT3HALF,
              textTransform: 'capitalize',
            }}
          >
            {vehicleData?.status || 'N/A'}
          </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: 10,
              alignSelf: 'center',
            }}
          >
            <TouchableOpacity onPress={handleEditVehicle}>
              <Icons.edit color="#60A5FA" />
            </TouchableOpacity>
            <View
              style={{
                height: windowHeight(2.5),
                borderColor: isDark ? appColors.darkborder : appColors.border,
                borderWidth: windowHeight(0.05),
              }}
            />
            <TouchableOpacity onPress={() => handleDeleteVehicle(driverId)}>
              <Icons.Delete />
            </TouchableOpacity>
          </View>
        </View>
      </View>

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

      <View
        style={{
          flexDirection: rtl ? 'row-reverse' : 'row',
          marginTop: windowHeight(0),
          marginHorizontal: windowHeight(2),
        }}
      >
        <View
          style={{
            height: windowHeight(7),
            width: windowHeight(8),
            alignItems: 'center',
            justifyContent: 'center',
            borderRadius: windowWidth(2),
            backgroundColor: colors.background,
          }}
        >
          <Image
            source={{ uri: vehicleData?.vehicle_type_image_url }}
            resizeMode="contain"
            style={{ height: windowHeight(5), width: windowHeight(6) }}
          />
        </View>
        <View
          style={{
            justifyContent: 'space-around',
            flex: 1,
            marginHorizontal: windowWidth(5),
          }}
        >
          <View
            style={{
              flexDirection: rtl ? 'row-reverse' : 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              width: '113%',
            }}
          >
            <View
              style={{
                flexDirection: rtl ? 'row-reverse' : 'row',
                alignItems: 'center',
              }}
            >
              <Text style={{ marginTop: windowHeight(0.3) }}>
                <Icons.NumberPlat />
              </Text>
              <Text
                style={{
                  color: colors.text,
                  fontFamily: appFonts.medium,
                  fontSize: fontSizes.FONT4,
                  marginHorizontal: windowWidth(1),
                }}
              >
                {vehicleData?.plate_number}
              </Text>
            </View>
          </View>
          <View
            style={{
              flexDirection: rtl ? 'row-reverse' : 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
            }}
          >
            <Text
              style={{
                color: isDark ? appColors.white : appColors.black,
                fontFamily: appFonts.medium,
                fontSize: fontSizes.FONT3SMALL,
                textAlign: rtl ? 'left' : 'right',
              }}
            >
              {name}
            </Text>
          </View>
        </View>
      </View>
    </View>
  )
}

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

  const gotoAddVehicle = () => {
    navigate('AddVehicleDetails')
  }
  const [refreshing, setRefreshing] = useState(false)
  const dispatch = useDispatch()

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

  return (
    <View style={{ flex: 1, backgroundColor: colors.background }}>
      <Header
        title={translateData?.manageVehicle}
        style={styles.gap}
        icon={<Icons.plus color={isDark ? appColors.white : appColors.black} />}
        onPress={gotoAddVehicle}
      />
      <ScrollView
        style={{ height: '80%' }}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            tintColor={isDark ? appColors.white : appColors.black}
            colors={[appColors.primary]}
            progressBackgroundColor={
              isDark ? appColors.bgDark : appColors.white
            }
          />
        }
      >
        {!fleetVehicle?.data || fleetVehicle?.data?.length === 0 ? (
          <View>
            <View
              style={{
                marginTop: windowHeight(19),
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <FastImage
                source={isDark ? Images.noVehicleDark : Images.noVehicle}
                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.EmptyVehicleList}
                </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.Pleasetryrefreshing}
              </Text>
            </View>{' '}
          </View>
        ) : (
          <View style={{ marginVertical: windowHeight(3) }}>
            {fleetVehicle?.data?.map((driver: any) => (
              <DriverCard
                key={driver.id}
                driverId={driver.id}
                {...driver}
                isDark={isDark}
                rtl={rtl}
                vehicleData={driver}
                status={driver.status}
              />
            ))}
          </View>
        )}
      </ScrollView>
    </View>
  )
}
