import { FC, useContext, useEffect, useState } from "react";
import Footer from "../../components/home/footer/Footer";
import InternalPageHeader from "../../components/internalPageHeader/InternalPageHeader";
import styles from "./customerSupport.module.scss";
import * as CategoryAPI from "../api/category";
import { Button, Checkbox, Image, Modal, notification, Radio, Select, Skeleton, Steps } from "antd";
import cx from "classnames";
import Router, { useRouter } from "next/router";
import _ from "lodash";
import OTPModal from "../../components/modal/otpModal/OTPModal";
import * as OrderApi from "../api/getOrders";
import * as CommonApi from "../api/common";
import moment from "moment";
import type { CheckboxChangeEvent } from "antd/es/checkbox";
import type { CheckboxValueType } from "antd/es/checkbox/Group";
import type { RadioChangeEvent } from "antd";
import { CheckCircleFilled } from "@ant-design/icons";
import shopConetxt from "../../context/shopConetxt";
import Loading from "../../components/Loading";
import { baseUrl, s3BucketUrl } from "../../constants/urls";


const { Step } = Steps;
const { Option } = Select;
const steps = [
  {
    id: 1,
    title: "Choose an order you have a problem with it?",
    complete: false,
    formData: null,
  },
  {
    id: 2,
    title: "Select one or more items related to your issue.",
    complete: false,
    formData: null,
  },
  {
    id: 3,
    title: "Describe your problem in more detail.",
    complete: false,
    formData: null,
  },
  {
    id: 4,
    title: "Request for a Call back",
    complete: false,
    formData: null,
  },
];
const languageOptions = [
  { label: "Telugu", value: "Telugu", checked: false },
  { label: "English", value: "English", checked: false },
  { label: "Hindi", value: "Hindi", checked: false },
];
const CustomerOrder: FC<any> = () => {
  const {
    isProductListLoading
  } = useContext(shopConetxt);
  const [state, setState] = useState({
    isRouteChanging: false,
    loadingKey: 0,
  });
  const [current, setCurrent] = useState(0);
  const [category, setCategory] = useState([]);
  const [categoryTree, setCategoryTree] = useState([]);
  const [loginRes, setLoginRes] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [orderData, setOrderData] = useState<any>([]);
  const [orderDetails, setOrderDetails] = useState<any>({});
  const [orderId, setOrderId] = useState("");
  const [itemId, setItemId] = useState("");
  const [concern, setConcern] = useState("");
  const [subConcern, setSubConcern] = useState("");
  const [callingSuccess, setCallingSuccess] = useState(false);
  const [concernReason, setConcernReason] = useState([]);
  const [subConcernReason, setSubConcernReason] = useState([]);
  const [selectLanguage, setSelectLanguage] = useState("");
  const router = useRouter();
  const [stateArray,setStateArray] = useState([]);
  const handleRouteChangeStart = () => {
    setState((prevState) => ({
      ...prevState,
      isRouteChanging: true,
      loadingKey: prevState.loadingKey ^ 1,
    }));
  };
  const handleRouteChangeEnd = () => {
    setState((prevState) => ({
      ...prevState,
      isRouteChanging: false,
    }));
  };

  useEffect(() => {
    handleRouteChangeStart()
    CategoryAPI.fetchCategory().then((res) => {
      setCategory(res);
    });
    CategoryAPI.fetchCategoryTree().then((res) => {
      setCategoryTree(res.categories);
    });
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    setLoginRes(details);
   

    const params = {
      status: "",
      token: details?.token,
    };
    OrderApi.getOrders(params).then((res) => {
      handleRouteChangeEnd()
      setOrderData(res.data);
    });
    CommonApi.getRequest(`${baseUrl}/api/concerns`).then((concern)=>{
  
      setConcernReason(concern?.data?.data)
      
    })
    CommonApi.getRequest(`${baseUrl}/api/indian-states`).then((res)=>{
      setStateArray(res?.data)
    })
    
  }, []);

  const onChange = (value: number) => {
    console.log("onChange:", current);
    setCurrent(value);
  };
  const detailsOrder = (details: any) => {
    setOrderId(details.id);
    const params = {
      id: details.id,
      token: loginRes?.token,
    };
    OrderApi.getOrdersById(params).then((res) => {
      setOrderDetails(res.data);
      setCurrent(current + 1);
    });
  };

  const selectReason =(reason:any)=>{
    console.log(reason);
    if(reason){
    CommonApi.getRequest(`${baseUrl}/api/subconcerns/${reason}`).then((subConcern)=>{
  
      setSubConcernReason(subConcern?.data?.data)
      
    })
  }
  }

  const itemDetails = (item: any) => {
    setItemId(item.id);
    setCurrent(current + 1);
  };
  const languageSelect = (e: RadioChangeEvent) => {
    console.log("checked = ", e.target.value);
    setSelectLanguage(e.target.value);
  };
  const back =()=>{
    if(current!==0){
      
    setCurrent(current-1);
    }
  }
  const submitCallback =()=>{
    if(selectLanguage=="" || !selectLanguage){
      notification.error({message:"Please Slect Language"});
    }else{
    const params={
      orderId:orderId,
      itemId:itemId,
      order_id: orderId,
      product_id: itemId,
      concern_id: concern,
      subconcern_id: subConcern,
      language: selectLanguage
    }
    CommonApi.postRequestWithToken(`${baseUrl}/api/concerns/submit?token=true`,params, loginRes?.token).then((res)=>{
      // console.log(res,"res");
      setCallingSuccess(true)
    })
    
  }
  }
  return (
    <>
    <Loading isRouteChanging={state.isRouteChanging} key={state.loadingKey} />
      <InternalPageHeader catagories={category} categoryTree={categoryTree} stateArray={stateArray}/>
      <div className="container">
       {current!==0?<div><Button style={{color:"#291C61",margin:"1rem auto"}} onClick={back}>Back</Button></div>:null}
        <Steps current={current} className={"stepsMain"}>
          {steps.map((item) => (
            <Step
              key={item.id}
              title={item.title}
              className={styles.stepValue}
            />
          ))}
        </Steps>
       
        {current === 0 ? (
          <div>
            {orderData.length > 0
              ? orderData.map((order: any, idx: number) => {
                  return (
                    <div className={cx()} key={idx}>
                      <div className="ant-row">
                        <div className="ant-col ant-col-xs-8 ant-col-xl-5 p-4">
                        
                      <Checkbox
                        onChange={() => {
                          detailsOrder(order);
                        }}
                        className={styles.checkBoxContainer}
                      >
                        Select this order
                      </Checkbox>
                        </div>
                      <div className={cx("ant-col ant-col-xs-16 ant-col-xl-19",styles.tabPaneContainer)}>
                      <div className={cx("ant-row p-4")}>
                        <span
                          className={cx(
                            "ant-col-xl-1 ant-col-xs-0",
                            styles.subDetails
                          )}
                        >
                          Order{" "}
                        </span>
                        <span className={cx("ant-col-xl-5 ant-col-xs-0 pl-2")}>
                          {moment(order?.created_at).format("DD-MM-YYYY")}
                        </span>
                        <span
                          className={cx(
                            "ant-col-xl-1 ant-col-xs-12",
                            styles.subDetails
                          )}
                        >
                          Total
                        </span>
                        <span className={cx("ant-col-xl-4 ant-col-xs-12")}>
                          {order?.formated_grand_total}
                        </span>

                        <div className={cx("ant-col-xl-8 ant-col-xl-24")} />
                        <Button
                          type="primary"
                          className={cx(
                            "ant-col-xl-5 ant-col-xl-24",
                            styles.primaryButtonStyle
                          )}
                          onClick={() => {
                            detailsOrder(order);
                          }}
                        >
                          Order Details
                        </Button>
                      </div>
                      <hr />

                      <div className="ant-row mb-5 p-4">
                        <div className="ant-col-24">
                          <h2 className="mb-3">Delivery as on </h2>
                        </div>
                        <div className="ant-col-xl-16 ant-col-xs-24 pr-4">
                          {order?.items.map((item: any, index: number) => {
                            return (
                              <div className="ant-row mb-4 " key={index}>
                                <div className="ant-col-xs-8 ant-col-sm-8 ant-col-xl-6 ">
                                  <Image
                                   preview={false}
                                    src={ s3BucketUrl+ item?.product?.base_image?.path}
                                    width="93px"
                                    height="93px"
                                  />
                                </div>
                                <div className="ant-col-xs-16 ant-col-sm-16 ant-col-xl-12">
                                  <div className="ant-row">
                                    <h3>{item?.product?.name}</h3>
                                  </div>
                                  <div className="ant-row">
                                    <span
                                      className={cx(
                                        "ant-col ant-col-xs-0  ant-col-md-2  "
                                      )}
                                    >
                                      By
                                    </span>
                                    <span
                                      className={cx(
                                        "ant-col ant-col-xs-0  ant-col-md-10 "
                                      )}
                                    >
                                      {item?.product?.company}
                                    </span>
                                    <span
                                      className={cx("ant-col ant-col-md-4")}
                                    >
                                      Qty
                                    </span>
                                    <span className={cx("ant-col-md-4")}>
                                      {item?.qty_ordered}
                                    </span>
                                  </div>
                                </div>
                              </div>
                               
                            );
                          })}
                        </div>
                        </div>
                      </div>
                    </div>
                    </div>
                  );
                })
              : <div className="flex" style={{height:"300px"}}>
              <Skeleton active></Skeleton>
             
              </div>}
          </div>
        ) : current === 1 ? (
          <div className={styles.detailsContainer}>
            <div className="ant-row mb-6">
              <div
                className={cx(
                  "ant-col ant-col-xs-24 ant-col-sm-24 ant-col-xl-12 flex",
                  styles.detailsDisplay
                )}
              >
                <span className={styles.subDetails}>
                  Order Placed &nbsp; &nbsp; &nbsp; &nbsp;
                </span>
                <span className={styles.subDetailsValue}>
                  {moment(orderDetails?.created_at).format("DD-MM-YYYY")}
                </span>
              </div>

              <div
                className={cx(
                  "ant-col ant-col-xs-24 ant-col-sm-24 ant-col-xl-12 flex",
                  styles.detailsDisplay
                )}
              >
                <span className={styles.subDetails}>
                  Total Amount &nbsp; &nbsp; &nbsp; &nbsp;
                </span>
                <span className={styles.subDetailsValue}>
                  {orderDetails?.formated_base_grand_total}
                </span>
              </div>
            </div>
            <div className="ant-col-xl-16 ant-col-xs-24">
              {orderDetails?.items.map((data: any, idx: number) => {
                return (
                  <div className="ant-row mb-8" key={idx}>
                    <div className="ant-col-xl-7 ant-col-xs-12">
                      <Checkbox
                        onChange={() => {
                          itemDetails(data);
                        }}
                        className={styles.checkBoxContainer}
                      >
                        Select this product
                      </Checkbox>
                    </div>
                    <div className="ant-col-xl-7 ant-col-xs-12">
                      <Image
                        preview={false}
                        src={ s3BucketUrl+ data?.product?.base_image?.path}
                        width="93px"
                        height="93px"
                      />
                    </div>
                    <div className="ant-col-xl-10">
                      <div className="ant-row">
                        <h3 className={cx(styles.productName)}>
                          {data?.product?.name}
                        </h3>
                      </div>
                      <div className="ant-row">
                        <span>by</span>
                        <span>{data?.product?.company}</span>
                        <span>{data?.product?.qty_ordered}</span>
                      </div>
                      <div className="ant-row">
                        <span className="ant-col-xl-12">
                          ₹{data?.product?.price}{" "}
                        </span>
                      </div>
                    </div>
                  </div>
                  
                );
              })}
            </div>
          </div>
        ) : current === 2 ? (
          <div>
            <div className={cx(styles.problemContainer)}>
              <h2>Select your exact concern</h2>
              <div className="ant-row">
                <div className="ant-col ant-col-xs-24 ant-col-xl-12">
                  <h3>Concern</h3>
                  <Select
                    className={cx(styles.dropdownContainer, "mx-2")}
                    placeholder="Select reason"
                    // value={concern}
                    onChange={(evt) => {
                      setConcern(evt);
                      selectReason(evt);
                    }}
                   
                  >
                    {concernReason.map((con:any,idx:number)=>{
                      return <Option value={con.id} key={idx}>{con.title}</Option>
                    })}
                   
                  </Select>
                </div>
                <div className="ant-col ant-col-xs-24 ant-col-xl-12">
                  <h3>Sub-Concern</h3>
                  <Select
                    className={styles.dropdownContainer}
                    placeholder="Select sub reason"
                    // value={subConcern}
                    onChange={(evt) => {
                      setSubConcern(evt);
                      setCurrent(current + 1);
                    }}
                  >
                    
                    {subConcernReason.map((con:any,idx:number)=>{
                      return <Option value={con.id} key={idx}>{con.title}</Option>
                    })}
                  </Select>
                </div>
              </div>
            </div>
          </div>
        ) : (
          <div>
            <div className={styles.problemContainer}>
              <div className="ant-row">
                <div className="ant-col ant-col-xs-24 ant-col-md-12 ant-col-xl-12">
                  <h2>Language</h2>
                  <Radio.Group
                    onChange={languageSelect}
                    size="large"
                    className={styles.checkboxContainerRadio}
                  >
                    {languageOptions.map((data: any, idx: number) => {
                      return (
                        <Radio value={data.value} key={idx}>
                          {data.label}
                        </Radio>
                      );
                    })}
                  </Radio.Group>
                  <Button
                    type="primary"
                    icon={
                      <Image
                      preview={false}
                        src={"/images/call-white-icon.svg"}
                        alt="call"
                        width={25}
                        height={25}
                      />
                    }
                    className={styles.finalButton}
                    onClick={() => {
                      // setCallingSuccess(true);
                      submitCallback();
                    }}
                  >
                    {" "}
                    Request Call Back
                  </Button>
                </div>
                <div className="ant-col ant-col-xs-24 ant-col-md-12 ant-col-xl-12">
                  <div className="flex item-center justify-center mt-14">
                  <Button className={styles.buttonCustomer}icon={<Image preview={false} src={"/images/Chat-icon.svg"} alt="msg"  width={25} height={25}/>}>Chat with us</Button>
                  </div>
                
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
      <Modal
        width={600}
        style={{ width: "600px" }}
        visible={callingSuccess}
        onOk={() => {
          setCallingSuccess(false);
        }}
        onCancel={() => {
          setCallingSuccess(false);
          router.push({
            pathname: `/home`,
          });
        }}
        footer={null}
        destroyOnClose={true}
      >
        <div className={styles.modalContent}>
          <CheckCircleFilled style={{ color: "#291C61", fontSize: "40px" }} />
          <h1 className={styles.addressCardTitle}>
            Thanks for the call back request!
          </h1>
          <h3 className={styles.addressCardSubTitle}>
            Our executive will call you in 30 Min.
          </h3>
          <h4 className={styles.time}>Working hours - 9am - 5pm only</h4>
        </div>
      </Modal>
      <Footer />
    </>
  );
};

export default CustomerOrder;
