"use client";

import { useSiteContext } from "@/app/Context/SiteContext";
import { formatPhone } from "@/app/utils/formatPhone";
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 DeliveryNotePDF({ brandSettings, form, settings }) {
  const {
    selectedCustomer,
    getCustomerDetails,
    lineItems,
    timeZone,
    customMessage,
    usedSerials,
  } = useSiteContext();



  const customerDetails = getCustomerDetails(form);

  const deliveryNoteNumber = form?.itemNumber || form?.deliverynote_number || "N/A";
  const lpoReference = form?.lpo_number || "N/A";

  const customerName =
    parseArrayField(form?.customer_info)?.[0]?.name ||
    "";
  const address =
    parseArrayField(form?.customer_info)?.[0]?.address_line_1 ||
    "";
  const mobile =
    parseArrayField(form?.customer_info)?.[0]?.phone ||
    "";
  const email =
    parseArrayField(form?.customer_info)?.[0]?.email ||
    "";

  const safeCustomMessage = Array.isArray(customMessage)
    ? customMessage
    : typeof customMessage === "object" && customMessage !== null
      ? Object.values(customMessage)
      : [];


  const items =
    parseArrayField(Array.isArray(lineItems) && lineItems.length > 0
      ? lineItems
      : form?.line_items ?? []);



  const safeLineItems = Array.isArray(items)
    ? parseArrayField(items).map((item) => {
      const match = safeCustomMessage.find(
        (msg) => msg.key === item.key || msg.item_id === item.item_id
      );



      const originalQty = Number(item.qty) || 0;
      const additionalQty = Number(match?.available) || 0;

      return {
        ...item,
        qty: originalQty + additionalQty,
        unit: match?.unit || item.unit,
      };
    })
    : [];




  const totalQty = safeLineItems.reduce((sum, item) => {
    const qty = parseFloat(item?.qty || 0);
    return sum + qty;
  }, 0);

  return (
    <div
      style={{
        fontFamily: "Arial, sans-serif",
        fontSize: "14px",
        padding: "20px",
        maxWidth: "100%",
        margin: "0 auto",
      }}
    >
      {/* Header */}
      <table
        style={{
          width: "100%",
          borderCollapse: "collapse",
          marginBottom: "10px",
        }}
      >
        <tbody>
          <tr>
            <td style={{ width: "60%", verticalAlign: "top", padding: "10px" }}>
              {brandSettings?.company_logo_color && (
                <img
                  src={`${apiUrl}/proxy?fileUrl=${frontEndUrl}${brandSettings?.company_logo_color}`}
                  alt="Company Logo"
                  style={{
                    width: "120px",
                    height: "120px",
                    objectFit: "contain",
                    display: "block",
                    marginBottom: "12px",
                  }}
                />
              )}

              <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>Website: {brandSettings?.website}</div>
              <div>Phone: {brandSettings?.phone}</div>
              <div>
                TRN: {brandSettings?.tax_vat_registration_number || "N/A"}
              </div>
            </td>

            <td
              style={{ width: "40%", verticalAlign: "top", textAlign: "right" }}
            >
              <div
                style={{
                  fontWeight: "700",
                  fontSize: "22px",
                  color: brandSettings?.primary_color,
                  textAlign: "right",
                  marginBottom: "10px",
                }}
              >
                DELIVERY NOTE
              </div>
              <table
                style={{
                  float: "right",
                  marginTop: "10px",
                  fontSize: "14px",
                  borderCollapse: "collapse",
                }}
              >
                <tbody>
                  <tr>
                    <td style={cellStyle}>DATE</td>
                    <td
                      style={{
                        ...cellStyle,
                        fontWeight: "bold",
                        whiteSpace: "nowrap",
                      }}
                    >
                      {formatDateWithTime(
                        form?.deliverynote_date,
                        brandSettings
                      )}
                    </td>
                  </tr>
                  <tr>
                    <td style={{ ...cellStyle, whiteSpace: "nowrap" }}>
                      DELIVERY NOTE #
                    </td>
                    <td style={{ ...cellStyle, fontWeight: "bold" }}>
                      {deliveryNoteNumber}
                    </td>
                  </tr>
                  <tr>
                    <td style={{ ...cellStyle, whiteSpace: "nowrap" }}>
                      CUSTOMER ID
                    </td>
                    <td style={{ ...cellStyle, fontWeight: "bold" }}>
                      {selectedCustomer?.customer_id ||
                        customerDetails?.customer_id ||
                        "N/A"}
                    </td>
                  </tr>
                  <tr>
                    <td style={{ ...cellStyle, whiteSpace: "nowrap" }}>
                      LPO REF
                    </td>
                    <td style={{ ...cellStyle, fontWeight: "bold" }}>
                      {lpoReference}
                    </td>
                  </tr>
                </tbody>
              </table>
            </td>
          </tr>
        </tbody>
      </table>

      {/* Ship To Section */}
      <table
        style={{
          width: "100%",
          borderCollapse: "collapse",
          marginTop: "20px",
          border: `solid thin ${brandSettings?.primary_color || "#000"}`,
        }}
      >
        <thead>
          <tr>
            <td
              style={{
                backgroundColor: brandSettings?.primary_color,
                color: "white",
                padding: "6px",
                fontWeight: "bold",
              }}
            >
              SHIP TO
            </td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={{ padding: "10px" }}>
              {customerName}
              <br />
              {address}
              <br />
              {formatPhone(mobile)}
              <br />
              {email}
            </td>
          </tr>
        </tbody>
      </table>

      {/* Items Table */}
      <table
        style={{
          border: `solid thin ${brandSettings?.primary_color || "#000"}`,
          width: "100%",
          borderCollapse: "collapse",
          marginTop: "20px",
        }}
        border="1"
      >
        <thead>
          <tr
            style={{
              backgroundColor: `${brandSettings?.primary_color || "#000"}`,
              color: "#fff",
            }}
          >
            <th style={{ ...thStyle, whiteSpace: "nowrap" }}>S NO.</th>
            <th style={thStyle}>ITEM DESCRIPTION</th>
            <th style={thStyle}>HSN/SKU</th>
            <th style={thStyle}>SERIAL</th>
            <th style={thStyle}>UNIT</th>
            <th style={thStyle}>QTY</th>
          </tr>
        </thead>

        <tbody>
          {safeLineItems.length ? (
            safeLineItems.map((item, index) => {
              //  Get serials from usedSerials
              const serialArray = usedSerials?.[item?.item_id] || [];
              let serialDisplay = serialArray.filter((s) => s && s.trim());

              //  Fallback: parse from form.serializationSerial
              if (
                (!serialDisplay || serialDisplay.length === 0) &&
                form?.serializationSerial
              ) {
                const regex = new RegExp(
                  `${item.item_name}\\(${item.item_id}\\): \\(([^)]*)\\)`,
                  "i"
                );
                const match = form.serializationSerial.match(regex);
                if (match && match[1]) {
                  serialDisplay = match[1].split(",").map((s) => s.trim());
                }
              }

              const formattedSerials =
                serialDisplay && serialDisplay.length > 0
                  ? serialDisplay.join(", ")
                  : "-";

              return (
                <tr key={index}>
                  <td style={{ ...tdStyle }}>{index + 1}</td>
                  <td style={{ ...tdStyle, width: "50%" }}>
                    {item?.item_name}
                  </td>
                  <td style={tdStyle}>{item?.sku || "N/A"}</td>
                  <td
                    style={{
                      ...tdStyle,
                      whiteSpace: "normal",
                      wordBreak: "break-word",
                    }}
                  >
                    {formattedSerials}
                  </td>
                  <td style={tdStyle}>{item?.unit || "N/A"}</td>
                  <td style={tdStyle}>{parseFloat(item?.qty || 0)}</td>
                </tr>
              );
            })
          ) : (
            <tr>
              <td
                colSpan="6"
                style={{ textAlign: "center", color: "red", padding: "10px" }}
              >
                No items available
              </td>
            </tr>
          )}
          <tr>
            <td
              colSpan="5"
              style={{
                textAlign: "right",
                fontWeight: "bold",
                borderTop: `1px solid ${brandSettings?.primary_color || "#000"}`,
                padding: "8px",
                color: brandSettings?.primary_color,
              }}
            >
              Total Qty
            </td>
            <td
              style={{
                ...tdStyle,
                border: `1px solid ${brandSettings?.primary_color || "#000"}`,
              }}
            >
              {totalQty}
            </td>
          </tr>
        </tbody>
      </table>

      {/* Terms and Conditions */}
      <table
        style={{
          width: "100%",
          borderCollapse: "collapse",
          marginTop: "20px",
          border: `solid thin ${brandSettings?.primary_color || "#000"}`,
        }}
      >
        <thead>
          <tr>
            <td
              style={{
                backgroundColor: brandSettings?.primary_color,
                color: "white",
                padding: "6px",
                fontWeight: "bold",
              }}
            >
              TERMS AND CONDITIONS
            </td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={borderedCellStyle}>
              <div
                className="overflow-hidden smallfont"
                dangerouslySetInnerHTML={{
                  __html:
                    form?.general_terms_conditions ||
                    form?.terms ||
                    settings?.terms_conditions ||
                    "",
                }}
              />
            </td>
          </tr>
        </tbody>
      </table>

      <p style={{ marginTop: "20px" }}>
        Items Received in Good Condition as described in the proposal.
      </p>

      <table style={{ width: "100%", marginTop: "20px" }}>
        <tbody>
          <tr>
            <td>
              Signature:
              <br />
              <br />
              Received by:
              <br />
              Designation:
            </td>
            <td style={{ textAlign: "right" }}>
              <br />
              <br />
              Company Stamp
            </td>
          </tr>
        </tbody>
      </table>

      <p
        style={{
          textAlign: "center",
          marginTop: "40px",
          fontStyle: "italic",
          fontSize: "12px",
        }}
      >
        This is not a tax invoice.
      </p>
    </div>
  );
}

// Styles
const cellStyle = {
  padding: "6px",
  border: "1px solid #000",
};

const borderedCellStyle = {
  padding: "10px",
  border: "1px solid #000",
};

const thStyle = {
  padding: "8px",
  textAlign: "left",
  border: "1px solid #000",
};

const tdStyle = {
  padding: "8px",
  textAlign: "left",
  border: "1px solid #000",
  whiteSpace: "nowrap",
};
