import { useSiteContext } from "@/app/Context/SiteContext";
import { useFormattedPrice } from "@/app/utils/formatPrice";
import { formatDateWithTime } from "@/app/utils/formattedDateWithTime";
import { getNameByCode } from "@/app/utils/getNameByCode";
import { parseArrayField } from "@/app/utils/parseArrayField";
import { apiUrl, frontEndUrl } from "@/app/utils/variables";

export default function PurchaseReturnPDF({
  brandSettings,
  form,
  currency,
}) {
  const { getCurrentCurrency, currentSession } = useSiteContext();
  const { formatPrice } = useFormattedPrice();

  /* ======================================================
     PURCHASE & RETURN ITEMS
  ====================================================== */
  const purchase =
    parseArrayField(form?.purchase_info)?.[0] || null;

  const returnedItems =
    parseArrayField(form?.updated_line_items) || [];


    

  /* ======================================================
     CURRENCY
  ====================================================== */
  const currentCurrency =
    getCurrentCurrency(form, currency) ||
    form?.currency ||
    purchase?.currency;

  /* ======================================================
     PURCHASE RETURN INFO
  ====================================================== */
  const returnDate =
    form?.purchasereturn_date || form?.updated_at;

  /* ======================================================
     TOTAL
  ====================================================== */
  const returnTotal = returnedItems.reduce(
    (sum, item) =>
      sum +
      Number(item.return_qty || 0) *
        Number(item.buying_price || item.price || 0),
    0
  );

  /* ======================================================
     RENDER
  ====================================================== */
  return (
    <div
      id="pdf-content"
      style={{
        fontFamily: "Arial, sans-serif",
        padding: "30px",
        position: "relative",
      }}
    >
      {/* ================= WATERMARK ================= */}
      <div
        style={{
          position: "absolute",
          top: "45%",
          left: "50%",
          transform: "translate(-50%, -50%) rotate(-30deg)",
          fontSize: "80px",
          color: "rgba(22,101,52,0.15)",
          fontWeight: "700",
          pointerEvents: "none",
        }}
      >
        PURCHASE RETURN
      </div>

      <table style={{ width: "100%", borderCollapse: "collapse" }}>
        <tbody>
          {/* ================= HEADER ================= */}
          <tr>
            <td valign="top">
              {brandSettings?.company_logo_color && (
                <img
                  src={`${apiUrl}/proxy?fileUrl=${frontEndUrl}${brandSettings.company_logo_color}`}
                  style={{
                    width: "120px",
                    height: "120px",
                    objectFit: "contain",
                    display: "block",
                    marginBottom: "10px",
                  }}
                />
              )}

              <div style={{ fontSize: "13px", marginTop: "10px" }}>
                <strong>{brandSettings?.company_name}</strong>
                <div>{brandSettings?.address_line_1}</div>
                <div>
                  {brandSettings?.city},{" "}
                  {getNameByCode(brandSettings?.state_province, "state")},{" "}
                  {getNameByCode(brandSettings?.country, "country")}{" "}
                  {brandSettings?.postal_zip_code}
                </div>
                <div>Phone: {brandSettings?.phone}</div>
                <div>
                  TRN: {brandSettings?.tax_vat_registration_number}
                </div>
              </div>
            </td>

            <td align="right">
              <div
                style={{
                  fontSize: "22px",
                  fontWeight: "700",
                  marginBottom: "20px",
                }}
              >
                PURCHASE RETURN
              </div>

              <table cellPadding="4">
                <tbody>
                  <tr>
                    <td align="right" style={{ paddingRight: "10px" }}>
                      RETURN DATE
                    </td>
                    <td style={{ border: "1px solid #000", fontWeight: "700" }}>
                      {formatDateWithTime(returnDate, brandSettings)}
                    </td>
                  </tr>

                  <tr>
                    <td align="right" style={{ paddingRight: "10px" }}>
                      PURCHASE #
                    </td>
                    <td style={{ border: "1px solid #000", fontWeight: "700" }}>
                      {purchase?.purchase_number || "-"}
                    </td>
                  </tr>

                  <tr>
                    <td align="right" style={{ paddingRight: "10px" }}>
                      RETURN #
                    </td>
                    <td style={{ border: "1px solid #000", fontWeight: "700" }}>
                      {form?.purchasereturn_number || "-"}
                    </td>
                  </tr>
                </tbody>
              </table>
            </td>
          </tr>

          {/* ================= SUPPLIER ================= */}
          <tr>
            <td colSpan={2} style={{ paddingTop: "20px" }}>
              <table
                style={{
                  width: "100%",
                  border: `1px solid ${
                    brandSettings?.primary_color || "#000"
                  }`,
                }}
              >
                <tbody>
                  <tr>
                    <td
                      style={{
                        background: brandSettings?.primary_color,
                        color: "#fff",
                        fontWeight: "700",
                        padding: "6px",
                      }}
                    >
                      SUPPLIER DETAILS
                    </td>
                  </tr>
                  <tr>
                    <td style={{ padding: "8px", fontSize: "13px" }}>
                      <div>{purchase?.supplier_name}</div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </td>
          </tr>

          {/* ================= RETURN ITEMS ================= */}
          <tr>
            <td colSpan={2} style={{ paddingTop: "20px" }}>
              <table
                style={{
                  width: "100%",
                  border: `1px solid ${
                    brandSettings?.primary_color || "#000"
                  }`,
                  borderCollapse: "collapse",
                }}
              >
                <thead>
                  <tr
                    style={{
                      background: brandSettings?.primary_color,
                      color: "#fff",
                    }}
                  >
                    <th>ITEM</th>
                    <th>RETURN QTY</th>
                    <th>UNIT COST</th>
                    <th>TOTAL</th>
                  </tr>
                </thead>

                <tbody>
                  {returnedItems.length === 0 ? (
                    <tr>
                      <td colSpan={4} style={{ padding: "10px" }}>
                        No returned items
                      </td>
                    </tr>
                  ) : (
                    returnedItems.map((item, i) => {
                      const unitCost =
                        Number(item.buying_price || item.price || 0);

                      return (
                        <tr key={i}>
                          <td style={{ padding: "6px" }}>
                            <strong>{item.item_name}</strong>
                          </td>
                          <td align="center">{item.return_qty}</td>
                          <td align="center">
                            {formatPrice(
                              unitCost,
                              currentCurrency,
                              false
                            )}
                          </td>
                          <td align="center">
                            {formatPrice(
                              item.return_qty * unitCost,
                              currentCurrency,
                              false
                            )}
                          </td>
                        </tr>
                      );
                    })
                  )}
                </tbody>
              </table>
            </td>
          </tr>

          {/* ================= TOTAL ================= */}
          <tr>
            <td
              colSpan={2}
              style={{
                textAlign: "right",
                paddingTop: "12px",
                fontWeight: "700",
              }}
            >
              Return Total:{" "}
              {formatPrice(returnTotal, currentCurrency, false)}
            </td>
          </tr>

          {/* ================= FOOTER ================= */}
          <tr>
            <td colSpan={2} style={{ paddingTop: "30px", fontSize: "11px" }}>
              <p>
                This document confirms returned goods against the original
                purchase.
              </p>
              <p>
                Processed by:{" "}
                {currentSession?.user?.full_name ||
                  currentSession?.user?.username}
              </p>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}
