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() : "-"
        )
      );

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

      // CHECKOUT HERE THE SPACING OF THE TABLES - Change this value to adjust spacing between tables
      y += 3; // compact spacing under the title

      // Header row
      const tableX = 14;
      const tableWidth = pdfWidth - 28;
      const colCount = headersUpper.length;
      const colWidth = tableWidth / colCount;
      const colWidths = headersUpper.map(() => colWidth);

      // Header styling
      pdf.setFillColor(primaryColor);
      pdf.setTextColor("#FFFFFF");
      pdf.setFontSize(8);
      pdf.rect(tableX, y, tableWidth, 7, "F");
      
      // Draw header borders
      pdf.setDrawColor(0);
      pdf.rect(tableX, y, tableWidth, 7, "S");
      
      headersUpper.forEach((h: string, i: number) => {
        const isAmountColumn = h.includes("AMOUNT") || h.includes("VALUE");
        let x;
        
        if (isAmountColumn) {
          // Right align for amount columns - position text near right edge
          x = tableX + (i + 1) * colWidths[i] - 3;
        } else {
          // Left align for other columns
          x = tableX + i * colWidths[i] + 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 || "-", colWidths[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
        if (y + rowHeight > pdfHeight - 15) {
          pdf.addPage();
          y = 20;
          pdf.setFillColor(primaryColor);
          pdf.setTextColor("#FFFFFF");
          pdf.rect(tableX, y, tableWidth, 7, "F");
          
          // Draw header borders on new page
          pdf.setDrawColor(0);
          pdf.rect(tableX, y, tableWidth, 7, "S");
          
          headersUpper.forEach((h: string, i: number) => {
            const isAmountColumn = h.includes("AMOUNT") || h.includes("VALUE");
            let x;
            
            if (isAmountColumn) {
              // Right align for amount columns - position text near right edge
              x = tableX + (i + 1) * colWidths[i] - 3;
            } else {
              // Left align for other columns
              x = tableX + i * colWidths[i] + 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 row borders
        pdf.setDrawColor(0);
        pdf.rect(tableX, y, tableWidth, rowHeight, "S");
        
        // Draw vertical column borders
        for (let k = 1; k < colCount; k++) {
          const vx = tableX + k * colWidth;
          pdf.line(vx, y, vx, y + rowHeight);
        }
        
        // Draw horizontal row border
        pdf.line(tableX, y + rowHeight, tableX + tableWidth, y + rowHeight);

        // 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;
          
          if (isAmountColumn) {
            // Right align for amount columns - position text near right edge
            tx = tableX + (j + 1) * colWidths[j] - 3;
          } else {
            // Left align for other columns
            tx = tableX + j * colWidths[j] + 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>
  );
}
