import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import  * as yup from "yup";
import { Form, FormControl, Row, Col, Button } from "react-bootstrap";
import { getPorts } from "../../../services/dashboard";
import Select from 'react-select';
import { googleAddressActionUrl } from "../../../helpers/projectHelper";
import { useRouter } from "next/router";
import { roundTrip } from "../../../services/public";
import { useSession } from "next-auth/react";
import { toCheckUserTypeSubscreption } from "../../../helpers/toCheckUserType"
import { isValidLocationData } from "@/utils/conditions/ConditionCreateQuotes";
import { processResponseData } from "@/helpers/geolocationParsingUtils";
import { Suggestion } from "@/interfaces/Maps";
import BulkUploadBtn from "./BulkUploadBtn";

type SelectAddressType = {
    name: string;
    city: string;
    zip: number;
    state: string;
};

const RunAnalysis = (props: any) => {
    const { data } = useSession();
    const accessToken = data?.user?.image;
    const Router = useRouter();
    const [togetMarketList, setTogetMarketList] = useState([]);
    const [selectedOption, setSelectedOption] = useState(null);
    const [searchedSuggestions, setSearchSuggestions] = useState<Suggestion[]>([]);
    const [selectedLocationObject, setSelectedLocationObject] = useState({});
    const [selectedOriginDestination, setSelectedOriginDestination] = useState("");
    const [originLat, setOriginLat] = useState("");
    const [originLng, setOriginLng] = useState("");
    const [findErr, setFindErr] = useState({ origin_destination: "", market: "",});
    const [hoveredPlan, setHoveredPlan] = useState(null); 
    useEffect(() => {
      const fetchMarketData = async () => {
        let res = await getPorts();
        setTogetMarketList(res?.data);
        const marketFinalData = res?.data || [];
        let marketArray: any[] = [];

        if (props.marketOptionValue) {
          marketArray = Array.isArray(props.marketOptionValue)
            ? props.marketOptionValue
            : [props.marketOptionValue];
        }
    
        if (marketArray.length > 0 && marketArray[0]?.market) {
          const filteredRateQuoteMarketLocations = marketFinalData.filter(
            (market: any) => market.market === marketArray[0].market
          );

          if (filteredRateQuoteMarketLocations.length > 0) {
            setSelectedOption(filteredRateQuoteMarketLocations);
            setValue("port_id", filteredRateQuoteMarketLocations[0]);
          }
        }else{
          setSelectedOption(null);
          setValue("port_id", '');
          setSelectedOriginDestination("");
          setValue("origin_destination", "");
        }
      };
      fetchMarketData();
    }, [props.marketOptionValue]);

    const { register, handleSubmit, formState, setValue, getValues, setError, clearErrors} =
        useForm({
        resolver: yupResolver(
            yup.object().shape({
            port_id: yup
                .mixed()
                .required("The market value is required.")
                .test("is-object", "The market value is required.", (value) => 
                    value !== null && typeof value === "object"
                ),
            origin_destination: yup.string().required("The origin or destination value is required."),
            }),
        ),
    });
    const { errors } = formState;

    const onSubmit = (formData: any, e: any, navigate: string) => {
        e?.preventDefault();
        const locationData = selectedLocationObject as any;
        if (!isValidLocationData(locationData)) {
          setError("origin_destination", {
            type: "manual",
            message: "The origin or destination value is required.",
          });
          return false;
        }
        let marketId = formData?.port_id?.id;
        let marketLat = formData?.port_id?.lat;
        let marketLng = formData?.port_id?.lng;

        const calculateRoundtripDistance = (lng, lat, formDataLng, formDataLat) => {
            const payload = {
                port_id: marketId,
                lat: formDataLat,
                lng: formDataLng,
            };
        
          return roundTrip(accessToken, payload);
        };
    
        const handleFindRate = async () => {
          if (navigate !== "rate-quotes") return;
          if(originLng && originLat){
            const roundtripDistance = await calculateRoundtripDistance(
              marketLng,
              marketLat,
              originLng,
              originLat,
            );
            let port: any = togetMarketList?.filter(
              (item: any) => item.id == getValues("port_id")?.id,
            )[0];
            const Distance = roundtripDistance?.data?.original_val?.toFixed(2);
            let queryObj = {
              port: `${port?.state_code}-${port?.name}`,
              original_val: Distance,
              max: roundtripDistance?.data?.max,
              min: roundtripDistance?.data?.min,
            };
            Router.push({ pathname: "/rate-quotes", query: queryObj });
          }
        };
        navigationScope(navigate, handleFindRate);
    };

    const filterMarketOption = (option: { data: { market: string; }; }, inputValue: string) => {
        return option.data.market.toLowerCase().includes(inputValue.toLowerCase());
    }

    const portnameFilterChange = (selectedValue: any) => {
        setSelectedOption(selectedValue);
        setValue("port_id", selectedValue);
        if (selectedValue) {
            clearErrors("port_id");
        }
    }

    const handleOriginDestinationChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      setSelectedOriginDestination(e.target.value);
      setValue("origin_destination", e.target.value);
      if (e.target.value) {
          clearErrors("origin_destination");
      }
    };

    async function getAddressSuggestions(event: any) {
        try {
          const searchedString = event.target.value;
          setSelectedLocationObject({});
          if (searchedString.length > 1) {
            const searchResponse = await fetch(
              googleAddressActionUrl(searchedString),
            );
            const searchedResponseData = await searchResponse.json();
            const suggestionsArray=  processResponseData(
              searchedResponseData?.results,
            );
    
            setSearchSuggestions(suggestionsArray);
          } else {
            setSearchSuggestions([]);
          }
        } catch (error) {
          setSearchSuggestions([]);
        }
    }

    function bindSelectedAddress(item: SelectAddressType) {
        const cityName = cityNameOfValue(item.name[0]?.city, item);
        const stateCodeName = stateNameOfValue(item.name[0]?.state, item, cityName);
        const zipCodeNumber = /^[A-Za-z0-9\s]+$/.test(item.name[0]?.zip_code)
          ? item.name[0]?.zip_code
          : "";
        const finalDestinationName = formatDestinationAddress(
          cityName,
          stateCodeName,
          zipCodeNumber,
        );
        setOriginLat(item.lat);
        setOriginLng(item.lng);
        setValue("origin_destination", finalDestinationName);
        formState.errors.origin_destination = undefined;
        setSearchSuggestions([]);
        setSelectedOriginDestination(finalDestinationName);
        setSelectedLocationObject(item);
    }

    function cityNameOfValue(cityValue: any, fullItemValue: any) {
        if (cityValue) {
          return cityValue;
        } else if (
          fullItemValue?.name[0]?.city === "" &&
          fullItemValue?.name[0]?.state === ""
        ) {
          return fullItemValue?.name[0]?.zip_code;
        } else {
          return "";
        }
    }

    function stateNameOfValue(
        stateValue: any,
        fullItemValue: any,
        cityName: any,
      ) {
        if (stateValue) {
          return fullItemValue?.state_code;
        } else {
          if (fullItemValue?.name[0]?.zip_code !== cityName) {
            return fullItemValue?.name[0]?.zip_code;
          } else {
            return "";
          }
        }
    }

    function formatDestinationAddress(
            cityName: any,
            stateCode: any,
            zipCodeNumber: any
        ): string {
        let formattedAddress = cityName || ''; 
        if (stateCode) {
            formattedAddress += `, ${stateCode}`; 
        }
        if (zipCodeNumber) {
            formattedAddress += `, ${zipCodeNumber}`; 
        }
        return formattedAddress;
    }

    function stateNameOriginDestination(item: any) {
        const state_od = item?.name[0]?.state;
        const zip_od = item?.name[0]?.zip;
        let result = "";
        if (state_od) {
          result = state_od;
          if (zip_od) {
            result += `, `; 
          }
        }
        return result;
    }

    function originErrScope2(errors2: any, findErr2: { origin_destination: string; market: string; }): string | undefined {
        return (errors2.origin_destination ||
          findErr2?.origin_destination) &&
          "is-invalid";
    }

    function navigationScope(navigate: string, handleFindRate: () => Promise<void>) {
      if (navigate === "rate-quotes") {
          handleFindRate();
      }
    }

    const handlePlanHover = (userTypeData: any)=>{
      setHoveredPlan(userTypeData);
    }
    
    const handlePlanLeaveEvent = (e: any) => {
      setHoveredPlan(null);
    };

    return (
        <div style={{padding: '10px'}}>
          <Row style={{display: 'flex', justifyContent: 'space-between'}}>
             <Col lg={6} md={12} sm={12}>
                <Form onSubmit={handleSubmit((formdata, event)=>onSubmit(formdata, event, 'rate-quotes'))} autoComplete="off">
                    <Row>
                        <Col md={12}>
                            <div className="d-flex" style={{gap: '20px'}}>
                               <Col md={5}>
                                  <label style={{fontSize: '14px'}}>Select Market <span style={{color:"red"}}>*</span></label>
                                  <div style={{fontWeight: '100', fontSize: '16px'}} id="rateQuoteMarketFilter">
                                  <Select
                                      id="port_id"
                                      placeholder="Select Market"
                                      isClearable={true}
                                      value={selectedOption}
                                      options={togetMarketList}
                                      onChange={portnameFilterChange}
                                      getOptionLabel={e => (
                                          <div style={{ display: 'flex', alignItems: 'center' }}>
                                              <span style={{ marginLeft: 5 }}>{e.market}</span>
                                          </div>
                                      )}
                                      filterOption={filterMarketOption}
                                  />
                                  {errors.port_id && (
                                      <div className="text-danger" style={{ fontSize: "12px" }}>
                                          {errors.port_id.message}
                                      </div>
                                  )}
                                  </div>
                               </Col>
                            
                               <Col md={4}>
                                  <div className="mb-3 address-autocomplete-parent">
                                      <label style={{fontSize: '14px'}}>Origin/Destination <span style={{color:"red"}}>*</span></label>
                                      <FormControl
                                        {...register("origin_destination")}
                                          className={
                                              originErrScope2(errors, findErr)
                                          }
                                          id="origin_destination"
                                          placeholder="Origin/Destination"
                                          autoComplete="off"
                                          onInput={(e) => {
                                              e.preventDefault();
                                              getAddressSuggestions(e);
                                          }}
                                          value={selectedOriginDestination}
                                          onChange={handleOriginDestinationChange}
                                      />
                                      <div className={searchedSuggestions.length < 1 ? "d-none" : ""}>
                                          <ul className="city-listing-css">
                                              {searchedSuggestions?.map((item: any, index: any) => (
                                              <li
                                                  key={index}
                                                  onClick={() => {
                                                  setFindErr((prevErr) => ({
                                                      ...prevErr,
                                                      origin_destination: "",
                                                  }));
                                                  bindSelectedAddress({
                                                      name: [
                                                      {
                                                          name: item?.name[0]?.name,
                                                          city: item?.name[0]?.city,
                                                          zip_code: item?.name[0]?.zip,
                                                          state: item?.name[0]?.state
                                                          ? item?.name[0]?.state
                                                          : "",
                                                      },
                                                      ],
                                                      lat: item.lat,
                                                      lng: item.lng,
                                                      state_code: item.state_code,
                                                      post_code: item.post_code,
                                                  });
                                                  }}
                                              >
                                                  {item?.name[0]?.city ? `${item?.name[0]?.city}, ` : ""}
                                                  {stateNameOriginDestination(item)}
                                                  {item?.name[0]?.zip ? `${item?.name[0]?.zip}` : ""}
                                              </li>
                                              ))}
                                          </ul>
                                      </div>
                                      <Form.Control.Feedback type="invalid" style={{fontSize: '12px', fontWeight: '100'}}>
                                          {errors.origin_destination?.message?.toString()
                                              ? "The origin or destination value is required."
                                              : ""}
                                      </Form.Control.Feedback>
                                      <p className="addVal">
                                          {findErr.origin_destination && (
                                              <p>{findErr.origin_destination}</p> 
                                          )}
                                      </p>
                                  </div>
                                </Col>
                            
                                <Col md={3}>
                                  <div style={{ visibility: 'hidden' }}>
                                    <div>''</div>
                                  </div>
                                  {!toCheckUserTypeSubscreption(data) ? (
                                     <Button type="submit" className="btn btn-danger w-100">
                                        Run Analysis
                                    </Button>
                                  ): (
                                    <>
                                      <Button type="button" className="btn btn-danger w-100" onMouseOver={() => handlePlanHover("common_user")}>
                                        Run Analysis
                                      </Button>
                                      {hoveredPlan === "common_user" && data?.user?.is_child !== 1 && "free" &&
                                        <div onMouseLeave={() => handlePlanLeaveEvent()}>
                                          <div
                                            onMouseLeave={() => handlePlanLeaveEvent()}
                                            style={{ position: "relative" }}
                                            onClick={() => props.SetCheckPlanModalStatus(true)}
                                            x-placement='bottom-start'
                                            aria-labelledby='nav-dropdown'
                                            className='hover-box dropdown-menu show dropdown-menu-light'
                                            data-popper-reference-hidden='false'
                                            data-popper-escaped='false'
                                            data-popper-placement='bottom-start'
                                            
                                            style={{position: 'relative', width: '100%', minWidth: '462px', bottom: '138px'}}
                                          >
                                            <a
                                              data-rr-ui-dropdown-item=''
                                              className='dropdown-item'
                                              role='button'
                                              tabindex='0'
                                              href='#'
                                            >
                                              This feature is only available with the Premium Membership.
                                            </a>
                                          </div>
                                        </div>
                                      } 
                                    </>
                                    )}
                                </Col>
                            </div>
                        </Col>  
                    </Row>
                </Form>
            </Col>
            <BulkUploadBtn 
              disableRateBtn = {!props.selectedQuotes?.length}
              selectedRateOuotesRecords = {props.selectedQuotes}
              SetCheckPlanModalStatus = {props.SetCheckPlanModalStatus}
            />
          </Row>
        </div>
    );
};

export default RunAnalysis;
