import React, { useContext } from "react";
import AuthenticatedLayout from "@/Layouts/AuthenticatedLayout";
import { FilterMatchMode } from "primereact/api";
import { DataTable } from "primereact/datatable";
import { Column } from "primereact/column";
import { InputText } from "primereact/inputtext";
import { useEffect } from "react";
import axios from "axios";
import { Button } from "primereact/button";
import { useState } from "react";
import { useRef } from "react";
import "../../../css/receipt.css";
import Print from "./Print";
import Print3Inch from "./Print3Inch";
import Print2Inch from "./Print2Inch";
import { authUser } from "@/Components/AuthProvider";
import { Dialog } from "primereact/dialog";
import { Calendar } from "primereact/calendar";
import { Dropdown } from "primereact/dropdown";
import { Toast } from "primereact/toast";
import SalesPersonSearch from "@/Components/SalesPersonSearch";

export default function Sales({ auth }) {
  const { permission } = useContext(authUser);
  const isRestrictedMode = permission?.includes("pos_restricted_mode");
  const [sales, setSales] = useState([]);
  const [shop, setShop] = useState([]);
  const [sale, setSale] = useState([]);
  const [loading, setLoading] = useState(false);
  const [totalRecords, setTotalRecords] = useState(0);

  const [lazyParams, setLazyParams] = useState({
    first: 0,
    rows: 10,
    page: 0,
    search: "",
  });
  const searchTimeout = useRef(null);
  const toast = useRef(null);

  const [collectModalOpen, setCollectModalOpen] = useState(false);
  const [collectSale, setCollectSale] = useState(null);
  const [collBanks, setCollBanks] = useState([]);
  const [collMobileBanks, setCollMobileBanks] = useState([]);
  const [collPaymentType, setCollPaymentType] = useState("cash");
  const [collPaymentAccountId, setCollPaymentAccountId] = useState("cash");
  const [collPaymentAmount, setCollPaymentAmount] = useState("");
  const [collOrderNo, setCollOrderNo] = useState("");
  const [collNote, setCollNote] = useState("");
  const [collDate, setCollDate] = useState(() => new Date());
  const [collSubmitting, setCollSubmitting] = useState(false);
  const [collSalesPersonId, setCollSalesPersonId] = useState(null);
  const [collSalesPersonText, setCollSalesPersonText] = useState("");

  const getInvoiceRemainingDue = (sale) => {
    const gt = Number(sale?.grand_total ?? 0);
    const paid = Number(sale?.current_payment ?? 0);
    return Math.max(0, gt - paid);
  };

  const openCollectModal = (sale) => {
    setCollectSale(sale);
    const rem = getInvoiceRemainingDue(sale);
    setCollPaymentAmount(rem > 0 ? String(rem) : "");
    setCollOrderNo("");
    setCollNote("");
    setCollDate(new Date());
    setCollPaymentType("cash");
    setCollPaymentAccountId("cash");
    setCollSalesPersonId(null);
    setCollSalesPersonText("");
    setCollectModalOpen(true);
    Promise.all([
      axios.get(route("bank.view")),
      axios.get(route("mobilebank.view")),
    ])
      .then(([b, m]) => {
        setCollBanks(b.data?.bank || []);
        setCollMobileBanks(m.data?.mobilebank || []);
      })
      .catch(() => {
        setCollBanks([]);
        setCollMobileBanks([]);
      });
  };

  const closeCollectModal = () => {
    setCollectModalOpen(false);
    setCollectSale(null);
    setCollSubmitting(false);
    setCollSalesPersonId(null);
    setCollSalesPersonText("");
  };

  const submitInvoiceDueCollection = () => {
    if (!collectSale?.client_id) {
      toast.current?.show({
        severity: "warn",
        summary: "Customer",
        detail: "This invoice has no customer; due collection is not available.",
        life: 4000,
      });
      return;
    }
    const remaining = getInvoiceRemainingDue(collectSale);
    const pay = Number(collPaymentAmount);
    if (!collOrderNo?.trim()) {
      toast.current?.show({
        severity: "warn",
        summary: "Receipt No",
        detail: "Receipt number is required.",
        life: 3000,
      });
      return;
    }
    if (!pay || pay <= 0) {
      toast.current?.show({
        severity: "warn",
        summary: "Payment",
        detail: "Enter a valid payment amount.",
        life: 3000,
      });
      return;
    }
    if (pay - remaining > 0.0001) {
      toast.current?.show({
        severity: "warn",
        summary: "Payment",
        detail: `Amount cannot exceed invoice due (${remaining.toFixed(2)}).`,
        life: 4000,
      });
      return;
    }
    if (collPaymentType === "Bank" && !collPaymentAccountId) {
      toast.current?.show({
        severity: "warn",
        summary: "Bank",
        detail: "Select a bank account.",
        life: 3000,
      });
      return;
    }
    if (collPaymentType === "Mobile Bank" && !collPaymentAccountId) {
      toast.current?.show({
        severity: "warn",
        summary: "Mobile bank",
        detail: "Select a mobile banking account.",
        life: 3000,
      });
      return;
    }

    const warehouseId =
      collectSale.location_id ??
      collectSale.transition_location_id ??
      auth.user.shop_id;

    const paymentId =
      collPaymentType === "cash" ? "cash" : Number(collPaymentAccountId);

    const payload = {
      customer_id: collectSale.client_id,
      invoice_id: collectSale.id,
      date: collDate,
      order_no: collOrderNo.trim(),
      note: collNote?.trim() ?? "",
      warehouse_id: warehouseId,
      payment_type: collPaymentType,
      sales_person_id: collSalesPersonId,
      list: [
        {
          deu_balance: remaining,
          total_sales: remaining,
          payment: pay,
          prev_payment: 0,
          payment_id: paymentId,
          payment_type: "cash",
          index: 0,
        },
      ],
    };

    setCollSubmitting(true);
    axios
      .post(route("customer-store-due-collection"), payload)
      .then(() => {
        toast.current?.show({
          severity: "success",
          summary: "Saved",
          detail: "Due collection recorded for this invoice.",
          life: 3000,
        });
        closeCollectModal();
        loadSales();
      })
      .catch((error) => {
        const errs = error.response?.data?.errors;
        if (errs && typeof errs === "object") {
          const first = Object.values(errs)[0];
          const msg = Array.isArray(first) ? first[0] : String(first);
          toast.current?.show({
            severity: "error",
            summary: "Error",
            detail: msg || "Could not save collection.",
            life: 5000,
          });
        } else {
          toast.current?.show({
            severity: "error",
            summary: "Error",
            detail: "Could not save collection.",
            life: 4000,
          });
        }
      })
      .finally(() => setCollSubmitting(false));
  };

  {
    /* Table Header Component  */
  }
  const [filters, setFilters] = useState({
    global: { value: null, matchMode: FilterMatchMode.CONTAINS },
    name: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    type: { value: null, matchMode: FilterMatchMode.STARTS_WITH },
    "customer.name": { value: "", matchMode: "contains" },
  });
  const [globalFilterValue, setGlobalFilterValue] = useState("");
  // Load sales data with server-side pagination and search
  const loadSales = async (params = lazyParams) => {
    setLoading(true);
    try {
      // Try the new paginated endpoint first
      const paginatedResponse = await axios.get(
        route("sales.paginated"),
        {
          params: {
            rows: params.rows,
            page:
              params.page ||
              Math.floor(params.first / params.rows),
            search: params.search || "",
          },
        }
      );

      if (paginatedResponse.data.sales) {
        setSales(paginatedResponse.data.sales);
        setTotalRecords(paginatedResponse.data.totalRecords);
        return;
      }
    } catch (paginatedError) {
      console.log(
        "Paginated endpoint not available, falling back to regular view"
      );
    }

    try {
      // Fallback to the original sales-view endpoint
      const response = await axios.get(route("sales.view"), {
        params: {
          rows: params.rows,
          page: params.page || Math.floor(params.first / params.rows),
          search: params.search || "",
        },
      });

      if (response.data.totalRecords !== undefined) {
        // New paginated response format
        setSales(response.data.sales);
        setTotalRecords(response.data.totalRecords);
      } else {
        // Original response format - set total records for client-side handling
        setSales(response.data.sales);
        setTotalRecords(response.data.sales.length);
      }
    } catch (error) {
      console.error("Error loading sales:", error);
      setSales([]);
      setTotalRecords(0);
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    loadSales();
  }, []);

  useEffect(() => {
    if (lazyParams.first !== 0 || lazyParams.page !== 0) {
      loadSales();
    }
  }, [lazyParams]);

  // Handle pagination
  const onPage = (event) => {
    const params = {
      ...lazyParams,
      first: event.first,
      rows: event.rows,
      page: event.page,
    };
    setLazyParams(params);
    loadSales(params);
  };

  const onGlobalFilterChange = (e) => {
    const value = e.target.value;
    let _filters = { ...filters };

    _filters["global"].value = value;
    setFilters(_filters);
    setGlobalFilterValue(value);

    // Clear existing timeout
    if (searchTimeout.current) {
      clearTimeout(searchTimeout.current);
    }

    // Set new timeout for debounced search
    searchTimeout.current = setTimeout(() => {
      const params = {
        ...lazyParams,
        first: 0,
        page: 0,
        search: value,
      };
      setLazyParams(params);
      loadSales(params);
    }, 500);
  };
  const renderHeader = () => {
    return (
      <div className="w-100% flex justify-end	">
        <span className="p-input-icon-left h-10 ">
          <i className="pi pi-search" />
          <InputText
            className="h-[41px] w-64 max-w-[90vw] md:w-72"
            value={globalFilterValue}
            onChange={onGlobalFilterChange}
            placeholder="Invoice, date, customer name, phone, code…"
          />
        </span>
      </div>
    );
  };

  const header = renderHeader();
  {
    /*End Table Header   */
  }

  const handelDelete = (e) => {
    let dataId = e.currentTarget.getAttribute("data-id");
    let con = confirm("Are you sure to Delete");
    if (con) {
      setLoading(true);
      axios
        .delete(route("sales.destroy", dataId))
        .then((res) => {
          // Reload current page data instead of using response data
          loadSales();
        })
        .catch((error) => {
          console.error("Error deleting sale:", error);
          setLoading(false);
        });
    }
  };

  const handelEdit = (e) => {
    let dataId = e.currentTarget.getAttribute("data-id");

    window.location.href = route("sales.edit", dataId);

  };

  // Get invoice print mode from settings
  const getInvoicePrintMode = () => {
    if (typeof window !== 'undefined' && window.setting && window.setting.invoice_print_mode) {
      return window.setting.invoice_print_mode;
    }
    return 'a4'; // Default to A4
  };

  const printMode = getInvoicePrintMode();

  return (
    <>
      <div id="print">
        {printMode === "pos_2inch" ? (
          <Print2Inch sales={sale} auth={auth} />
        ) : printMode === "pos_3inch" ? (
          <Print3Inch sales={sale} auth={auth} />
        ) : (
          <Print sales={sale} auth={auth} />
        )}
      </div>
      <AuthenticatedLayout
        user={auth.user}
        header={<></>}
        headerButton={<></>}
      >
        <Toast ref={toast} position="top-right" />
        <Dialog
          header="Collect invoice due"
          visible={collectModalOpen}
          className="w-full max-w-lg"
          contentClassName="px-1 sm:px-2 pt-2 pb-1"
          onHide={closeCollectModal}
          footer={
            <div className="flex justify-end gap-3 border-t border-slate-100 pt-4 mt-1">
              <Button
                label="Cancel"
                icon="pi pi-times"
                className="p-button-text"
                onClick={closeCollectModal}
                disabled={collSubmitting}
              />
              <Button
                label="Save collection"
                icon="pi pi-check"
                className="p-button-success"
                loading={collSubmitting}
                onClick={submitInvoiceDueCollection}
              />
            </div>
          }
        >
          {collectSale && (
            <div className="flex flex-col gap-7 pb-2">
              <div className="rounded-xl border border-slate-200 bg-slate-50/80 p-4 sm:p-5 text-sm space-y-3">
                <div>
                  <div className="font-semibold text-slate-800">
                    Invoice{" "}
                    <span className="tabular-nums">{collectSale.invoice_no}</span>
                  </div>
                  <div className="mt-2 text-slate-600">
                    {collectSale.customer?.name ?? "—"}
                    {collectSale.customer?.code
                      ? ` (${collectSale.customer.code})`
                      : ""}
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-x-4 gap-y-4 text-xs sm:text-sm">
                  <div>
                    <span className="text-slate-500">Grand total</span>
                    <div className="mt-1 font-medium tabular-nums">
                      {Number(collectSale.grand_total ?? 0).toFixed(2)}
                    </div>
                  </div>
                  <div>
                    <span className="text-slate-500">Paid on invoice</span>
                    <div className="mt-1 font-medium tabular-nums">
                      {Number(collectSale.current_payment ?? 0).toFixed(2)}
                    </div>
                  </div>
                  <div className="col-span-2 border-t border-slate-200 pt-4 mt-1">
                    <span className="text-slate-500">Due on this invoice</span>
                    <div className="mt-2 text-lg font-semibold tabular-nums text-amber-800">
                      {getInvoiceRemainingDue(collectSale).toFixed(2)}
                    </div>
                  </div>
                </div>
              </div>

              <div className="p-float-label">
                <Dropdown
                  value={collPaymentType}
                  options={["cash", "Bank", "Mobile Bank"]}
                  onChange={(e) => {
                    const v = e.value;
                    setCollPaymentType(v);
                    if (v === "cash") {
                      setCollPaymentAccountId("cash");
                    } else {
                      setCollPaymentAccountId(null);
                    }
                  }}
                  className="w-full h-11"
                />
                <label>Payment type</label>
              </div>

              {collPaymentType === "Bank" && (
                <div className="p-float-label">
                  <Dropdown
                    value={collPaymentAccountId}
                    options={collBanks}
                    onChange={(e) => setCollPaymentAccountId(e.value)}
                    optionLabel="bank_name"
                    optionValue="id"
                    filter
                    showClear
                    placeholder="Select bank"
                    className="w-full h-11"
                  />
                  <label>Bank account</label>
                </div>
              )}

              {collPaymentType === "Mobile Bank" && (
                <div className="p-float-label">
                  <Dropdown
                    value={collPaymentAccountId}
                    options={collMobileBanks}
                    onChange={(e) => setCollPaymentAccountId(e.value)}
                    optionLabel="account_type"
                    optionValue="id"
                    filter
                    showClear
                    placeholder="Select mobile bank"
                    className="w-full h-11"
                  />
                  <label>Mobile banking</label>
                </div>
              )}

              <div className="p-float-label">
                <InputText
                  type="number"
                  min={0}
                  step="0.01"
                  className="w-full h-11"
                  value={collPaymentAmount}
                  onChange={(e) => setCollPaymentAmount(e.target.value)}
                />
                <label>Collection amount</label>
              </div>

              {permission.includes("sales_person_pos_view") && (
                <div>
                  <SalesPersonSearch
                    salesPersonText={collSalesPersonText}
                    onSalesPersonSelect={(sp) => {
                      setCollSalesPersonId(sp.id || null);
                      if (sp.id && sp.name && sp.code) {
                        setCollSalesPersonText(`${sp.name} (${sp.code})`);
                      } else {
                        setCollSalesPersonText("");
                      }
                    }}
                    placeholder="Sales person (optional)"
                    useFloatLabel={false}
                    showClear={true}
                    className="w-full min-w-0 h-11 [&.p-autocomplete]:w-full [&_.p-inputtext]:w-full [&_.p-inputtext]:h-11 [&_.p-inputtext]:text-sm [&_.p-inputtext]:bg-gray-100 [&_.p-inputtext]:border-gray-200 [&_.p-inputtext]:rounded-md [&_.p-inputtext]:text-gray-700"
                  />
                </div>
              )}

              <div className="p-float-label">
                <Calendar
                  value={collDate}
                  onChange={(e) => setCollDate(e.value)}
                  showIcon
                  className="w-full"
                  dateFormat="yy-mm-dd"
                />
                <label>Date</label>
              </div>

              <div className="p-float-label">
                <InputText
                  className="w-full h-11"
                  value={collOrderNo}
                  onChange={(e) => setCollOrderNo(e.target.value)}
                />
                <label>Receipt No</label>
              </div>

              <div className="p-float-label">
                <InputText
                  className="w-full h-11"
                  value={collNote}
                  onChange={(e) => setCollNote(e.target.value)}
                />
                <label>Note (optional)</label>
              </div>
            </div>
          )}
        </Dialog>
        {/* View Table*/}
        <div className="card">
          <DataTable
            className="defulattable"
            value={sales}
            lazy
            dataKey="id"
            paginator
            showGridlines
            first={lazyParams.first}
            rows={lazyParams.rows}
            totalRecords={totalRecords}
            onPage={onPage}
            loading={loading}
            header={header}
            filters={filters}
            emptyMessage="No sales found."
            paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown"
            rowsPerPageOptions={[10, 25, 50, 100]}
          >
            <Column
              field="created_at"
              body={(e) => {
                const dt = new Date(e.created_at);
                const dateStr = dt.toLocaleDateString("en-CA", { timeZone: "Asia/Dhaka" });
                const timeStr = new Date(e.updated_at).toLocaleTimeString("en-US", { timeZone: "Asia/Dhaka", hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: true });
                return (
                  <div className="flex flex-col gap-0.5">
                    <span className="font-semibold text-slate-800">{dateStr}</span>
                    <span className="text-xs text-slate-500">{timeStr}</span>
                  </div>
                );
              }}
              header="Date"
            />

            <Column
              field="invoice_no"
              body={(e) => {
                return <b> {e.invoice_no}</b>;
              }}
              header="Invoice No"
            />
            <Column body={(e) => {
              return <b> {e?.customer?.name}  {e?.customer?.code && `(${e?.customer?.code})`} {e?.customer?.number && `(${e?.customer?.number})`}</b>;
            }} header="Customer" />
            <Column
              header="Invoice due"
              style={{ minWidth: "7rem" }}
              body={(e) => {
                if (!e?.client_id) {
                  return <span className="text-slate-400">—</span>;
                }
                // Show due amount for THIS invoice only (grand_total - current_payment)
                const due = getInvoiceRemainingDue(e);
                return (
                  <span
                    className={[
                      "tabular-nums font-medium",
                      due > 0 ? "text-amber-800" : "text-slate-700",
                    ].join(" ")}
                  >
                    {due.toFixed(2)}
                  </span>
                );
              }}
            />
            <Column
              field="total"
              header="Total"
              dataType="boolean"
            />
            {permission.includes("sales_vat_view") && (
              <Column
                field="vat"
                header="Vat"
                body={(e) => {
                  return <> {e.vat} </>;
                }}
                dataType="boolean"
              />
            )}

            <Column
              field="after_discount"
              header="Discount Total"
              body={(e) => {
                return <> {e.after_discount ?? 0} </>;
              }}
              dataType="boolean"
            />
            {isRestrictedMode && (
              <Column
                header="Expected Grand Total"
                style={{ width: "160px", minWidth: "140px", maxWidth: "200px" }}
                bodyClassName="whitespace-normal break-words"
                body={(e) => {
                  const data = e.pos_table_parcel_json;
                  const logs = data?.customer_copy_print_log;
                  const tableOrParcel = data?.table_or_parcel || "-";
                  const salesPersonName =
                    e?.updated_by?.name ||
                    e?.user?.name ||
                    e?.sales_person?.name ||
                    e?.salesPerson?.name ||
                    "";
                  if (!Array.isArray(logs) || logs.length === 0) {
                    return <span className="text-slate-400 text-xs">-</span>;
                  }
                  const saleTotal = Number(e.grand_total || 0);
                  return (
                    <div className="min-w-0">
                      {/* Top row: Name + Table/Parcel badge */}
                      <div className="flex items-start justify-between gap-2">
                        <div className="min-w-0">
                          <div className="text-xs sm:text-sm font-semibold text-slate-800 truncate">
                            {salesPersonName || "-"}
                          </div>


                        </div>

                        {/* Badge */}
                        {tableOrParcel ? (
                          <span className="shrink-0 inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-2 py-0.5 text-[10px] font-medium text-slate-700">
                            {tableOrParcel}
                          </span>
                        ) : (
                          <span className="shrink-0 inline-flex items-center rounded-full border border-slate-200 bg-slate-50 px-2 py-0.5 text-[10px] font-medium text-slate-400">
                            -
                          </span>
                        )}
                      </div>

                      {/* Totals row */}
                      <div className="mt-2 flex flex-wrap gap-1.5">
                        {logs?.length ? (
                          logs.map((item, idx) => {
                            const t = Number(item?.total) || 0;
                            const match =
                              Math.round(t * 100) === Math.round((Number(saleTotal) || 0) * 100);

                            return (
                              <span
                                key={idx}
                                className={[
                                  "inline-flex items-center rounded-md px-2 py-1 text-[11px] font-semibold leading-none",
                                  "border",
                                  match
                                    ? "border-emerald-200 bg-emerald-50 text-emerald-800"
                                    : "border-red-200 bg-red-50 text-red-700",
                                ].join(" ")}
                                title={match ? "Matched total" : "Mismatch"}
                              >
                                {t}
                              </span>
                            );
                          })
                        ) : (
                          <span className="text-[11px] text-slate-400">No totals</span>
                        )}
                      </div>
                    </div>
                  );
                }}
              />
            )}
            <Column
              field="order_no"
              header="Note"
              dataType="boolean"
            />
            <Column
              field="grand_total"
              header="Grand total"
              dataType="boolean"
            />
            <Column
              header="Action"
              className="p-button-rounded p-button-success mr-2 px-3 py-2  w-10 h-10 font-medium"
              body={(e) => {
                return (
                  <>
                    {permission.includes("sales_view") && (
                      <Button
                        icon="pi pi-eye"
                        title="View Details"
                        onClick={() => {
                          window.location.href = route(
                            "sales.show",
                            e.id
                          );
                        }}
                        className="p-button-rounded p-button-help mr-2 px-3 py-2 w-10 h-10 font-medium"
                      />
                    )}
                    {permission.includes("sales_edit") && (
                      <Button
                        icon="bx bx-edit"
                        data-id={e.id}
                        onClick={handelEdit}
                        className="p-button-rounded  p-button-success mr-2 px-3 py-2  w-10 h-10  font-medium"
                      />
                    )}

                    {permission.includes("customer_collection_create") &&
                      e?.client_id &&
                      getInvoiceRemainingDue(e) > 0 && (
                        <Button
                          icon="pi pi-wallet"
                          title="Collect due on this invoice"
                          onClick={() => openCollectModal(e)}
                          className="p-button-rounded p-button-secondary mr-2 px-3 py-2 w-10 h-10 font-medium"
                        />
                      )}

                    <Button
                      icon="bx bx-printer"
                      data-id={e.id}
                      onClick={() => {
                        setSale(e);
                        setTimeout(async () => {
                          // Load both fonts explicitly
                          await document.fonts.load(
                            "16px ProseAntiqueBold"
                          );
                          await document.fonts.load(
                            "16px corsiva-regular"
                          );

                          // Wait until all fonts are fully loaded
                          await document.fonts.ready;
                          window.print();
                        }, 300);
                      }}
                      className="p-button-rounded p-button-info  mr-2 px-3 py-2  w-10 h-10  font-medium"
                    />

                    {permission.includes("sales_delete") && (
                      <Button
                        icon="pi pi-trash"
                        data-id={e.id}
                        onClick={handelDelete}
                        className="p-button-rounded p-button-warning px-3 py-2  w-10 h-10  font-medium"
                      />
                    )}


                  </>
                );
              }}
              bodyClassName="text-center"
              style={{ minWidth: "17rem" }}
            />
          </DataTable>
        </div>
        {/* View Table End*/}
      </AuthenticatedLayout>
    </>
  );
}
