import { useState } from "react";
import axios from "axios";
import {API} from "../config";
import "../assets/css/home.css";
import {validZip} from "../constraints/validation";
import {colorCode} from "../constant";
import DistanceDetails from "./distanceDetails";
import { getDistance, getZipCode } from "../services/homeService";
const Home = ()=>{
    const [fromValidPin, setFromValidpin] = useState(undefined);
    const [toValidPin, setToValidpin] = useState(undefined);
    const [tabData,settabData] = useState();
    const [isError,setIsError] = useState();
    const [autoCompleteFrom,setAutoCompleteFrom] = useState();
    const [valueFrom,setValueFrom] = useState();
    const [autoCompleteTo,setAutoCompleteTo] = useState();
    const [valueTo,setValueTo] = useState();
    const checkValidationFrom = async (value)=>{
        settabData("");
        setIsError("");
        let result = validZip(value && value!==null && value.trim());
        setFromValidpin(result);
        let val = value && value!==null && value.trim();
        setValueFrom(val);
        if(result === undefined && val.length>1){
            await getZipCode(val)
            .then(response=>{
                if(response.status === 0){
                    setAutoCompleteFrom("");
                    setIsError(response.message+" for source")
                }
                setAutoCompleteFrom(response.data && response.data.data);
            })
            .catch(error=>{
                setIsError(error.response.data.message)
            })
        }
        else{
            setAutoCompleteFrom("");
        }
    }
    const valueSet = (zip,loc)=>{
        if(loc==="from"){
            setValueFrom(zip);
            setAutoCompleteFrom("");
        }
        else{
            setValueTo(zip);
            setAutoCompleteTo("");
        }
    }
    const checkValidationTo = async (value)=>{
        settabData("");
        setIsError("");
        let result = validZip(value && value!==null && value.trim());
        setToValidpin(result);
        let val = value && value!==null && value.trim();
        setValueTo(val);
        if(result === undefined && val.length>1){
            await getZipCode(val)
            .then(response=>{
                if(response.status === 0){
                    setAutoCompleteTo("");
                    setIsError(response.message+" for destination")
                }
                setAutoCompleteTo(response.data && response.data.data);
            })
            .catch(error=>{
                setIsError(error.response.data.message)
            })
        }
        else{
            setAutoCompleteTo("");
        }
    }
    const onSubmit = async (e) => {
        e.preventDefault();
        setAutoCompleteTo("");
        setAutoCompleteFrom("");
        setIsError("");
        if(fromValidPin === undefined && toValidPin === undefined){
            let data = {
                from: e.target[0] && e.target[0].value && e.target[0].value!==null && e.target[0].value.trim(),
                to: e.target[1] && e.target[1].value && e.target[1].value!==null && e.target[1].value.trim()
            }
            await getDistance(data)
            .then(response=>{
                if(response.status === 0){
                    setIsError(response.message)
                }
                settabData(response.data && response.data.data);
            })
            .catch(error=>{
                setIsError(error.response.data.message)
            })
        }
    };
    return(
        <>
            <div className="container mt-3">
                <form className="row fromcontainer p-4" onSubmit={onSubmit}>
                    <div className="col-md-5 inputBox">
                        <label htmlFor="formPin" className="form-label">Source</label>
                        <input type="text" 
                        style={{borderColor: fromValidPin ? colorCode.inValidColor : colorCode.validColor}}
                        className="form-control" 
                        autoComplete="off"
                        id="formPin" 
                        value={valueFrom}
                        placeholder="Enter Zip Code" 
                        name="formPin"
                        onChange={(e)=>checkValidationFrom(e.target.value)}
                        />
                        {
                            autoCompleteFrom && autoCompleteFrom!==null && autoCompleteFrom.length>0 &&
                            <div className="autoList">
                                {
                                    autoCompleteFrom.map((item,i)=>{
                                        return(
                                            <p key={i} onClick={()=>{valueSet(item.zipCode,"from")}}>{item.zipCode}</p>
                                        )
                                    })
                                }
                            </div>
                        }
                        {fromValidPin && <p className="errMsg">{fromValidPin}</p>}
                    </div>
                    <div className="col-md-5 inputBox">
                        <label htmlFor="toPin" className="form-label">Destination</label>
                        <input type="text" 
                        style={{borderColor: toValidPin ? colorCode.inValidColor : colorCode.validColor}}
                        className="form-control" 
                        id="toPin" 
                        autoComplete="off"
                        value={valueTo}
                        placeholder="Enter Zip Code" 
                        name="toPin"
                        onChange={(e)=>checkValidationTo(e.target.value)}
                        />
                        {
                            autoCompleteTo && autoCompleteTo!==null && autoCompleteTo.length>0 &&
                            <div className="autoList">
                                {
                                    autoCompleteTo.map((item,i)=>{
                                        return(
                                            <p key={i} onClick={()=>{valueSet(item.zipCode,"to")}}>{item.zipCode}</p>
                                        )
                                    })
                                }
                            </div>
                        }
                        {setToValidpin && <p className="errMsg">{toValidPin}</p>}
                    </div>
                    <div className="col-md-2 mt-4 pt-2">
                        <button type="submit" className="btn btn-success w-100">Get Distance</button>
                    </div>
                </form>
            </div>
            {
                isError && 
                <div className="container">
                    <div className="row">
                        <div className="col-md-12 mt-3">
                            <div className="errorMsg">
                                <strong>{isError}</strong>
                            </div>
                        </div>
                    </div>
                </div>
                
            }
            {
                tabData &&  
                <div className="container mt-3">
                    <div className="row d-flex justify-content-center">
                        <div className="col-md-12">
                            <DistanceDetails data={tabData} from={valueFrom} to={valueTo}/>
                        </div>
                    </div>
                </div>
            }
            
        </>
    )
}

export default Home;