import { AutoComplete, Button, DatePicker, Input, notification } from "antd";
import { FC, useEffect, useState } from "react";
import { capitalizeWords } from "../../../constants/commonFunction";
import styles from "./rfqList.module.scss";
import cx from "classnames";
import * as RFQAPI from "../../../pages/api/rfq";
import * as GallaryApi from "../../../pages/api/gallaries";
import { useMediaQuery } from "react-responsive";
import moment from "moment";
import "moment/locale/zh-cn";
import type { DatePickerProps } from "antd";
import * as XLSX from "xlsx";
import {
  UploadOutlined,
  PlusCircleFilled,
  MinusCircleFilled,
  SearchOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import uomData from "../../../mockData/uomData";

const EditRfq: FC<any> = ({ backOption, rfqData, loginRes }) => {
  const isMobile = useMediaQuery({ maxWidth: 767.68 });
  const today = new Date().toISOString().split("T")[0];
  const [qty, setQty] = useState(0);

  const [brandArray, setBrandArray] = useState([]);
  const [ownCard, setOwnCard] = useState(rfqData?.items);
  const [uomOptions, setUomOptions] = useState<
    { value: string; label: string }[]
  >([]);
  const [options, setOptions] = useState<{ value: string; label: string }[]>(
    []
  );

  const renderItem = (title: string, text: string) => ({
    value: capitalizeWords(title),
    label: <div>{capitalizeWords(title)}</div>,
  });

  useEffect(() => {
    const uom_array: any = [];
    uomData.forEach((element: any) => {
      // console.log(element,"element")
      uom_array.push(renderItem(element, element));
    });
    setUomOptions(uom_array);
    const array_strng: any = [];
    GallaryApi.brandApi().then((res) => {
      if (res) setBrandArray(res);
      array_strng.push(renderItem("No Brand", "No Brand"));
      res?.forEach((element: any) => {
        // console.log(element,"element")
        array_strng.push(renderItem(element.brand_name, element.brand_name));
      });
      setOptions(array_strng);
    });
  }, []);
  const updateQuantity = (data: any) => {
    if (data.name == "" || data.name == undefined) {
      notification.warning({ message: "Please Enter Item Name" });
    } else if (data.brand == "") {
      notification.warning({ message: "Please Select  Brand" });
    } else if (data.quantity == "") {
      notification.warning({ message: "Please Enter  Expected Quanity" });
    } else {
      const params = {
        id: data.id,
        name: data.name,
        brand: data.brand,
        specifications: data.specifications,
        quantity: data?.quantity,
        delivery_date: data?.delivery_date,
      };
      // return;
      RFQAPI.updateRfq(params, data.id, loginRes?.token).then((res) => {
        // console.log(res,"res")
        notification.success({ message: res?.message });
        // setOwnCard([]);
        // backOption();
      });
    }
  };
  const onChange = (date: any, dateString: any, idx: number) => {
    const params = {
      target: {
        value: dateString,
        name: "delivery_date",
      },
    };
    handleInputChange(params, idx, "");
  };

  function handleInputChange(event: any, index: number, val: any) {
    // return;
    if (event?.fileList) {
      const list: any = [...ownCard];
      list[index]["item_image"] = event.fileList;
      setOwnCard(list);
    } else if (!event?.target) {
      const list: any = [...ownCard];
      list[index]["brand"] = event;
      setOwnCard(list);
    } else {
      const { name, value } = event.target;
      const list: any = [...ownCard];
      list[index][name] = value;
      setOwnCard(list);
    }
  }

  const excelExport = (data: any) => {
    const Heading = [
      [
        "Customer Name:",
        loginRes?.data?.first_name + " " + loginRes?.data?.last_name,
      ],
      ["Phone Number:", loginRes?.data?.phone],
      ["Email:", loginRes?.data?.email],
      [], // Empty row for spacing
      [
        "S.no",
        "Product Title",
        "Specifications",
        "Make/Brand",
        "UOM",
        "Qty",
        "Rate/Per unit",
        "Total Value",
      ],
    ];

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet([]);
    XLSX.utils.sheet_add_aoa(ws, Heading);

    const final_result = [];
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      const total = element.customer_price * element.quantity;
      const result = [
        index + 1,
        element.name,
        element.specifications,
        element.brand,
        element.uom,
        element.quantity,
        element.customer_price,
        total,
      ];
      final_result.push(result);
    }

    XLSX.utils.sheet_add_json(ws, final_result, {
      origin: "A7",
      skipHeader: true,
    }); // Start from row 7 after customer info

    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    var name_date = new Date().toString().slice(4, 15).replace(/ /g, "_");
    XLSX.writeFile(wb, `RequestForQuote_${name_date}.xlsx`);
    return;

    // let Heading = [['S.no', 'Product Title', 'Specifications', "Make/Brand", "UOM", "Qty", "Rate/Per unit", "Total Value"]];
    // const wb = XLSX.utils.book_new();
    // const ws: XLSX.WorkSheet = XLSX.utils.json_to_sheet([]);
    // XLSX.utils.sheet_add_aoa(ws, Heading);

    //let buffer = XLSX.write(workbook, { bookType: "xlsx", type: "buffer" });
    //XLSX.write(workbook, { bookType: "xlsx", type: "binary" });
    // const final_result = [];
    for (let index = 0; index < data.length; index++) {
      const element = data[index];
      const total = element.customer_price * element.quantity;
      const result = [
        index + 1,
        element.name,
        element.specifications,
        element.brand,
        element.uom,
        element.quantity,
        element.customer_price,
        total,
      ];
      final_result.push(result);
    }

    XLSX.utils.sheet_add_json(ws, final_result, {
      origin: "A2",
      skipHeader: true,
    });

    XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
    var name_date = new Date().toString().slice(4, 15).replace(/ /g, "_");
    XLSX.writeFile(wb, `RequesforQuote_${name_date}.xlsx`);
  };

  const cardDetails = () => {
    return (
      <>
        {rfqData?.items?.map((rfq: any, idx: number) => {
          // console.log(moment(rfq?.delivery_date, 'DD-MM-YYYY', true), "rfq?.delivery_date")
          return (
            <div key={idx} className={styles.tableData}>
              <div
                style={{
                  padding: "0.5rem 0",
                  marginLeft: isMobile ? 0 : "-6px",
                  width: isMobile ? "100%" : "3rem",
                  display: isMobile ? "none" : "block",
                  fontSize: "12px",
                }}
              >
                {isMobile ? <span className={styles.label}>Id : </span> : null}
                {rfq?.id}
              </div>
              {isMobile && (
                <div style={{ textAlign: "start" }}>
                  Item Name / Item Code<span style={{ color: "red" }}>*</span>
                </div>
              )}
              <div style={{ display: "flex" }}>
                <input
                  name="name"
                  placeholder="Enter Item Name"
                  type="text"
                  value={rfq?.name}
                  onChange={(e) => handleInputChange(e, idx, "")}
                  className={styles.textInput}
                  readOnly={rfqData?.status == "Quotation Generated"}
                />
              </div>
              {isMobile && (
                <div style={{ textAlign: "start" }}>
                  Specification / Description / URL
                </div>
              )}
              <div style={{ display: "flex" }}>
                <input
                  name="specifications"
                  placeholder="Enter Specification"
                  type="text"
                  value={rfq?.specifications}
                  onChange={(e) => handleInputChange(e, idx, "")}
                  className={styles.textInput}
                  readOnly={rfqData?.status == "Quotation Generated"}
                />
              </div>
              {isMobile && (
                <div style={{ textAlign: "start" }}>
                  Brand<span style={{ color: "red" }}>*</span>
                </div>
              )}
              <div style={{ display: "flex" }}>
                <AutoComplete
                  disabled={rfqData?.status == "Quotation Generated"}
                  style={{ padding: isMobile ? 0 : "3px" }}
                  className={styles.fileContainer}
                  filterOption={(inputValue, option) =>
                    option!.value
                      .toUpperCase()
                      .indexOf(inputValue.toUpperCase()) !== -1
                  }
                  value={rfq?.brand}
                  defaultValue={rfq?.brand}
                  onChange={(e) => handleInputChange(e, idx, "brand")}
                  placeholder=" Enter Brand"
                  options={options}
                >
                  <Input
                    className={styles.textInput}
                    //placeholder="Enter Brand"
                    suffix={<SearchOutlined />}
                    readOnly={rfqData?.status == "Quotation Generated"}
                  />
                </AutoComplete>
              </div>
              {isMobile && (
                <div style={{ textAlign: "start" }}>
                  UOM<span style={{ color: "red" }}>*</span>
                </div>
              )}
              <div
                style={{
                  display: "flex",
                  alignItems: isMobile ? "flex-start" : "flex-start",
                  justifyContent: isMobile ? "flex-start" : "center",
                  border: isMobile ? "1px solid #ccc" : "1px solid #ccc",
                  padding: "8px",
                  width: isMobile ? "100%" : "160px",
                  height: "38px",
                  marginLeft: "2px",
                  borderRadius: "6px",
                }}
              >
                {rfq?.uom}
              </div>
              {isMobile && (
                <div style={{ textAlign: "start" }}>
                  Quantity<span style={{ color: "red" }}>*</span>
                </div>
              )}
              <div style={{ display: "flex" }}>
                <input
                  name="quantity"
                  placeholder="Enter Qty"
                  type="number"
                  value={rfq?.quantity}
                  onChange={(e) => handleInputChange(e, idx, "")}
                  className={cx(styles.textInput, "numberInput")}
                  readOnly={rfqData?.status == "Quotation Generated"}
                />
              </div>
              {isMobile && (
                <div style={{ textAlign: "start" }}>Delivery Date</div>
              )}
              <div style={{ display: "flex" }}>
                <input
                  readOnly={rfqData?.status == "Quotation Generated"}
                  type="date"
                  value={
                    rfq?.delivery_date == ""
                      ? moment().format("DD-MM-YYYY")
                      : moment(rfq?.delivery_date, "DD-MM-YYYY", true).format(
                          "YYYY-MM-DD"
                        )
                  }
                  style={{
                    border: "1px solid #cccc",
                    height: "38px",
                    width: "100%",
                    borderRadius: "6px",
                  }}
                  onChange={(e) => {
                    const dateValue = moment(e.target.value).format(
                      "DD-MM-YYYY"
                    ); // Access the selected date
                    onChange(e, dateValue, idx); // Pass it to your handler
                  }}
                  min={today}
                />
                {/* <DatePicker onChange={(date, dateString) => onChange(date, dateString, idx)} defaultValue={rfq?.delivery_date==""?moment():moment(rfq?.delivery_date)} value={rfq?.delivery_date==""?moment():moment(rfq?.delivery_date)} name="delivery_date" showToday={true}  disabledDate={d => !d
                                || d.isBefore(new Date())}

                            />  */}
              </div>
              {rfqData?.status == "Quotation Generated" ? null : (
                <Button
                  type="primary"
                  ghost
                  onClick={() => {
                    updateQuantity(rfq);
                  }}
                >
                  Update
                </Button>
              )}
            </div>
          );
        })}
      </>
    );
  };
  return (
    <>
      <div className={styles.container}>
        <div className="flex justify-between">
          <Button type="primary" onClick={() => excelExport(rfqData?.items)}>
            Export Excel
          </Button>
          <h1 className={styles.title}>RFQ Edit</h1>

          <Button type="primary" ghost onClick={backOption}>
            Back
          </Button>
        </div>
        <div className="ant-row my-4">
          <div className="ant-col ant-col-xs-24 ant-col-md-12 ant-col-xl-12">
            <div className={styles.labelDiv}>Representative Name</div>
            <div className={styles.valueDiv}>
              {rfqData?.representative_name}
            </div>
          </div>
          <div className="ant-col ant-col-xs-24 ant-col-md-12 ant-col-xl-12">
            <div className={styles.labelDiv}>Representative Phone</div>
            <div className={styles.valueDiv}>
              {rfqData?.representative_contact_number}
            </div>
          </div>
        </div>
        <table>
          <tr className={styles.tableRow}>
            <th>Id</th>
            <th style={{ width: "160px" }}>
              Item Name <span style={{ color: "red" }}>*</span>
            </th>
            <th style={{ width: "160px" }}>Specification</th>
            <th style={{ width: "160px" }}>
              Brand <span style={{ color: "red" }}>*</span>
            </th>
            <th style={{ width: "160px" }}>
              UOM <span style={{ color: "red" }}>*</span>
            </th>
            <th style={{ width: "160px" }}>
              Quantity <span style={{ color: "red" }}>*</span>
            </th>
            <th style={{ width: "160px" }}>Delivery Date</th>
            {/* <th style={{ width: "180px" }}>Price</th> */}
          </tr>
        </table>
        {cardDetails()}
      </div>
    </>
  );
};

export default EditRfq;
