import React, {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import Breadcrumb from "../../components/common/Breadcrumb";
import { useEmployee } from "../../hooks/useEmployees";
import EmployeeSearchInput from "../../components/common/EmployeeSearchInput";
import { useForm } from "react-hook-form";
import Label from "../../components/common/Label";
import AdvancePaymentList from "../../components/AdvancePayment/AdvancePaymentListDetails";
import { employee } from "../../data/masters";
import { formatFigure } from "../../utils/appUtils";
import { useParams } from "react-router-dom";
import { useExpenseTransactions } from "../../hooks/useExpense";
import handleAdvancePaymentExport from "../../components/AdvancePayment/handleAdvancePaymentExport";

export const AdvancePaymentContext = createContext();
export const useAdvancePaymentContext = () => {
  const context = useContext(AdvancePaymentContext);
  if (!context) {
    throw new Error(
      "useAdvancePaymentContext must be used within an AdvancePaymentProvider"
    );
  }
  return context;
};
const AdvancePaymentPageDetails = () => {
  const { employeeId } = useParams();

  const { data: transactionData } = useExpenseTransactions(employeeId, {
    enabled: !!employeeId
  });

  const employeeName = useMemo(() => {
    if (Array.isArray(transactionData) && transactionData.length > 0) {
      const emp = transactionData[0].employee;
      if (emp) return `${emp.firstName} ${emp.lastName}`;
    }
    return "";
  }, [transactionData]);

  const [balance, setBalance] = useState(null);
  const { control, reset, watch } = useForm({
    defaultValues: {
      employeeId: employeeId || "",
      searchString: "",
    },
  });

  const selectedEmployeeId = employeeId || watch("employeeId");

  const searchString = watch("searchString");

  useEffect(() => {
    const selectedEmpoyee = sessionStorage.getItem("transaction-empId");
    reset({
      employeeId: selectedEmpoyee || "",
    });
  }, [reset]);


  const tableRef = useRef(null);

  const handleExport = (type) => {
    handleAdvancePaymentExport(type, transactionData, tableRef);
  };

  return (
    <AdvancePaymentContext.Provider value={{ setBalance }}>
      <div className="container-fluid">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Finance", link: "/advance-payment" },
            { label: "Advance Payment", link: "/advance-payment" },
            employeeName && { label: employeeName, link: "" },
          ].filter(Boolean)}
        />

        <div className="card px-4 py-2 page-min-h ">
          <div className="row py-1 align-items-center">

            {/* LEFT SIDE → EXPORT DROPDOWN */}
            <div className="col-md-4 d-flex align-items-center">
              <div className="dropdown">
                <button
                  aria-label="Click me"
                  className="btn btn-sm btn-label-secondary dropdown-toggle"
                  type="button"
                  data-bs-toggle="dropdown"
                  aria-expanded="false"
                >
                  <i className="bx bx-export me-2 bx-sm"></i>Export
                </button>

                <ul className="dropdown-menu">
                  <li>
                    <button className="dropdown-item" onClick={() => handleExport("print")}>
                      <i className="bx bx-printer me-1"></i> Print
                    </button>
                  </li>
                  <li>
                    <button className="dropdown-item" onClick={() => handleExport("csv")}>
                      <i className="bx bx-file me-1"></i> CSV
                    </button>
                  </li>
                  <li>
                    <button className="dropdown-item" onClick={() => handleExport("excel")}>
                      <i className="bx bxs-file-export me-1"></i> Excel
                    </button>
                  </li>
                  <li>
                    <button className="dropdown-item" onClick={() => handleExport("pdf")}>
                      <i className="bx bxs-file-pdf me-1"></i> PDF
                    </button>
                  </li>
                </ul>
              </div>
            </div>

            {/* RIGHT SIDE → CURRENT BALANCE */}
            <div className="col-md-8 d-flex justify-content-end align-items-center">
              {balance !== null ? (
                <>
                  <label className="fs-5 fw-semibold">Current Balance :</label>
                  <span
                    className={`${balance > 0 ? "text-success" : "text-danger"} fs-5 fw-bold ms-1`}
                  >
                    {balance > 0 && <i className="bx bx-plus b-sm"></i>}{" "}
                    {formatFigure(balance, { type: "currency", currency: "INR" })}
                  </span>
                </>
              ) : null}
            </div>

          </div>

          <AdvancePaymentList employeeId={selectedEmployeeId} searchString={searchString} tableRef={tableRef} />
        </div>
      </div>
    </AdvancePaymentContext.Provider>
  );
};

export default AdvancePaymentPageDetails;
