import React, { useContext, useEffect, useState } from "react";
import Select from "react-select";
import { ConfigContext } from "../../Context/ConfigContext";
import axios from "axios";
import { useParams } from "react-router-dom";
import Swal from "sweetalert2";
import { ContentLoader, NoRecords } from "../../Components/Shimmer";
import { DateFormaterMonth } from "../GlobalFunctions";

const AddItems = () => {
  const { apiURL, apiHeaderJson } = useContext(ConfigContext);

  const [itemID, setItemID] = useState(null);
  const [itemsData, setItemsData] = useState([]);
  const [categoryID, setCategoryID] = useState(null);
  const [categoryData, setCategoryData] = useState([]);
  const [deliveryDate, setDeliveryDate] = useState(null);
  const [itemQuantity, setItemQuantity] = useState(null);
  const [loadingList, setloadingList] = useState(true);
  const [itemPrice, setItemPrice] = useState(null);
  const [projectselectedItems, setProjectselectedItems] = useState([]);
  const [isVariationMode, setIsVariationMode] = useState(false);

  const [editProjectItemId, setEditProjectItemId] = useState(null);
  const [isEditMode, setIsEditMode] = useState(false);

  const { projectId } = useParams();

  const getItemsList = async () => {
    try {
      const response = await axios.get(`${apiURL}api/items`);
      const { data, success } = response.data;

      if (success) {
        setItemsData(
          data.map((row) => ({
            value: row.item_id,
            label: row.item_name,
          }))
        );
      } else {
        setItemsData([]);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const getItemCategories = async () => {
    try {
      const headers = apiHeaderJson;
      const response = await axios.get(
        `${apiURL}api/items/categories/categories`,
        { headers }
      );
      const { data, success } = response.data;

      if (success) {
        setCategoryData(
          data.map((row) => ({
            value: row.item_category_id,
            label: row.item_category_name,
          }))
        );
      } else {
        setCategoryData([]);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const getProjectItemList = async () => {
    try {
      setloadingList(true);
      const response = await axios.get(`${apiURL}api/requests/GetProjectItems`, {
        params: { project_id: projectId },
      });

      const { data, success } = response.data;

      if (success) {
        setProjectselectedItems(data || []);
      } else {
        setProjectselectedItems([]);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setloadingList(false);
    }
  };

  const resetForm = () => {
    setItemID(null);
    setCategoryID(null);
    setItemPrice("");
    setItemQuantity("");
    setDeliveryDate(null);
    setEditProjectItemId(null);
    setIsEditMode(false);
    setIsVariationMode(false);
  };

  const handleSelect = (selectedOption) => {
    setItemID(selectedOption ? selectedOption.value : null);
  };

  const getProjectItemDetails = async (project_item_id) => {
    try {
      const headers = apiHeaderJson;

      const response = await axios.get(
        `${apiURL}api/requests/GetProjectItemDetails`,
        {
          params: { project_item_id },
          headers,
        }
      );

      const { success, data, message } = response.data;

      if (!success) {
        Swal.fire({
          icon: "error",
          title: "Failed",
          text: message || "Unable to fetch item details",
        });
        return;
      }

      const fields = Array.isArray(data) ? data?.[0] : data;

      setEditProjectItemId(project_item_id);
      setIsEditMode(true);

      setItemID(fields?.item_id ? Number(fields?.item_id) : null);
      setCategoryID(
        fields?.item_category_id ? Number(fields?.item_category_id) : null
      );
      setItemPrice(fields?.pi_item_price ?? "");
      setItemQuantity(fields?.pi_item_qty ?? "");
      setDeliveryDate(fields?.pi_item_delivery_date ?? null);
    } catch (error) {
      console.log(error);
      Swal.fire({
        icon: "error",
        title: "Error",
        text: error?.message || "Something went wrong",
      });
    }
  };

  const handleSubmitItems = async (e) => {
    e.preventDefault();

    if (!itemQuantity) return;

    if (!isVariationMode) {
      if (!itemID || !categoryID || !itemPrice) return;
    }

    if (!isEditMode && !isVariationMode) {
      const isDuplicateItem = projectselectedItems.some(
        (item) => Number(item.item_id) === Number(itemID)
      );

      if (isDuplicateItem) {
        Swal.fire({
          icon: "warning",
          title: "Duplicate Item",
          text: "This item is already added to the project.",
        });
        return;
      }
    }

    try {
      const headers = apiHeaderJson;

      let finalQty = Number(itemQuantity);

      if (isEditMode || isVariationMode) {
        const currentItem = projectselectedItems.find(
          (item) =>
            Number(item.project_item_id) === Number(editProjectItemId)
        );

        const existingQty = Number(currentItem?.pi_item_qty || 0);

        finalQty = existingQty + Number(itemQuantity);
      }

      const Body = {
        project_id: projectId,
        item_id: itemID,
        item_category_id: categoryID,
        item_price: itemPrice,
        item_qty: finalQty,
        pi_item_delivery_date: deliveryDate,
      };

      if (isEditMode || isVariationMode) {
        Body.project_item_id = editProjectItemId;
      }

      const response = await axios.post(
        `${apiURL}api/requests/AddProjectItem`,
        Body,
        { headers }
      );

      const { success, message } = response.data;

      Swal.fire({
        title: `<strong>${success ? "Success" : "Failed"}</strong>`,
        text: message,
        icon: success ? "success" : "error",
        timer: 1200,
        timerProgressBar: true,
        showConfirmButton: false,
      });

      if (success) {
        document.getElementById("itemModal")?.click();
        resetForm();
        getProjectItemList();
      }
    } catch (error) {
      console.log(error);

      Swal.fire({
        icon: "error",
        title: "Error",
        text: error?.message || "Something went wrong",
      });
    }
  };

  const handleDelete = (id) => {
    try {
      const Body = { project_item_id: id };
      const headers = apiHeaderJson;

      Swal.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes, Remove it!",
      }).then((result) => {
        if (result.isConfirmed) {
          axios
            .post(`${apiURL}api/requests/DeleteProjectItem`, Body, { headers })
            .then((response) => {
              Swal.fire({
                title: `<strong>${response.data.success ? "Success" : "Failed"
                  }</strong>`,
                text: response.data.message,
                icon: response.data.success ? "success" : "error",
                timer: 1000,
                timerProgressBar: true,
                showConfirmButton: false,
              });

              if (response.data.success) {
                setProjectselectedItems([]);
                getProjectItemList();
              }
            })
            .catch((error) => {
              Swal.fire({
                title: "<strong>Error</strong>",
                html: error.message || error,
                icon: "error",
              });
            });
        }
      });
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getItemsList();
    getProjectItemList();
    getItemCategories();
  }, []);

  return (
    <div className="col-xxl-12">
      <div className="card">
        <div className="card-body">
          <div className="card-header align-items-center d-flex mb-3">
            <div className="d-flex align-items-center">
              <h5 className="card-title flex-grow-1 mb-0">Items List</h5>
            </div>

            <div className="d-flex justify-content-end align-items-center ms-auto">
              <button
                type="button"
                className="btn btn-primary btn-label waves-effect waves-light"
                data-bs-toggle="modal"
                data-bs-target="#AddItemModal"
                onClick={() => {
                  resetForm();
                  getItemsList();
                }}
              >
                <i className="bx bx-add-to-queue label-icon align-middle fs-16 me-2"></i>
                Add Item
              </button>
            </div>
          </div>

          <div className="table-responsive">
            {loadingList ? (
              <ContentLoader />
            ) : projectselectedItems.length === 0 ? (
              <NoRecords />
            ) : (
              <table className="table table-hover table-centered align-middle table-nowrap mb-0">
                <thead className="table-light">
                  <tr>
                    <th scope="col" style={{ width: "30%" }}>
                      Item Details
                    </th>
                    <th scope="col" className="text-center">
                      Unit
                    </th>
                    <th scope="col" className="text-center">
                      Price
                    </th>
                    <th scope="col" className="text-center">
                      Category
                    </th>
                    <th scope="col" className="text-center">
                      Qty & Variations
                    </th>
                    <th scope="col" className="text-center">
                      Delivery Date
                    </th>
                    <th scope="col" className="text-center">
                      Actions
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {projectselectedItems.map((item, index) => {
                    return (
                      <tr key={index}>
                        <td>
                          <div className="d-flex align-items-center">
                            <div className="flex-shrink-0 me-3">
                              <div className="avatar-sm">
                                <div className="avatar-title bg-light rounded">
                                  <i className="bx bx-package align-middle fs-4 text-primary"></i>
                                </div>
                              </div>
                            </div>
                            <div className="flex-grow-1">
                              <h6 className="mb-1">{item?.item_name}</h6>
                              <p className="text-muted mb-0">
                                ID: {item?.item_id}
                              </p>
                            </div>
                          </div>
                        </td>

                        <td className="text-center">
                          <span className="fw-semibold">
                            {item?.item_unit || "-"}
                          </span>
                        </td>

                        <td className="text-center">
                          <span className="fw-semibold">
                            {item?.pi_item_price} QAR
                          </span>
                        </td>

                        <td className="text-center">
                          <span className="badge bg-info-subtle text-info">
                            {item?.item_category_name}
                          </span>
                        </td>

                        <td className="text-center">
                          <div className="d-flex justify-content-center align-items-center gap-2">
                            {item?.pi_item_qty_old && item?.pi_item_qty_old !== item?.pi_item_qty && (
                              <>
                                <span className="badge bg-light text-muted">
                                  {item?.pi_item_qty_old}
                                </span>
                                <i className="ri-arrow-right-line text-muted"></i>
                              </>
                            )}


                            <span className="badge bg-primary-subtle text-primary">
                              {item?.pi_item_qty}
                            </span>
                          </div>
                        </td>

                        <td className="text-center">
                          <span className="text-muted">
                            {DateFormaterMonth(item?.pi_item_delivery_date) ||
                              "-"}
                          </span>
                        </td>

                        <td className="text-center">
                          <div className="d-flex gap-2 justify-content-center">
                            <button
                              className="btn btn-sm btn-outline-warning"
                              data-bs-toggle="modal"
                              data-bs-target="#AddItemModal"
                              onClick={() => {
                                setIsVariationMode(true);
                                getProjectItemDetails(item?.project_item_id);
                              }}
                              title="Add Variation"
                            >
                              <i className="ri-refresh-line"></i>
                            </button>

                            <button
                              className="btn btn-sm btn-outline-primary"
                              data-bs-toggle="modal"
                              data-bs-target="#AddItemModal"
                              onClick={() => {
                                getItemsList();
                                getItemCategories();
                                getProjectItemDetails(item?.project_item_id);
                              }}
                              title="Edit Item"
                            >
                              <i className="ri-edit-2-line"></i>
                            </button>

                            <button
                              onClick={() =>
                                handleDelete(
                                  item?.project_item_id || item?.item_id
                                )
                              }
                              className="btn btn-sm btn-outline-danger"
                              title="Remove Item"
                            >
                              <i className="ri-delete-bin-line"></i>
                            </button>
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>
      </div>

      <div
        id="AddItemModal"
        className="modal fade"
        tabIndex={-1}
        aria-labelledby="myModalLabel"
        aria-hidden="true"
        style={{ display: "none" }}
      >
        <div className="modal-dialog modal-dialog-centered">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title">
                {isVariationMode
                  ? "Add Variation"
                  : isEditMode
                    ? "Edit Project Item"
                    : "Add New Project Item"}
              </h5>
              <button
                type="button"
                className="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
                onClick={() => resetForm()}
              ></button>
            </div>

            <div className="modal-body">
              <form onSubmit={handleSubmitItems} className="row g-3">
                {!isVariationMode && (
                  <>

                    <div className="col-12">
                      <label className="form-label">Select Item</label>
                      <Select
                        onChange={handleSelect}
                        options={itemsData}
                        placeholder="Select Item"
                        value={
                          itemID
                            ? itemsData.find((option) => option.value === itemID || null)
                            : null
                        }
                        className="basic-single"
                        classNamePrefix="select"
                      />
                    </div>

                    <div className="col-12">
                      <label className="form-label">Select Category</label>
                      <Select
                        onChange={(selected) =>
                          setCategoryID(selected ? selected.value : null)
                        }
                        options={categoryData}
                        placeholder="Select Category"
                        value={
                          categoryID
                            ? categoryData.find(
                              (option) => option.value === categoryID
                            )
                            : null
                        }
                        className="basic-single"
                        classNamePrefix="select"
                      />
                    </div>

                    <div className="col-12">
                      <label className="form-label">Item Price (QAR)</label>
                      <input
                        type="number"
                        id="itemPrice"
                        name="itemPrice"
                        value={itemPrice}
                        onChange={(e) => setItemPrice(e.target.value)}
                        className="form-control"
                        placeholder="Enter Item Price"
                        min="0"
                        step="0.01"
                      />
                    </div>

                    <div className="col-12">
                      <label className="form-label">Delivery Date</label>
                      <input
                        type="date"
                        id="deliveryDate"
                        name="deliveryDate"
                        value={deliveryDate || ""}
                        onChange={(e) => setDeliveryDate(e.target.value)}
                        className="form-control"
                      />
                    </div>

                  </>
                )}

                <div className="col-12">
                  <label className="form-label">Item Quantity</label>
                  <input
                    type="number"
                    id="itemQuantity"
                    name="itemQuantity"
                    value={itemQuantity}
                    onChange={(e) => setItemQuantity(e.target.value)}
                    className="form-control"
                    placeholder="Enter Item Quantity"
                    min="1"
                  />
                </div>

                <div className="modal-footer mt-2">
                  <button
                    type="button"
                    className="btn btn-light"
                    data-bs-dismiss="modal"
                    id="itemModal"
                    onClick={() => resetForm()}
                  >
                    Cancel
                  </button>

                  <button
                    type="submit"
                    className="btn btn-primary"
                    disabled={
                      !itemQuantity ||
                      (!isVariationMode && (!itemPrice || !itemID || !categoryID))
                    }
                  >
                    {isEditMode ? "Update Item" : "Add Item"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddItems;
