"use client";

import React, {
  useEffect,
  useState,
  forwardRef,
  useImperativeHandle,
} from "react";
import { Table, Tag } from "antd";
import { jsPDF } from "jspdf";
import autoTable from "jspdf-autotable";
import { useFormattedPrice } from "@/app/utils/formatPrice";
import { useSiteContext } from "@/app/Context/SiteContext";
import { pageSize } from "@/app/utils/variables";
import {
  formatDateWithTime,
  formatTime,
} from "@/app/utils/formattedDateWithTime";
import { hexToRgbArray } from "@/app/utils/hexToRgbArray";



/* ---------- SalesReport Component ---------- */
const SalesReport = forwardRef(({ data = [], totalItems, brandData }, ref) => {
  const { currentPage, setCurrentPage, activeTheme } = useSiteContext();
  const { formatPrice } = useFormattedPrice();

  const [time, setTime] = useState(new Date());
  useEffect(() => {
    const timer = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(timer);
  }, []);

  const formattedTime = time.toLocaleTimeString("en-US", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: true,
    timeZone: brandData?.time_zone || "Asia/Dubai",
  });

  /* ---------- Exposed PDF Function ---------- */
  const downloadPDF = () => {
    if (!data || data.length === 0) return;

    const doc = new jsPDF("landscape", "pt", "a4");
    doc.setFontSize(18);
    doc.text("SALES REPORT", 40, 40);

    doc.setFontSize(10);
    doc.text(
      `Generated on: ${formatDateWithTime(
        new Date(),
        brandData
      )} - ${formattedTime}`,
      40,
      55
    );

    const columns = [
      { header: "Invoice No", dataKey: "invoice_number" },
      { header: "Customer", dataKey: "customer_name" },
      { header: "Date", dataKey: "invoice_date" },
      { header: "Currency", dataKey: "currency" },
      { header: "Total", dataKey: "total_invoice_value" },
      { header: "Credited", dataKey: "credited" },
      { header: "Outstanding", dataKey: "outstanding" },
      { header: "Profit", dataKey: "profit" },
      { header: "Status", dataKey: "status" },
    ];

    const rows = data.map((inv) => {
      const total = Number(inv.total_invoice_value || 0);
      const balance = Number(inv.balance_amount || 0);
      const credited = total - balance;
      const profit = Number(inv.profit || 0);

      return {
        invoice_number: inv.invoice_number,
        customer_name: inv.customer_name,
        invoice_date: `${formatDateWithTime(
          inv.invoice_date,
          brandData
        )} ${formatTime(brandData?.time_zone, inv.created_at)}`,
        currency: inv.currency,
        total_invoice_value: formatPrice(total, inv.currency, true),
        credited: formatPrice(credited, inv.currency, true),
        outstanding:
          balance > 0 ? formatPrice(balance, inv.currency, true) : "-",
        profit: formatPrice(profit, inv.currency, true),
        status: inv.status,
      };
    });

    autoTable(doc, {
      startY: 80,
      columns,
      body: rows,
      styles: { fontSize: 9, cellPadding: 4 },
      headStyles: {
        fillColor: brandColor || brandData?.primary_color || "#eee"
          ? hexToRgbArray(activeTheme.primary)
          : [41, 128, 185],
        textColor: 255,
      },
    });

    // Summary
    const totals = data.reduce((acc, inv) => {
      const cur = inv.currency || "USD";
      if (!acc[cur])
        acc[cur] = { total: 0, credited: 0, outstanding: 0, profit: 0 };
      const total = Number(inv.total_invoice_value) || 0;
      const bal = Number(inv.balance_amount) || 0;
      const credited = total - bal;
      acc[cur].total += total;
      acc[cur].credited += credited;
      acc[cur].outstanding += bal;
      acc[cur].profit += Number(inv.profit || 0);
      return acc;
    }, {});

    let y = doc.lastAutoTable.finalY + 30;
    doc.setFontSize(12);
    doc.text("Summary by Currency", 40, y);
    y += 20;

    Object.entries(totals).forEach(([cur, t]) => {
      doc.setFontSize(10);
      doc.text(`${cur} Totals:`, 60, y);
      y += 15;
      doc.text(`Total: ${formatPrice(t.total, cur, true)}`, 80, y);
      y += 15;
      doc.text(`Credited: ${formatPrice(t.credited, cur, true)}`, 80, y);
      y += 15;
      doc.setTextColor(200, 0, 0);
      doc.text(`Outstanding: ${formatPrice(t.outstanding, cur, true)}`, 80, y);
      y += 15;
      doc.setTextColor(40);
      doc.text(`Profit: ${formatPrice(t.profit, cur, true)}`, 80, y);
      y += 25;
    });

    doc.save(`sales_report_${Date.now()}.pdf`);
  };

  // Expose function to parent
  useImperativeHandle(ref, () => ({ downloadPDF }));

  /* ---------- Table Config ---------- */
  const columns = [
    { title: "Invoice No", dataIndex: "invoice_number", key: "invoice_number" },
    { title: "Customer", dataIndex: "customer_name", key: "customer_name" },
    {
      title: "Invoice Date",
      dataIndex: "invoice_date",
      key: "invoice_date",
      render: (date, record) =>
        `${formatDateWithTime(date, brandData)} - ${formatTime(
          brandData?.time_zone,
          record.created_at
        )}`,
    },
    {
      title: "Total",
      dataIndex: "total_invoice_value",
      key: "total_invoice_value",
      render: (val, record) => formatPrice(val, record.currency),
    },
    {
      title: "Balance",
      dataIndex: "balance_amount",
      key: "balance_amount",
      render: (val, record) =>
        val > 0 ? (
          <span style={{ color: "red" }}>
            {formatPrice(val, record.currency)}
          </span>
        ) : (
          "-"
        ),
    },
    {
      title: "Profit",
      dataIndex: "profit",
      key: "profit",
      render: (val, record) => <span>{formatPrice(val, record.currency)}</span>,
    },
    {
      title: "Outstanding",
      key: "outstanding",
      render: (_, record) =>
        formatPrice(Number(record.balance_amount || 0), record.currency),
    },
    {
      title: "Status",
      dataIndex: "status",
      key: "status",
      render: (status) => {
        const color =
          status === "Paid"
            ? "green"
            : status === "Partially Paid"
              ? "orange"
              : "red";
        return <Tag color={color}>{status}</Tag>;
      },
    },
  ];

  const totalsByCurrency = data.reduce((acc, item) => {
    const cur = item.currency || "USD";
    if (!acc[cur])
      acc[cur] = { total: 0, profit: 0, credited: 0, outstanding: 0 };
    const total = Number(item.total_invoice_value) || 0;
    const bal = Number(item.balance_amount) || 0;
    acc[cur].total += total;
    acc[cur].profit += Number(item.profit) || 0;
    acc[cur].credited += total - bal;
    acc[cur].outstanding += bal;
    return acc;
  }, {});

  return (
    <div className="table-container">
      <Table
        size="small"
        dataSource={data}
        columns={columns}
        rowKey="invoice_id"
        rowClassName={() => "crm-row"}
        scroll={{ x: true }}
        className="crm-table"
        bordered
        pagination={{
          current: currentPage,
          pageSize: pageSize,
          total: totalItems,
          onChange: (page) => setCurrentPage(page),
          showSizeChanger: false,
        }}
        summary={() => (
          <Table.Summary fixed>
            {Object.entries(totalsByCurrency).map(([cur, totals]) => (
              <React.Fragment key={cur}>
                <Table.Summary.Row>
                  <Table.Summary.Cell index={0} colSpan={2}>
                    <b>Totals ({cur})</b>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={3}>
                    <b>{formatPrice(totals.total, cur)}</b>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={4}>
                    <b>{formatPrice(totals.profit, cur)}</b>
                  </Table.Summary.Cell>
                </Table.Summary.Row>

                <Table.Summary.Row>
                  <Table.Summary.Cell
                    index={0}
                    colSpan={3}
                  ></Table.Summary.Cell>
                  <Table.Summary.Cell index={3} colSpan={2}>
                    <div
                      style={{
                        backgroundColor: "#d4edda",
                        padding: "4px",
                        textAlign: "center",
                        borderRadius: "2px",
                      }}
                    >
                      <b>
                        Credited Amount: {formatPrice(totals.credited, cur)}
                      </b>
                    </div>
                  </Table.Summary.Cell>
                  {totals.outstanding > 0 && (
                    <Table.Summary.Cell index={5} colSpan={2}>
                      <div
                        style={{
                          backgroundColor: "#f8d7da",
                          padding: "4px",
                          textAlign: "center",
                          borderRadius: "2px",
                        }}
                      >
                        <b>
                          Outstanding Amount:{" "}
                          {formatPrice(totals.outstanding, cur)}
                        </b>
                      </div>
                    </Table.Summary.Cell>
                  )}
                </Table.Summary.Row>
              </React.Fragment>
            ))}
          </Table.Summary>
        )}
      />
    </div>
  );
});

SalesReport.displayName = "SalesReport";
export default SalesReport;
