import {
  View,
  Text,
  Image,
  TouchableOpacity,
  Share,
  Linking,
} from "react-native";
import React, { useState, useEffect } from "react";
import styles from "../../styles";
import { useValues } from "@src/utils/context/index";
import Images from "@utils/images";
import {
  Call,
  Message,
  PlatNumber,
  RatingEmptyStart,
  RatingHalfStar,
  RatingStar,
  ShareTrip,
  SOS,
} from "@utils/icons";
import { useNavigation } from "@react-navigation/native";
import style from "./style";
import { useSelector } from "react-redux";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import { SolidLine } from "@src/commonComponent";

export function DriverData({ driverDetails, duration, onSOSPress }) {
  const { bgFullStyle, viewRTLStyle, textColorStyle, textRTLStyle } =
    useValues();
  const { navigate } = useNavigation();
  const [status, setStatus] = useState("ongoing");
  const [endTime, setEndTime] = useState("");
  const [currentTime, setCurrentTime] = useState("");
  const { translateData, taxidoSettingData } = useSelector(
    (state) => state.setting
  );
  const { isDark } = useValues();

  const gotoChat = () => {
    navigate("ChatScreen", {
      driverId: driverDetails?.driver?.id,
      riderId: driverDetails?.rider?.id,
      rideId: driverDetails?.id,
      driverName: driverDetails?.driver?.name,
      driverImage: driverDetails?.driver?.profile_image_url,
    });
  };

  const gotoDiler = (phoneNumber: number) => {
    Linking.openURL(`tel:${phoneNumber}`);
  };

  useEffect(() => {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const ampm = hours >= 12 ? "PM" : "AM";
    const formattedHours = hours % 12 || 12;
    const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;
    const formattedCurrentTime = `${formattedHours}:${formattedMinutes} ${ampm}`;
    setCurrentTime(formattedCurrentTime);
    const endTime = new Date(now.getTime() + duration * 60 * 1000);
    const endHours = endTime.getHours();
    const endMinutes = endTime.getMinutes();
    const endAmpm = endHours >= 12 ? "PM" : "AM";
    const formattedEndHours = endHours % 12 || 12;
    const formattedEndMinutes = endMinutes < 10 ? `0${endMinutes}` : endMinutes;
    const formattedEndTime = `${formattedEndHours}:${formattedEndMinutes} ${endAmpm}`;
    setEndTime(formattedEndTime);
  }, []);

  const handleShare = async () => {
    try {
      const result = await Share.share({
        message: `Gocab Details
                            Expected time of arrival: ${endTime}
                            Pickup: ${driverDetails?.locations[0]}
                            Destination: ${driverDetails?.locations[1]}
                            Driver Name : ${driverDetails?.driver?.name}
                            Vehicle details: 
                            Vehicle Type:  ${driverDetails?.vehicle_type?.vehicle_model}, 
                            Plat No:  ${driverDetails?.vehicle_type?.plate_number}`,
      });

      if (result.action === Share.sharedAction) {
        if (result.activityType) {
        } else {
        }
      } else if (result.action === Share.dismissedAction) {
      }
    } catch (error: any) { }
  };

  return (
    <View style={[styles.card1, { backgroundColor: bgFullStyle }]}>
      <View
        style={{
          flexDirection: viewRTLStyle,
          alignItems: "center",
          justifyContent: "space-between",
          marginHorizontal: windowWidth(6),
        }}
      >
        <View>
          <View style={{ flexDirection: viewRTLStyle, alignItems: "center" }}>
            <Text
              style={[
                styles.number,
                { color: textColorStyle, textAlign: textRTLStyle },
              ]}
            >
              {driverDetails?.plate_number}
            </Text>
          </View>
          <View style={[styles.taxiDetail, { flexDirection: viewRTLStyle }]}>
            <Text style={[styles.taxiType, { color: textColorStyle }]}>
              {driverDetails?.vehicle_type?.vehicle_model}
            </Text>
          </View>
        </View>
        {status === "ongoing" ? (
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={handleShare}
            style={[
              style.shreTripView,
              {
                flexDirection: viewRTLStyle,
              },
            ]}
          >
            <ShareTrip color={textColorStyle} />
            <Text
              style={[
                styles.share,
                {
                  color: appColors.iconColor,
                  marginBottom: 10,
                  marginHorizontal: windowWidth(4),
                },
              ]}
            >
              {translateData.shareTrip}
            </Text>
          </TouchableOpacity>
        ) : null}
      </View>
      <SolidLine color={isDark ? appColors.solidBorder : appColors.lightGray} />

      <View
        style={[
          styles.subCard1,
          { flexDirection: viewRTLStyle, marginHorizontal: windowWidth(12) },
        ]}
      >
        <View style={{ flexDirection: viewRTLStyle }}>
          {driverDetails?.driver?.profile_image_url ? (
            <Image
              source={{ uri: driverDetails?.driver?.profile_image_url }}
              style={styles.driverImage}
            />
          ) : (
            <View
              style={[
                styles.driverImage,
                {
                  backgroundColor: isDark
                    ? appColors.whiteColor
                    : appColors.blackColor,
                  alignItems: "center",
                  justifyContent: "center",
                },
              ]}
            >
              <Text
                style={[
                  styles.drivername,
                  {
                    color: isDark ? appColors.blackColor : appColors.whiteColor,
                  },
                ]}
              >
                {driverDetails?.driver?.name.charAt(0).toUpperCase()}
              </Text>
            </View>
          )}

          <View style={styles.details}>
            <Text style={[styles.name, { color: textColorStyle }]}>
              {driverDetails?.driver?.name}
            </Text>
            <View style={{ flexDirection: viewRTLStyle }}>
              {Array.from({ length: 5 }).map((_, index) => {
                const fullStarThreshold = index + 1;
                const halfStarThreshold = index + 0.5;
                if (driverDetails?.driver?.rating_count >= fullStarThreshold) {
                  return <RatingStar key={index} />;
                } else if (
                  driverDetails?.driver?.rating_count >= halfStarThreshold
                ) {
                  return <RatingHalfStar key={index} />;
                } else {
                  return <RatingEmptyStart key={index} />;
                }
              })}
              <View
                style={{
                  flexDirection: "row",
                  marginHorizontal: windowWidth(3),
                }}
              >
                <Text style={[styles.rating, { color: textColorStyle }]}>
                  {Number(driverDetails?.driver?.rating_count).toFixed(1)}
                </Text>
                <Text style={styles.totalReview}>
                  ({driverDetails?.driver?.review_count})
                </Text>
              </View>
            </View>
          </View>
        </View>
        <View style={{ flexDirection: viewRTLStyle }}>
          {taxidoSettingData?.cabbooking_values?.activation?.sos_enable ==
            0 && (
              <TouchableOpacity
                style={[styles.message, { backgroundColor: appColors.alertRed }]}
                activeOpacity={0.7}
                onPress={onSOSPress}
              >
                <Text
                  style={{
                    color: appColors.whiteColor,
                    fontSize: fontSizes.FONT18,
                  }}
                >
                  {translateData?.SOS || "SOS"}
                </Text>
              </TouchableOpacity>
            )}
        </View>
      </View>

      <View
        style={{
          flexDirection: viewRTLStyle,
        }}
      >
        <TouchableOpacity
          style={[
            styles.message1,
            {
              backgroundColor: isDark
                ? appColors.solidBorder
                : appColors.lightGray,
              alignItems: "flex-start",
              paddingHorizontal: windowWidth(15),
            },
          ]}
          onPress={gotoChat}
          activeOpacity={0.7}
        >
          <Text
            style={{
              marginHorizontal: windowWidth(10),
              fontFamily: appFonts.regular,
              color: appColors.regularText,
            }}
          >
            {translateData?.sendMessage}
          </Text>
        </TouchableOpacity>
        <TouchableOpacity
          activeOpacity={0.7}
          style={[
            styles.message,
            {
              backgroundColor: isDark ? appColors.online : appColors.online,
              marginHorizontal: windowWidth(10),
            },
          ]}
          onPress={() => gotoDiler(driverDetails?.driver?.phone)}
        >
          <Call color={appColors.whiteColor} />
        </TouchableOpacity>
      </View>
    </View>
  );
}
