import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  Alert,
  ScrollView,
} from "react-native";
import React, { useState, useEffect } from "react";
import {
  Button,
  Header,
  HeaderContainer,
  InputText,
  notificationHelper,
  SwitchComponent,
} from "@src/commonComponent";
import {
  appColors,
  appFonts,
  fontSizes,
  windowHeight,
  windowWidth,
} from "@src/themes";
import {
  Clock,
  Gps,
  LocationFill,
  PickLocation,
  PickUpLocation,
  Target,
} from "@src/utils/icons";
import { useNavigation, useRoute } from "@react-navigation/native";
import { RentalInterface } from "@src/api/interface/rentalinterface";
import { rentalvehicleRequest } from "@src/api/store/actions";
import { useDispatch, useSelector } from "react-redux";
import styles from "./styles";
import { useValues } from "@src/utils/context/index";

import { external } from "@src/styles/externalStyle";
import { Calender1 } from "@src/assets/icons/calender1";
import { getValue } from "@src/utils/localstorage";
import { AppDispatch } from "@src/api/store";

export function RentalBooking() {
  const [toggle, setToggle] = useState(false);
  const [getDriver, setGetDriver] = useState(false);
  const { navigate } = useNavigation<any>();
  const route = useRoute();
  const [startDate, setStartDate] = useState("");
  const [startTime, setStartTime] = useState("");
  const [endDate, setEndDate] = useState("");
  const [endTime, setEndTime] = useState("");
  const [pickupLocation, setPickUpLocation] = useState();
  const [dropLocation, setDropLocation] = useState();
  const [pickUpCoords, setPickupCoords] = useState();
  const [dropCoords, setDropCoords] = useState();
  const dispatch = useDispatch<AppDispatch>();
  const [loading, setLoading] = useState(true);
  const {
    linearColorStyle,
    textColorStyle,
    viewRTLStyle,
    textRTLStyle,
    bgContainer,
    isDark,
    Google_Map_Key,
  } = useValues();
  const {
    DateValue,
    TimeValue,
    field,
    service_category_ID,
    service_category_slug,
    service_name,
    service_ID,
  }: any = route.params || {};
  const { selectedAddress, fieldValue }: any = route.params || {};
  const date = new Date(startDate);
  const day = date.getDate();
  const { translateData } = useSelector((state) => state.setting);
  const [findLoading, setFindLoading] = useState(false);
  const [errors, setErrors] = useState({
    startDate: "",
    startTime: "",
    endDate: "",
    endTime: "",
    invalidRange: "",
    pickupLocation: "",
    dropLocation: "",
  });
  const [onFocus, setOnFocus] = useState(false);
  const [activeField, setActiveField] = useState<string | null>(null);

  useEffect(() => {
    if (field === "startTime") {
      setStartDate(DateValue);
      setStartTime(TimeValue);
    } else if (field === "endTime") {
      setEndDate(DateValue);
      setEndTime(TimeValue);
    }
  }, [DateValue, TimeValue, field]);

  const handleToggle = () => {
    setToggle((prevToggle) => !prevToggle);
  };

  const handleToggleDriver = () => {
    setGetDriver((prevToggle) => !prevToggle);
  };

  const gotoCalander = (value: any) => {
    navigate("Calander", {
      fieldValue: value,
      startDate: startDate,
    });
  };

  const geocodeAddress = async (address) => {
    try {
      const response = await fetch(
        `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(
          address
        )}&key=${Google_Map_Key}`
      );
      const dataMap = await response.json();
      if (dataMap.results.length > 0) {
        const location = dataMap.results[0].geometry.location;
        return {
          lat: location.lat,
          lng: location.lng,
        };
      }
    } catch (error) { }
    return null;
  };

  useEffect(() => {
    if (fieldValue === "pickupLocation") {
      setPickUpLocation(selectedAddress);
    } else if (fieldValue === "destination") {
      setDropLocation(selectedAddress);
    }
  }, [selectedAddress, fieldValue]);

  useEffect(() => {
    const fetchCoordinates = async () => {
      try {
        const pickup = await geocodeAddress(pickupLocation);
        setPickupCoords(pickup);
        const drop = await geocodeAddress(dropLocation);
        setDropCoords(drop);
      } catch (error) {
      } finally {
        setLoading(false);
      }
    };

    fetchCoordinates();
  }, [pickupLocation, dropLocation]);

  useEffect(() => {
    setErrors((prevErrors) => ({
      ...prevErrors,
      startDate: startDate ? "" : prevErrors.startDate,
      startTime: startTime ? "" : prevErrors.startTime,
      endDate: endDate ? "" : prevErrors.endDate,
      endTime: endTime ? "" : prevErrors.endTime,
      pickupLocation: pickupLocation ? "" : prevErrors.pickupLocation,
      dropLocation: dropLocation ? "" : prevErrors.dropLocation,
    }));
  }, [startDate, startTime, endDate, endTime, dropLocation]);

  const findCar = async () => {
    const token = await getValue("token");

    if (!token) {
      navigate("SignIn");
    }

    setFindLoading(true);
    let newErrors = {
      startDate: "",
      startTime: "",
      endDate: "",
      endTime: "",
      invalidRange: "",
      pickupLocation: "",
      dropLocation: "",
    };

    let hasError = false;

    if (!pickupLocation) {
      newErrors.pickupLocation = translateData?.pickuplocate;
      hasError = true;
    }

    if (toggle && !dropLocation) {
      newErrors.dropLocation = translateData?.droplocation;
      hasError = true;
    }

    if (!startDate) {
      newErrors.startDate = translateData?.date;
      hasError = true;
    }

    if (!startTime) {
      newErrors.startTime = translateData?.timeselect;
      hasError = true;
    }

    if (!endDate) {
      newErrors.endDate = translateData.selectAnEndDate;
      hasError = true;
    }

    if (!endTime) {
      newErrors.endTime = translateData.selectAnEndTime;
      hasError = true;
    }
    if (startDate && startTime && endDate && endTime) {
      const start = `${startDate} ${startTime}`;
      const end = `${endDate} ${endTime}`;
      if (end <= start) {
        newErrors.invalidRange = translateData?.samedate;
        hasError = true;
      }
    }

    setErrors(newErrors);
    if (hasError) {
      setFindLoading(false);
      return;
    }
    !errors && setFindLoading(true);
    try {
      const pickup = await geocodeAddress(pickupLocation);

      if (pickup) {
        let payload: RentalInterface = {
          locations: [
            {
              lat: pickup?.lat,
              lng: pickup?.lng,
            },
          ],
          service_category: "rental",
        };

        dispatch(rentalvehicleRequest(payload))
          .unwrap()
          .then(async (res: any) => {
            if (res.success) {
              setFindLoading(false);
              navigate("RentalVehicleSelect", { payload });
            } else {
              setFindLoading(false);
              navigate("RentalVehicleSelect", {
                startDate,
                pickUpCoords,
                pickupLocation,
                dropLocation,
                dropCoords,
                service_category_ID,
                endDate,
                startTime,
                endTime,
                getDriver,
              });
            }
          })
          .catch((error: any) => { });
      } else {
      }
    } catch (error) { }
  };
  const handleFocus = (id: number) => {
    if (id === 1) {
      setActiveField("pickupLocation");
    } else if (id === 2) {
      setActiveField("destination");
    }
  };

  const gotoSelection = () => {
    setOnFocus(false);
    navigate("LocationSelect", {
      field: activeField,
      screenValue: "RentalBooking",
      service_ID: service_ID,
      service_name: service_name,
      service_category_ID: service_category_ID,
      service_category_slug: service_category_slug,
      formattedDate: DateValue,
      formattedTime: TimeValue,
    });
  };

  function formatStartDate(dateStr) {
    if (!dateStr) return translateData?.selectdate;

    const parts = dateStr.split(" ");
    if (parts.length < 3) return translateData?.selectdate;

    const [day, month, year] = parts;
    const monthNames = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ];
    const monthIndex = monthNames.indexOf(month.slice(0, 3));

    if (monthIndex === -1) return translateData?.selectdate;

    const dateObj = new Date(`20${year.slice(-2)}`, monthIndex, parseInt(day));
    dateObj.setDate(dateObj.getDate() + 1);

    const formattedDay = String(dateObj.getDate()).padStart(2, "0");
    const formattedMonth = String(dateObj.getMonth() + 1).padStart(2, "0");
    const formattedYear = dateObj.getFullYear();



    return `${formattedDay}/${formattedMonth}/${formattedYear}`;
  }

  const formatted = formatStartDate(startDate);
  const formattedEndDate = formatStartDate(endDate);


  return (
    <View style={external.main}>
      <View
        style={[
          { flex: 1 },
          {
            backgroundColor: isDark
              ? appColors.solidBorder
              : appColors.lightGray,
          },
        ]}
      >
        <HeaderContainer value={translateData.location} />
        <ScrollView style={styles.inputMainView}>
          <View
            style={[
              styles.con,
              {
                backgroundColor: isDark
                  ? appColors.primaryText
                  : appColors.whiteColor,
                borderColor: isDark ? appColors.darkBorder : appColors.go,
              },
            ]}
          >
            <View
              style={[
                {
                  flexDirection: viewRTLStyle,
                  alignItems: "center",
                  marginHorizontal: windowWidth(15),
                  marginBottom: windowHeight(5),
                },
              ]}
            >
              <View
                style={[
                  styles.searchView,
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.lightGray,
                  },
                ]}
              >
                <PickLocation />
              </View>
              <View>
                <TextInput
                  placeholder={translateData.enterPickupLocation}
                  placeholderTextColor={
                    isDark ? appColors.darkText : appColors.regularText
                  }
                  value={pickupLocation}
                  onChangeText={(text) => {
                    setPickUpLocation(text);
                    if (text.trim() === "") {
                      setErrors((prev) => ({
                        ...prev,
                        pickupLocation:
                          translateData.pleaseEnterAPickupLocation,
                      }));
                    } else {
                      setErrors((prev) => ({ ...prev, pickupLocation: "" }));
                    }
                  }}
                  onFocus={() => {
                    handleFocus(1);
                  }}
                  style={{
                    marginHorizontal: windowWidth(15),
                    color: isDark ? appColors.whiteColor : appColors.blackColor,
                    marginTop: windowHeight(4),
                    width: windowWidth(335),
                    height: windowHeight(40),
                  }}
                />
              </View>
            </View>

            <View>
              {toggle && (
                <View
                  style={[
                    {
                      flexDirection: viewRTLStyle,
                      alignItems: "center",
                      marginHorizontal: windowWidth(15),
                      marginBottom: windowHeight(5),
                      marginTop: windowHeight(8),
                    },
                  ]}
                >
                  <View
                    style={[
                      styles.searchView,
                      {
                        backgroundColor: isDark
                          ? appColors.primaryText
                          : appColors.lightGray,
                      },
                    ]}
                  >
                    <LocationFill color={appColors.dotLight} />
                  </View>
                  <TextInput
                    placeholder={translateData.dropLocation}
                    placeholderTextColor={
                      isDark ? appColors.darkText : appColors.regularText
                    }
                    value={dropLocation}
                    onChangeText={(text) => {
                      setDropLocation(text);
                      if (text.trim() === "") {
                        setErrors((prev) => ({
                          ...prev,
                          dropLocation: "error",
                        }));
                      } else {
                        setErrors((prev) => ({ ...prev, dropLocation: "" }));
                      }
                    }}
                    onFocus={() => {
                      handleFocus(2);
                    }}
                    warningText={errors.dropLocation ? errors.dropLocation : ""}
                    style={{
                      marginHorizontal: windowWidth(15),
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                      marginTop: windowHeight(4),
                      width: windowWidth(335),
                      height: windowHeight(40),
                    }}
                  />
                </View>
              )}
            </View>

            <View
              style={[
                styles.line,
                {
                  backgroundColor: isDark
                    ? appColors.solidBorder
                    : appColors.lightGray,
                },
              ]}
            />
            <TouchableOpacity
              onPress={gotoSelection}
              style={{
                backgroundColor: isDark
                  ? appColors.solidBorder
                  : appColors.lightGray,
                flexDirection: "row",
                paddingVertical: windowHeight(12),
                paddingHorizontal: windowWidth(15),
                borderRadius: windowHeight(35),
                alignItems: "center",
                justifyContent: "center",
                marginTop: windowHeight(10),
                marginHorizontal: windowWidth(15),
              }}
              activeOpacity={0.8}
            >
              <Gps colors={appColors.dotLight} />
              <Text
                style={{
                  marginHorizontal: windowWidth(10),
                  fontFamily: appFonts.medium,
                  color: isDark ? appColors.whiteColor : appColors.blackColor,
                }}
              >
                {translateData?.locateonMap}
              </Text>
            </TouchableOpacity>
          </View>

          <View
            style={[
              styles.dropView,
              { flexDirection: viewRTLStyle },
              {
                backgroundColor: isDark
                  ? appColors.primaryText
                  : appColors.whiteColor,
                borderColor: isDark ? appColors.darkBorder : appColors.go,
              },
            ]}
          >
            <Text
              style={{
                color: textColorStyle,
                fontFamily: appFonts.medium,
              }}
            >
              {translateData.dropLocations}
            </Text>
            <SwitchComponent
              Enable={toggle}
              onPress={handleToggle}
            ></SwitchComponent>
          </View>
          <View
            style={[
              styles.datetimeView,
              {
                backgroundColor: isDark
                  ? appColors.primaryText
                  : appColors.whiteColor,
                borderColor: isDark ? appColors.darkBorder : appColors.go,
              },
            ]}
          >
            <Text
              style={[
                styles.datetimeText,
                { textAlign: textRTLStyle },
                { color: textColorStyle },
              ]}
            >
              {translateData.startTimedate}
            </Text>

            <View style={[styles.row, { flexDirection: viewRTLStyle }]}>
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => gotoCalander("startTime")}
                style={[
                  styles.clockBtn,
                  { flexDirection: viewRTLStyle },
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.whiteColor,
                  },
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.lightGray,
                  },
                ]}
              >
                <View style={styles.calenderView}>
                  <Clock color={appColors.regularText} />
                </View>
                <TextInput
                  placeholder={translateData.selectTime}
                  placeholderTextColor={
                    isDark ? appColors.darkText : appColors.blackColor
                  }
                  style={[
                    styles.timeText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                  editable={false}
                  pointerEvents="none"
                  value={startTime}
                />
              </TouchableOpacity>
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => gotoCalander("startTime")}
                style={[
                  styles.clockBtn,
                  { flexDirection: viewRTLStyle },
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.whiteColor,
                  },
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.lightGray,
                  },
                ]}
              >
                <View style={styles.paddingHr}>
                  <Calender1 />
                </View>
                <TextInput
                  placeholder={translateData.selectDate}
                  placeholderTextColor={
                    isDark ? appColors.darkText : appColors.regularText
                  }
                  style={[
                    styles.timeText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                  editable={false}
                  value={formatted}
                />
              </TouchableOpacity>
            </View>
            <View
              style={{
                flexDirection: viewRTLStyle,
                marginTop: windowHeight(6),
              }}
            >
              {errors.startTime ? (
                <Text
                  style={{
                    color: appColors.textRed,
                    fontSize: fontSizes.FONT14SMALL,
                  }}
                >
                  {errors.startTime}
                </Text>
              ) : (
                ""
              )}
              {errors.startDate ? (
                <Text
                  style={{
                    color: appColors.textRed,
                    fontSize: fontSizes.FONT14SMALL,
                    paddingHorizontal: "35%",
                  }}
                >
                  {errors.startDate}
                </Text>
              ) : (
                ""
              )}
            </View>
            <Text
              style={[
                styles.datetimeText,
                { textAlign: textRTLStyle },
                { color: textColorStyle },
                { marginTop: windowHeight(18) },
              ]}
            >
              {translateData.endTimedate}
            </Text>

            <View
              style={{
                flexDirection: viewRTLStyle,
                justifyContent: "space-between",
              }}
            >
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => {
                  if (!startDate) {
                    notificationHelper(
                      "",
                      translateData?.selectplease,
                      "error"
                    );
                    return;
                  }
                  gotoCalander("endTime");
                }}
                style={[
                  styles.clockBtn,
                  { flexDirection: viewRTLStyle },
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.whiteColor,
                  },
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.lightGray,
                  },
                ]}
              >
                <View style={styles.calenderView}>
                  <Clock color={appColors.regularText} />
                </View>
                <TextInput
                  placeholder={translateData.selectTime}
                  placeholderTextColor={
                    isDark ? appColors.darkText : appColors.blackColor
                  }
                  style={[
                    styles.timeText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                  editable={false}
                  value={endTime}
                />
              </TouchableOpacity>
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => {
                  if (!startDate) {
                    notificationHelper(
                      "",
                      translateData?.selectplease,
                      "error"
                    );
                    return;
                  }
                  gotoCalander("endTime");
                }}
                style={[
                  styles.clockBtn,
                  { flexDirection: viewRTLStyle },
                  {
                    backgroundColor: isDark
                      ? appColors.solidBorder
                      : appColors.whiteColor,
                  },
                  {
                    borderColor: isDark
                      ? appColors.darkBorder
                      : appColors.lightGray,
                  },
                ]}
              >
                <View style={styles.paddingHr}>
                  <Calender1 />
                </View>
                <TextInput
                  placeholder={translateData.selectDate}
                  placeholderTextColor={
                    isDark ? appColors.darkText : appColors.blackColor
                  }
                  style={[
                    styles.timeText,
                    {
                      color: isDark
                        ? appColors.whiteColor
                        : appColors.blackColor,
                    },
                  ]}
                  editable={false}
                  value={formattedEndDate}
                />
              </TouchableOpacity>
            </View>
            <View
              style={{
                flexDirection: viewRTLStyle,
                marginTop: windowHeight(6),
              }}
            >
              {errors.startTime ? (
                <Text
                  style={{
                    color: appColors.textRed,
                    fontSize: fontSizes.FONT14SMALL,
                  }}
                >
                  {errors.startTime}
                </Text>
              ) : (
                ""
              )}
              {errors.startDate || errors.invalidRange ? (
                <Text
                  style={{
                    color: appColors.textRed,
                    fontSize: fontSizes.FONT14SMALL,
                    paddingHorizontal: "35%",
                  }}
                >
                  {errors.startDate ? errors.startDate : errors.invalidRange}
                </Text>
              ) : (
                ""
              )}
            </View>
          </View>
          <View
            style={[
              styles.tripMainView,
              { flexDirection: viewRTLStyle },
              { backgroundColor: bgContainer },
              { borderColor: isDark ? appColors.darkBorder : appColors.go },
            ]}
          >
            <View style={styles.tripSubView}>
              <Text
                style={[
                  styles.tripText,
                  { textAlign: textRTLStyle, color: textColorStyle },
                ]}
              >
                {translateData.getDriver}?
              </Text>
              <Text style={[styles.noDriverText, { textAlign: textRTLStyle }]}>
                {translateData.getDriverCar}
              </Text>
            </View>
            <View style={styles.switchView}>
              <SwitchComponent
                Enable={getDriver}
                onPress={handleToggleDriver}
              ></SwitchComponent>
            </View>
          </View>
        </ScrollView>
        <View style={styles.FindView}>
          <Button
            width={"91%"}
            title={translateData.findNow}
            onPress={findCar}
            loading={findLoading}
          />
        </View>
      </View>
    </View>
  );
}
