import {
  Modal,
  Image,
  Checkbox,
  Radio,
  Space,
  Input,
  Button,
  RadioChangeEvent,
  Upload,
  Typography,
  notification,
  Spin,
} from "antd";
import { ChangeEvent, FC, useEffect, useState } from "react";
import styles from "./returnOrder.module.scss";
import cx from "classnames";
import Slider from "react-slick";
import { RightOutlined, LeftOutlined, WarningFilled, LoadingOutlined, UploadOutlined } from "@ant-design/icons";
const { Text } = Typography;
import * as OrderApi from "../../../pages/api/getOrders";
const { TextArea } = Input;
import { baseUrl, s3BucketUrl } from "../../../constants/urls";
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import *as CommonApi from "../../../pages/api/common";



const isValidFileType = (file: File) => {
  const acceptedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'video/mp4', 'video/webm', 'video/ogg'];
  return acceptedTypes.includes(file.type);
};

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;
const ReturnOrder: FC<any> = (props) => {
  const [value, setValue] = useState("");
  const [returnButton, setReturnButton] = useState(false);
  const [loginRes, setLoginRes] = useState<any>({});
  const [reason, setReason] = useState("");
  const [loading, setLoading] = useState(false);
  const [fileList, setFileList] =  useState<File[]>([]);
  const [returnReason, setReturnReason] = useState<any>([])
  const cancelOptions = [
    "Duplicate Order",
    "Item damaged",
    "Ordered by mistake",
    " Delayed Delivery Cancellation",
    "Incorrect size ordered",
    " Product not required anymore",
  ];

  const { cancelModal, onCloseCancel, cancelOrderDetails, returnCloseOrderModal } = props;
  const slickSettings = {
    dots: false,
    arrows: true,
    infinite: false,
    nextArrow: <SampleNextArrow />,
    prevArrow: <SamplePrevArrow />,
    speed: 400,
    slidesToShow: 1,
    slidesToScroll: 1,
  };

  function SampleNextArrow(props: any) {
    const { className, style, onClick } = props;
    return (
      <div
        style={{
          ...style,
          display: "block",
          zIndex: "15",
          borderRadius: "50%",
          height: 20,
          width: 20,
          opacity: "1",
          right: 0,
          color: "#fff",
          justifyContent: "center",
        }}
        onClick={onClick}
      >
        {" "}
        <RightOutlined className={styles.iconRightDisplay} />
      </div>
    );
  }

  function SamplePrevArrow(props: any) {
    const { className, style, onClick } = props;
    return (
      <div
        style={{
          ...style,
          display: "block",
          zIndex: "15",
          borderRadius: "50%",
          height: 20,
          width: 20,
          opacity: "1",
          left: 0,
          color: "#fff",
          justifyContent: "center",
        }}
        onClick={onClick}
      >
        <LeftOutlined className={styles.iconLeftDisplay} />
      </div>
    );
  }

  const onChange = (e: RadioChangeEvent) => {
    console.log("radio checked", e.target.value);
    setValue(e.target.value);
  };

  useEffect(() => {
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);

    setLoginRes(details);
    CommonApi.getRequest(`${baseUrl}/api/customisation/product-flag-reasons/return`).then((res) => {

      setReturnReason(res?.data?.reasons)
    })
  }, []);

  const deleteOrder = () => {

    setReturnButton(true);
    setLoading(true);
    if (value == "") {
      notification.warning({ message: "Please Select Reason" });
      setReturnButton(false);
      setLoading(false);
    } else if (fileList.length == 0) {
      notification.warning({ message: "Please Upload Image" })
      setReturnButton(false);
      setLoading(false);
    } else if (reason == "") {
      notification.warning({ message: "Please Enter Descrption" })
      setReturnButton(false);
      setLoading(false);
    } else {
      const params = {
        id: cancelOrderDetails?.id,
        reason: value + "-" + reason,
        image: fileList
      };



      OrderApi.returnOrder(params, cancelOrderDetails?.id, loginRes?.token).then((res) => {
        notification.success({ message: res.message })
        setLoading(false);
        setReturnButton(false);
        onCloseCancel();
      });
    }
  };




  const handleChange = ({ fileList }: any) => {
    setFileList(fileList);
  };


  const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = Array.from(e.target.files || []);

    // Filter out invalid file types
    const validFiles = selectedFiles.filter(isValidFileType);

    // Limit the number of files to 4
    const newFiles:any = [...fileList, ...validFiles].slice(0, 4);

    
    setFileList(newFiles);
  };


  const handleRemoveFile = (index: number) => {
    const newFiles = [...fileList];
    newFiles.splice(index, 1);
    setFileList(newFiles);
  };

  return (
    <>
      <Modal
        visible={cancelModal}
        width={800}
        style={{
          width: "823px",
          height: "100%",
          position: "absolute",
          right: 0,
          top: 0,
        }}
        onOk={returnCloseOrderModal}
        onCancel={returnCloseOrderModal}
        footer={null}
        destroyOnClose={true}
        bodyStyle={{ height: "100%", width: "100%" }}
      >
        <h2 className={styles.title}>
          {" "}
          Are you sure you want to Return this Order?
        </h2>
        <div className={styles.detailsContainer}>
          <div>
            <Slider {...slickSettings} className="py-6">
              {cancelOrderDetails?.items?.map((data: any, idx: number) => {
                return (
                  <div key={idx} className="mr-2">
                    <div className={"p-2"}>
                      <div className={styles.itemContainer}>
                        <Image
                          src={s3BucketUrl + data?.product?.base_image?.path}
                          className={styles.image}
                          preview={false}
                        />
                        <div className={styles.contentContainer}>
                          <h3 className={cx(styles.productName)}>
                            {data?.product?.name}
                          </h3>
                          <div className="ant-row">
                            <span className="ant-col-xl-12">
                              ₹{data?.product?.price}{" "}
                            </span>
                          </div>
                          <div className="ant-row">
                            <span>by</span>
                            <span>
                              {
                                data?.additional
                                  ?.seller_code
                              }
                            </span>
                            <span>{data?.product?.qty_ordered}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </Slider>
          </div>
          <div className={cx("ant-col-sm-24 ant-col-xl-8")}>
            <div className={cx(styles.billContainer, "ant-row")}>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                Sub Total
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                {cancelOrderDetails?.formated_base_sub_total}
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                Discount
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                {cancelOrderDetails?.formated_base_discount_amount}
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                Taxable Amount
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                {cancelOrderDetails?.formated_base_tax_amount}
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12">
                Total
              </div>
              <div className="ant-col-xs-12 ant-col-sm-12 ant-col-xl-12 fs-6">
                {cancelOrderDetails?.formated_grand_total}
              </div>
            </div>
          </div>
          <div className={styles.returnWarning}>
            <WarningFilled style={{ color: "#f00", paddingRight: "0.5rem" }} />
            Important Note: By Returning this order, all the Items for this
            order will be returnes.
          </div>
          <h3>Reason for Returning <span style={{ color: "#f00", fontSize: "20px", marginTop: "2px" }} >*</span></h3>
          <Radio.Group onChange={onChange} value={value}>
            <Space direction="vertical" className="mt-5">
              {returnReason.map((data: any) => {
                return (
                  <Radio key={data} value={data}>
                    {data}
                  </Radio>
                );
              })}
            </Space>
          </Radio.Group>
          <h3 style={{marginTop:"20px"}}>List of Ineligible for Return <span style={{ color: "#f00", fontSize: "20px", marginTop: "2px" }} ></span></h3>
          <ul style={{listStyleType:"disc"}} className="mb-5 ml-4">
          <li>Products that are no longer needed</li>
          <li>Attempts to use industrial products that result in damage</li>
          <li>Made-to-order (on-demand) items</li>
          </ul>
          <div className="my-8">
            <h3>Upload Image <span style={{ color: "#f00", fontSize: "20px", marginTop: "2px",marginBottom:"1em" }} >*</span></h3>
            {/* <Upload
                listType="picture-card"
                fileList={fileList}
                onChange={handleChange}
                maxCount={3}
                accept=".jpg,.jpeg,.png,.gif,.bmp" // Specify accepted file extensions
                beforeUpload={checkImageType}
            >
              {fileList.length < 3 ? (
                <Button type="primary" ghost>
                  Add Photo
                </Button>
              ) : null}
            </Upload> */}
            <label className={styles.imageData}>
              <UploadOutlined />
              Upload Images/Video
              <input
                type="file"
                style={{ display: "none" }}
                multiple
                accept="image/*,video/*"
                onChange={handleFileChange}
              />
            </label>

            <div style={{marginTop:"20px"}}>
            {fileList.map((file, index) => (
          <div key={index} >
            <span>{file.name}</span>
            <button onClick={() => handleRemoveFile(index)} style={{marginLeft:"15px", fontSize: "20px",color: "#f00",cursor:"pointer"}}>Remove</button>
          </div>
        ))}
        </div>
          </div>
          <h3>Descrption  <span style={{ color: "#f00", fontSize: "20px", marginTop: "2px" }} >*</span></h3>
          <TextArea
            rows={4}
            placeholder="Enter Reason"
            value={reason}
            onChange={(e) => setReason(e.target.value)}
          />

          <div className="my-5">
            <Button type="primary" ghost className="my-2 ml-2" block onClick={returnCloseOrderModal}>
              No, I don't want to Return
            </Button>
            <Button
              disabled={returnButton}
              type="primary"
              className="my-2 ml-2"
              block
              onClick={deleteOrder}
            >
              Yes, Return my Order
            </Button>
          </div>
        </div>
        <Spin indicator={antIcon} spinning={loading} className={styles.loaderContainer} />
      </Modal>
    </>
  );
};

export default ReturnOrder;
