import { useState, useRef, useEffect } from "react";
import jsPDF from "jspdf";
import Header from "./Header";
import Section from "./Section";
import DataTable from "./DataTable";
import FormButton from "./FormButton";
import { useAuth } from "../../hooks/useAuth";
import { Navberbar } from "./Navberbar";
export default function Home() {
  const [company, setCompany] = useState("plutontech");
  const [date, setDate] = useState(
    () => new Date().toISOString().split("T")[0]
  );
  const [enquiries, setEnquiries] = useState<string[][]>([]);
  const [quotes, setQuotes] = useState<string[][]>([]);
  const [works, setWorks] = useState<string[][]>([]);
  const [invoices, setInvoices] = useState<string[][]>([]);
  const [payments, setPayments] = useState<string[][]>([]);
  const [totalMarketing, setTotalMarketing] = useState<string[][]>([]);

  const [submitted, setSubmitted] = useState(false);
  const [exported, setExported] = useState(false);
  const [summaryData, setSummaryData] = useState<{
    company: string;
    date: string;
    payments: string[][];
    totalMarketing: string[][];
    enquiries: string[][];
    quotes: string[][];
    works: string[][];
    invoices: string[][];
  } | null>(null);

  const previewRef = useRef<HTMLDivElement>(null);

  const { getProfile } = useAuth();
  const [profile, setProfile] = useState<any>(null);
  const [profileError, setProfileError] = useState<string | null>(null);

  useEffect(() => {
    const prof = getProfile();
    if (!prof || !prof.id) {
      setProfileError("Could not get current profile. Please log in again.");
      setProfile(null);
    } else {
      setProfile(prof);
      setProfileError(null);
    }
  }, []); // Remove getProfile dependency since it's now stable

  const handleSubmit = async () => {
    const data = {
      profiles: profile.id,
      profiles_name: profile.name,
      date,
      company_title: company,
      enquiries: enquiries.map(([customer_id, type_of_work, descriptions]) => ({
        customer_name: customer_id,
        type_of_work,
        descriptions,
      })),
      quotes_submitted: quotes.map(
        ([customer_id, type_of_work, Quote_no, quote_amount, remarks]) => ({
          customer_name: customer_id,
          type_of_work,
          Quote_no,
          quote_amount,
          remarks,
        })
      ),
      confirmed_work: works.map(
        ([customer_id, type_of_work, so_no, so_amount, remarks]) => ({
          customer_name: customer_id,
          type_of_work,
          so_no,
          so_amount,
          remarks,
        })
      ),
      invoiced_work: invoices.map(
        ([customer_id, type_of_work, invoice_no, invoice_amount, remarks]) => ({
          customer_name: customer_id,
          type_of_work,
          invoice_no,
          invoice_amount,
          remarks,
        })
      ),
      payments_collected: payments.map(
        ([customer_id, invoice_no, rcvd_amount, remarks]) => ({
          customer_name: customer_id,
          invoice_no,
          rcvd_amount,
          remarks,
        })
      ),
      total_marketing: totalMarketing.map(
        ([client_name, status, email, contact_no]) => ({
          client_name,
          status,
          email,
          contact_no,
        })
      ),
    };

    try {
      const res = await fetch(
        `${import.meta.env.VITE_BACKEND_URL}/api/employer/create`,
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(data),
        }
      );

      if (!res.ok) {
        let errorMsg = "Failed to submit";
        try {
          const errJson = await res.json();
          if (
            errJson &&
            errJson.profiles &&
            Array.isArray(errJson.profiles) &&
            errJson.profiles.length > 0
          ) {
            errorMsg = `Profile: ${errJson.profiles[0]}`;
            setProfileError(errorMsg);
          }
        } catch (e) {}
        throw new Error(errorMsg);
      }

      alert("Report submitted successfully!");
      setSubmitted(true);
      setExported(false);

      setSummaryData({
        company,
        date,
        payments: payments,
        totalMarketing: totalMarketing,
        enquiries: enquiries,
        quotes: quotes,
        works: works,
        invoices: invoices,
      });

      setEnquiries([["", "", ""]]);
      setQuotes([["", "", "", "", ""]]);
      setWorks([["", "", "", "", ""]]);
      setInvoices([["", "", "", "", ""]]);
      setPayments([["", "", "", ""]]);
      setTotalMarketing([["", "", "", ""]]);

      localStorage.removeItem("saved-enquiry-table");
      localStorage.removeItem("saved-quotation-table");
      localStorage.removeItem("saved-work-table");
      localStorage.removeItem("saved-invoice-table");
      localStorage.removeItem("saved-payment-table");
      localStorage.removeItem("saved-total-marketing-table");
    } catch (err) {
      console.error(err);
      alert("Submission failed. Check console for details.");
    }
  };

  const handleDownloadPDF = async () => {
    if (!summaryData) return;

    // Landscape A4 (correct dimensions without swapping)
    const pdf = new jsPDF("p", "mm", "a4");
    const pdfHeight = pdf.internal.pageSize.getHeight();
    const pdfWidth = pdf.internal.pageSize.getWidth();
    

    // Colors
    const primaryColor = "#5b81bf"; // Blue color for headers
    const secondaryColor = "#F5F5F5";

    // ---------------- HEADER ----------------
    pdf.setFillColor(primaryColor);
    pdf.rect(0, 0, pdfWidth, 20, "F");
    pdf.setTextColor("#FFFFFF");
    pdf.setFont("helvetica", "bold");
    pdf.setFontSize(12);

    // Header title
    pdf.text("DAILY REPORT SUMMARY", pdfWidth / 2, 13, {
      align: "center",
      angle: 0,
    });

    // Report details
    pdf.setFontSize(9);
    pdf.setFont("helvetica", "normal");
    pdf.setTextColor("#000000");
    let startY = 24;
    pdf.text(
      `COMPANY: ${summaryData.company?.toUpperCase?.() ?? ""}` as string,
      14,
      startY + 2,
      { angle: 0 }
    );
    pdf.text(
      `DATE: ${String(summaryData.date).toUpperCase()}`,
      pdfWidth - 50,
      startY + 2,
      { angle: 0 }
    );
    startY += 6;
    pdf.text(
      `PROFILE: ${
        profile?.name ? String(profile.name).toUpperCase() : "N/A"
      }` as string,
      14,
      startY,
      { angle: 0 }
    );
    startY += 10;

    // ---------------- TABLE RENDER FUNCTION ----------------
    const renderTable = (
      title: string,
      headers: string[],
      rows: string[][],
      y: number
    ): number => {
      if (
        !rows?.length ||
        (rows.length === 1 && rows[0].every((cell: string) => cell === ""))
      ) {
        return y;
      }

      const headersUpper = headers.map((h: string) => h.toUpperCase());
      const rowsUpper = rows.map((row: string[]) =>
        row.map((cell: string) =>
          cell && cell.trim() ? cell.toUpperCase() : "-"
        )
      );

      // Check if we need a new page for the entire table (title + content)
      const titleHeight = 6; // Space for title
      const headerHeight = 7; // Space for table header
      const minRowHeight = 7; // Minimum row height
      const estimatedTableHeight = titleHeight + headerHeight + (rowsUpper.length * minRowHeight);
      
      // If not enough space for the entire table, start on a new page
      if (y + estimatedTableHeight > pdfHeight - 20) {
        pdf.addPage();
        y = 20;
      }

      // Add table title
      pdf.setFontSize(10);
      pdf.setTextColor(primaryColor);
      pdf.setFont("helvetica", "bold");
      pdf.text(title.toUpperCase(), 14, y, { angle: 0 });
      y += 3;

      // Spacing under the title
      y += 5; // increased spacing for better visual separation

      // Header row - Calculate content-based column widths
      const tableX = 14;
      const maxTableWidth = pdfWidth - 28; // Maximum available width
      const colCount = headersUpper.length;
      
      // Define minimum and preferred widths for different column types
      const getColumnWidth = (header: string, index: number) => {
        const isAmountColumn = header.includes("AMOUNT") || header.includes("VALUE");
        const isNameColumn = header.includes("NAME") || header.includes("CLIENT");
        const isEmailColumn = header.includes("EMAIL");
        const isStatusColumn = header.includes("STATUS");
        const isContactColumn = header.includes("CONTACT") || header.includes("NO");
        const isTypeColumn = header.includes("TYPE") || header.includes("WORK");
        const isDescriptionColumn = header.includes("DESCRIPTION");
        const isRemarksColumn = header.includes("REMARKS");
        const isInvoiceNoColumn = header.includes("INVOICE NO");
        
        if (isAmountColumn) return 25; // Amount columns need less space
        if (isNameColumn) return 40; // Client names need more space
        if (isEmailColumn) return 55; // Email addresses need more space
        if (isContactColumn) return 30; // Contact numbers need moderate space
        if (isTypeColumn) return 45; // Work types need more space
        if (isDescriptionColumn) return 50; // Descriptions need most space
        if (isRemarksColumn) return 55; // Remarks need moderate space
        if (isStatusColumn) return 45; // Remarks need moderate space
        if (isInvoiceNoColumn) return 45; // Remarks need moderate space
        
        console.log("h",index);

        
        return 35; // Default width for other columns
      };
      
      const colWidths = headersUpper.map((header, index) => {
        // TEMPFIX DONT DELETE
        if(header.includes("INVOICE NO") && index === 1){
        return 45;
        }
        else if(header.includes("AMOUNT") && index ===2){
          return 55
        }

        return getColumnWidth(header, index)});
      const totalRequiredWidth = colWidths.reduce((sum, width) => sum + width, 0);
      
      // If total required width is less than max width, use required width
      // If it exceeds max width, scale down proportionally
      const tableWidth = Math.min(totalRequiredWidth, maxTableWidth);
      const scaleFactor = tableWidth / totalRequiredWidth;
      
      // Scale column widths if needed
      const finalColWidths = colWidths.map(width => width * scaleFactor);

      // Header styling
      pdf.setFillColor(primaryColor);
      pdf.setTextColor("#FFFFFF");
      pdf.setFontSize(8);
      pdf.rect(tableX, y, tableWidth, 7, "F");
      
      // Draw individual header cell borders with consistent border width
      pdf.setDrawColor(0);
      pdf.setLineWidth(0.5);
      let currentX = tableX;
      
      // Draw borders for each header cell
      for (let k = 0; k < colCount; k++) {
        const cellWidth = finalColWidths[k];
        pdf.rect(currentX, y, cellWidth, 7, "S");
        currentX += cellWidth;
      }
      
      headersUpper.forEach((h: string, i: number) => {
        const isAmountColumn = h.includes("AMOUNT") ;
        const isInvoiceValueColumn = h.includes("INVOICE VALUE");
        const isSoNO = h.includes("SO No");
        console.log("h",h);
        let x;
        
        // Calculate x position based on accumulated column widths
        let accumulatedWidth = 0;
        for (let j = 0; j < i; j++) {
          accumulatedWidth += finalColWidths[j];
        }
        
        if (isAmountColumn) {
          // Right align for amount columns - position text near right edge
          x = tableX + accumulatedWidth + finalColWidths[i] - 3;
        } 
        else if (isInvoiceValueColumn) {
          // Right align for amount columns - position text near right edge
          x = tableX + accumulatedWidth + finalColWidths[i] - 23;
        } 
        else if (isSoNO) {
          // Right align for amount columns - position text near right edge
          x = tableX + accumulatedWidth + finalColWidths[i] - 25;
        } 
        else {
          // Left align for other columns
          x = tableX + accumulatedWidth + 3;
        }
        
        pdf.text(h, x, y + 5.5, { 
          align: isAmountColumn ? "right" : "left", 
          angle: 0 
        });
      });

      // Rows with wrapping
      y += 7;
      pdf.setFontSize(8);
      const lineHeight = 3;
      rowsUpper.forEach((row: string[], i: number) => {
        const wrappedCells = row.map((cell: string, j: number) =>
          pdf.splitTextToSize(cell || "-", finalColWidths[j] - 6)
        );
        const maxLines = Math.max(
          1,
          ...wrappedCells.map((c: any) => (Array.isArray(c) ? c.length : 1))
        );
        const rowHeight = Math.max(7, maxLines * lineHeight + 3);

        // New page if needed - check if this row will fit
        if (y + rowHeight > pdfHeight - 15) {
          pdf.addPage();
          y = 20;
          
          // Redraw the table header on new page
          pdf.setFillColor(primaryColor);
          pdf.setTextColor("#FFFFFF");
          pdf.setFontSize(8);
          pdf.rect(tableX, y, tableWidth, 7, "F");
          
          // Draw individual header cell borders on new page with consistent border width
          pdf.setDrawColor(0);
          pdf.setLineWidth(0.5);
          let currentX = tableX;
          
          // Draw borders for each header cell
          for (let k = 0; k < colCount; k++) {
            const cellWidth = finalColWidths[k];
            pdf.rect(currentX, y, cellWidth, 7, "S");
            currentX += cellWidth;
          }
          
          // Redraw header text with proper alignment
          headersUpper.forEach((h: string, i: number) => {
            const isAmountColumn = h.includes("AMOUNT");
            const isInvoiceValueColumn = h.includes("INVOICE VALUE");
            const isSoNO = h.includes("SO No");
            let x;
            
            // Calculate x position based on accumulated column widths
            let accumulatedWidth = 0;
            for (let j = 0; j < i; j++) {
              accumulatedWidth += finalColWidths[j];
            }
            
            if (isAmountColumn) {
              // Right align for amount columns - position text near right edge
              x = tableX + accumulatedWidth + finalColWidths[i] - 3;
            } 
            else if (isInvoiceValueColumn) {
              // Right align for amount columns - position text near right edge
              x = tableX + accumulatedWidth + finalColWidths[i] - 23;
            } 
            else if (isSoNO) {
              // Right align for amount columns - position text near right edge
              x = tableX + accumulatedWidth + finalColWidths[i] - 25;
            } 
            else {
              // Left align for other columns
              x = tableX + accumulatedWidth + 3;
            }
            
            pdf.text(h, x, y + 5.5, { 
              align: isAmountColumn ? "right" : "left", 
              angle: 0 
            });
          });
          y += 7;
        }

        const fill = i % 2 === 0 ? secondaryColor : "#FFFFFF";
        pdf.setFillColor(fill);
        pdf.setTextColor("#000000");
        pdf.rect(tableX, y, tableWidth, rowHeight, "F");

        // Draw individual cell borders with consistent border width
        pdf.setDrawColor(0);
        pdf.setLineWidth(0.5);
        let currentX = tableX;
        
        // Draw borders for each cell in the row
        for (let k = 0; k < colCount; k++) {
          const cellWidth = finalColWidths[k];
          pdf.rect(currentX, y, cellWidth, rowHeight, "S");
          currentX += cellWidth;
        }

        // Cell text
        row.forEach((_: string, j: number) => {
          const lines = wrappedCells[j] as string[];
          const isAmountColumn = headersUpper[j].includes("AMOUNT") || headersUpper[j].includes("VALUE");

          let tx, ty = y + 4.5;
          


          // Calculate x position based on accumulated column widths
          let accumulatedWidth = 0;
          for (let k = 0; k < j; k++) {
            accumulatedWidth += finalColWidths[k];
          }
          
          if (isAmountColumn) {
            // Right align for amount columns - position text near right edge
            tx = tableX + accumulatedWidth + finalColWidths[j] - 3;
          } else {
            // Left align for other columns
            tx = tableX + accumulatedWidth + 3;
          }
          
          lines.forEach((ln: string) => {
            pdf.text(ln, tx, ty, { 
              align: isAmountColumn ? "right" : "left", 
              angle: 0 
            });
            ty += lineHeight;
          });
        });

        y += rowHeight;
      });

      return y + 8; // increased spacing below each table to prevent merging with next title
    };

    // ---------------- ADD ALL TABLES ----------------
    startY = renderTable(
      "Payments Collected Summary",
      ["Client Name", "Invoice No", "Amount", "Remarks"],
      summaryData.payments,
      startY
    );
    startY = renderTable(
      "Marketing Summary",
      ["Client Name", "Status", "Email", "Contact No"],
      summaryData.totalMarketing,
      startY
    );
    startY = renderTable(
      "Enquiries Summary",
      ["Client Name", "Type of Work", "Description"],
      summaryData.enquiries,
      startY
    );
    startY = renderTable(
      "Quotes Submitted Summary",
      ["Client Name", "Type of Work", "Quote No", "Amount", "Remarks"],
      summaryData.quotes,
      startY
    );
    startY = renderTable(
      "Confirmed Work Summary",
      ["Client Name", "Type of Work", "SO No", "SO Value", "Remarks"],
      summaryData.works,
      startY
    );
    startY = renderTable(
      "Invoiced Work Summary",
      ["Client Name", "Type of Work", "Invoice No", "Invoice Value", "Remarks"],
      summaryData.invoices,
      startY
    );

  pdf.save(`${date}-${company}-DailyReport.pdf`);
   

    setExported(true);
    setSummaryData(null);
  };
  // ---------------- PREVIEW RENDER TABLE ----------------
  const renderTable = (title: string, headers: string[], rows: string[][]) => {
    if (
      !rows?.length ||
      (rows.length === 1 && rows[0].every((cell: string) => cell === ""))
    ) {
      return null;
    }
    return (
      <div style={{ marginBottom: "30px", width: "100%", boxSizing: "border-box" }}>
        <h3
          style={{
            background: "#f5f5f5",
            padding: "12px 20px",
            borderRadius: "8px 8px 0 0",
            color: "#333",
            fontSize: "18px",
            margin: 0,
            border: "1px solid #ddd",
            textTransform: "uppercase",
            borderBottom: "none",
          }}
        >
          {title}
        </h3>
        <table
          style={{
            width: "100%",
            tableLayout: "fixed",
            borderCollapse: "separate",
            borderSpacing: 0,
            background: "#fff",
            border: "1px solid #ddd",
            borderRadius: "0 0 8px 8px",
            overflow: "hidden",
            fontSize: "14px",
            textTransform: "uppercase",
            minWidth: "100%",
            boxSizing: "border-box",
          }}
        >
          <thead style={{ background: "#fafafa" }}>
            <tr>
              {/* <th
                style={{
                  borderBottom: "1px solid #ddd",
                  padding: "12px",
                  textAlign: "left",
                  fontWeight: "bold",
                  color: "#444",
                }}
              >
                S.No
              </th> */}
              {headers.map((h: string, i: number) => (
                <th
                  key={i}
                  style={{
                    borderBottom: "1px solid #ddd",
                    padding: "16px 20px",
                    textAlign: "left",
                    fontWeight: "bold",
                    color: "#444",
                    width: `${100 / headers.length}%`,
                    wordWrap: "break-word",
                    boxSizing: "border-box",
                    minWidth: 0,
                    overflowWrap: "break-word",
                  }}
                >
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.map((row: string[], i: number) => (
              <tr
                key={i}
                style={{
                  background: i % 2 === 0 ? "#fdfdfd" : "#f7f7f7",
                }}
              >
                {/* <td
                  style={{
                    borderBottom: "1px solid #eee",
                    padding: "12px",
                    color: "#555",
                  }}
                >
                  {i + 1}
                </td> */}
                {row.map((cell: string, j: number) => (
                  <td
                    key={j}
                    style={{
                      borderBottom: "1px solid #eee",
                      padding: "16px 20px",
                      color: "#555",
                      width: `${100 / headers.length}%`,
                      wordWrap: "break-word",
                      boxSizing: "border-box",
                      minWidth: 0,
                      overflowWrap: "break-word",
                    }}
                  >
                    {cell}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  };

  return (
    <div>
      <Header />

      <Navberbar />

      {profileError && (
        <div style={{ color: "red", marginBottom: 16 }}>{profileError}</div>
      )}

      <Section label="REPORT DATE">
        <div className="flex flex-row gap-4 w-[50%]">
          <input
            type="date"
            id="report-date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
          />
          <select
            id="company-dropdown"
            value={company}
            onChange={(e) => setCompany(e.target.value)}
          >
            <option value="">SELECT COMPANY</option>
            <option value="PLUTON ADVERTISING">PLUTON ADVERTISING</option>
            <option value="ORYXMEDIA">ORYXMEDIA</option>
          </select>
        </div>
      </Section>

      <Section label="PAYMENT COLLECTION SUMMARY">
        <DataTable
          id="payment-table"
          headers={["CLIENT NAME", "INVOICE NO", "AMOUNT", "REMARKS"]}
          onChange={setPayments}
        />
      </Section>

      <Section label="MARKETING SUMMARY">
        <DataTable
          id="total-marketing-table"
          headers={["CLIENT NAME", "STATUS", "EMAIL", "CONTACT NO"]}
          onChange={setTotalMarketing}
        />
      </Section>

      <Section label="ENQUIRIES / SITE VISIT SUMMARY">
        <DataTable
          id="enquiry-table"
          headers={["CLIENT NAME", "TYPE OF WORK", "DESCRIPTION"]}
          onChange={setEnquiries}
        />
      </Section>

      <Section label="QUOTATION CREATED SUMMARY">
        <DataTable
          id="quotation-table"
          headers={[
            "CLIENT NAME",
            "TYPE OF WORK",
            "QUOTE NO",
            "AMOUNT",
            "REMARKS",
          ]}
          onChange={setQuotes}
        />
      </Section>

      <Section label="WORK CONFIRMED (SO CREATED) SUMMARY">
        <DataTable
          id="work-table"
          headers={[
            "CLIENT NAME",
            "TYPE OF WORK",
            "SO NO",
            "SO VALUE",
            "REMARKS",
          ]}
          onChange={setWorks}
        />
      </Section>

      <Section label="INVOICE CREATED SUMMARY">
        <DataTable
          id="invoice-table"
          headers={[
            "CLIENT NAME",
            "TYPE OF WORK",
            "INVOICE NO",
            "INVOICE VALUE",
            "REMARKS",
          ]}
          onChange={setInvoices}
        />
      </Section>

      <FormButton
        text="SUBMIT REPORT"
        variant="primary"
        onClick={handleSubmit}
      />

      {submitted && summaryData && !exported && (
        <>
          <div style={{ marginTop: 20 }}>
            <FormButton
              text="Export PDF"
              variant="info"
              onClick={handleDownloadPDF}
            />
          </div>

          <div
            ref={previewRef}
            style={{
              background: "#ffffff",
              padding: "30px",
              borderRadius: "10px",
              boxShadow: "0 0 10px rgba(0,0,0,0.1)",
              fontFamily: "'Helvetica Neue', Arial, sans-serif",
              lineHeight: 1.6,
              marginTop: 20,
            }}
          >
            <div style={{ textAlign: "center", marginBottom: "20px" }}>
              <h2
                style={{
                  fontSize: "28px",
                  margin: 0,
                  fontWeight: "bold",
                  color: "#333",
                }}
              >
                Daily Report Summary
              </h2>
              <p style={{ fontSize: "16px", margin: "4px 0", color: "#555" }}>
                <strong>Company:</strong> {summaryData.company}
              </p>
              <p style={{ fontSize: "16px", margin: "4px 0", color: "#555" }}>
                <strong>Date:</strong> {summaryData.date}
              </p>
              <p style={{ fontSize: "16px", margin: "4px 0", color: "#555" }}>
                <strong>Profile:</strong> {profile.name}
              </p>
            </div>

            {renderTable(
              "Payments Collected",
              ["Client Name", "Invoice No", "Amount", "Remarks"],
              summaryData.payments
            )}
            {renderTable(
              "Total Marketing",
              ["Client Name", "Status", "Email", "Contact No"],
              summaryData.totalMarketing
            )}
            {renderTable(
              "Enquiries",
              ["Client Name", "Type of Work", "Description"],
              summaryData.enquiries
            )}
            {renderTable(
              "Quotes Submitted",
              ["Client Name", "Type of Work", "Quote No", "Amount", "Remarks"],
              summaryData.quotes
            )}
            {renderTable(
              "Confirmed Work",
              ["Client Name", "Type of Work", "SO No", "SO Value", "Remarks"],
              summaryData.works
            )}
            {renderTable(
              "Invoiced Work",
              [
                "Client Name",
                "Type of Work",
                "Invoice No",
                "Invoice Value",
                "Remarks",
              ],
              summaryData.invoices
            )}
          </div>
        </>
      )}

      {submitted && exported && (
        <div
          style={{
            marginTop: 20,
            textAlign: "center",
            color: "#28a745",
            fontWeight: "bold",
          }}
        >
          Report exported as PDF. Thank you!
        </div>
      )}
    </div>
  );
}
