"use client";
import { formatQty, productLabel } from "@/lib/product-unit";

import { OrderStatusBadge as StatusBadge } from "@/components/order-status-badge";

import { displayValue, formatDate, statusLabel } from "@/lib/display-format";

import { useState, useMemo } from "react";
import {
  ChevronLeft,
  ChevronRight,
  Download,
  FileText,
  Package,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";
import type { MisReportOrderDto, MisReportSummaryDto, MisReportByCompanyDto, MisReportByProductDto } from "../dtos/mis-reporting.dto";

// ============================================
// Constants
// ============================================

const PAGE_SIZE = 10;


// ============================================
// Date Formatter
// ============================================



// ============================================
// Download CSV Helper
// ============================================

function downloadCSV(orders: MisReportOrderDto[]) {
  const headers = [
    "Order Number",
    "Company",
    "Community",
    "Status",
    "Total Items",
    "Total Quantity",
    "Products",
    "Order Date",
  ];

  const rows = orders.map((o) => [
    o.orderNumber,
    o.companyName,
    o.departmentName,
    statusLabel(o.status),
    o.totalItems.toString(),
    formatQty(o.totalQuantity),
    o.productNames.map((name, index) => productLabel(name, o.productUnits?.[index])).join("; "),
    formatDate(o.createdAt),
  ]);

  const csvContent = [headers, ...rows]
    .map((row) =>
      row.map((cell) => `"${displayValue(cell).replace(/"/g, '""')}"`).join(",")
    )
    .join("\n");

  const blob = new Blob(["\uFEFF", csvContent], { type: "text/csv;charset=utf-8;" });
  const url = URL.createObjectURL(blob);
  const link = document.createElement("a");
  link.href = url;
  link.download = "mis-report.csv";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

// ============================================
// Download PDF Helper
// ============================================

function downloadPDF(
  orders: MisReportOrderDto[],
  summary: MisReportSummaryDto | null,
  ordersByCompany: MisReportByCompanyDto[],
  ordersByProduct: MisReportByProductDto[]
) {
  const doc = new jsPDF("landscape", "mm", "a4");
  const pageWidth = doc.internal.pageSize.getWidth();
  const margin = 14;
  let y = margin;

  // --- Title ---
  doc.setFillColor(23, 37, 84); // navy-900
  doc.rect(0, 0, pageWidth, 28, "F");
  doc.setTextColor(255, 255, 255);
  doc.setFontSize(18);
  doc.setFont("helvetica", "bold");
  doc.text("MIS Report", margin, 18);
  doc.setFontSize(10);
  doc.setFont("helvetica", "normal");
  doc.text(`Generated on ${formatDate(new Date())}`, margin, 24);

  y = 36;

  // --- Summary Stats ---
  if (summary) {
    doc.setTextColor(30, 30, 30);
    doc.setFontSize(13);
    doc.setFont("helvetica", "bold");
    doc.text("Summary", margin, y);
    y += 7;

    const summaryData = [
      ["Total Orders", summary.totalOrders.toString()],
      ["Total Items", summary.totalItems.toString()],
      ["Total Quantity", formatQty(summary.totalQuantity)],
      ["Order From Companies", summary.uniqueCompanies.toString()],
      ["Unique Products", summary.uniqueProducts.toString()],
    ];

    autoTable(doc, {
      startY: y,
      head: [["Metric", "Value"]],
      body: summaryData,
      margin: { left: margin, right: margin },
      theme: "grid",
      headStyles: {
        fillColor: [23, 37, 84],
        textColor: [255, 255, 255],
        fontStyle: "bold",
        fontSize: 9,
      },
      bodyStyles: { fontSize: 9 },
      columnStyles: {
        0: { fontStyle: "bold", cellWidth: 60 },
        1: { cellWidth: 40 },
      },
    });

    y = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 10;

    // Status breakdown
    doc.setFontSize(13);
    doc.setFont("helvetica", "bold");
    doc.text("Status Breakdown", margin, y);
    y += 7;

    const statusData = [
      ["Received", summary.orderedCount.toString()],
      ["Processing", summary.processingCount.toString()],
      ["Shipped", summary.dispatchedCount.toString()],
      ["Delivered", summary.deliveredCount.toString()],
    ];

    autoTable(doc, {
      startY: y,
      head: [["Status", "Count"]],
      body: statusData,
      margin: { left: margin, right: margin },
      theme: "grid",
      headStyles: {
        fillColor: [23, 37, 84],
        textColor: [255, 255, 255],
        fontStyle: "bold",
        fontSize: 9,
      },
      bodyStyles: { fontSize: 9 },
      columnStyles: {
        0: { fontStyle: "bold", cellWidth: 60 },
        1: { cellWidth: 40 },
      },
    });

    y = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 10;
  }

  // --- Orders Table ---
  doc.setFontSize(13);
  doc.setFont("helvetica", "bold");
  doc.setTextColor(30, 30, 30);
  doc.text("Order Details", margin, y);
  y += 7;

  if (orders.length > 0) {
    const orderRows = orders.map((o) => [
      displayValue(o.orderNumber),
      displayValue(o.companyName),
      displayValue(o.departmentName),
      statusLabel(o.status),
      o.totalItems.toString(),
      formatQty(o.totalQuantity),
      displayValue(o.productNames.map((name, index) => productLabel(name, o.productUnits?.[index])).join(", ")),
      formatDate(o.createdAt),
    ]);

    autoTable(doc, {
      startY: y,
      head: [["Order #", "Company", "Community", "Status", "Items", "Qty", "Products", "Date"]],
      body: orderRows,
      margin: { left: margin, right: margin },
      theme: "striped",
      headStyles: {
        fillColor: [23, 37, 84],
        textColor: [255, 255, 255],
        fontStyle: "bold",
        fontSize: 8,
      },
      bodyStyles: { fontSize: 7 },
      columnStyles: {
        0: { cellWidth: 28 },
        1: { cellWidth: 35 },
        2: { cellWidth: 35 },
        3: { cellWidth: 24 },
        4: { cellWidth: 16, halign: "center" },
        5: { cellWidth: 16, halign: "center" },
        6: { cellWidth: 55 },
        7: { cellWidth: 28 },
      },
      didDrawPage: (data) => {
        // Footer on every page
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const pageCount = (doc as any).getNumberOfPages();
        doc.setFontSize(8);
        doc.setTextColor(150);
        doc.text(
          `Page ${data.pageNumber} of ${pageCount}`,
          pageWidth - margin,
          doc.internal.pageSize.getHeight() - 8,
          { align: "right" }
        );
        doc.text(
          "MIS Report — Confidential",
          margin,
          doc.internal.pageSize.getHeight() - 8
        );
      },
    });

    y = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 10;
  } else {
    doc.setFontSize(10);
    doc.setFont("helvetica", "italic");
    doc.setTextColor(120);
    doc.text("No orders found for the selected filters.", margin, y);
    y += 10;
  }

  // --- Orders by Company ---
  if (ordersByCompany.length > 0) {
    // Check if we need a new page
    if (y > doc.internal.pageSize.getHeight() - 60) {
      doc.addPage();
      y = margin;
    }

    doc.setFontSize(13);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 30, 30);
    doc.text("Orders by Company", margin, y);
    y += 7;

    const companyRows = ordersByCompany.map((c) => [
      displayValue(c.companyName),
      c.orderCount.toString(),
      formatQty(c.totalQuantity),
      `${c.percentage.toFixed(1)}%`,
    ]);

    autoTable(doc, {
      startY: y,
      head: [["Company", "Orders", "Total Quantity", "Share"]],
      body: companyRows,
      margin: { left: margin, right: margin },
      theme: "grid",
      headStyles: {
        fillColor: [23, 37, 84],
        textColor: [255, 255, 255],
        fontStyle: "bold",
        fontSize: 9,
      },
      bodyStyles: { fontSize: 9 },
      columnStyles: {
        0: { cellWidth: 60 },
        1: { cellWidth: 30, halign: "center" },
        2: { cellWidth: 40, halign: "center" },
        3: { cellWidth: 30, halign: "center" },
      },
    });

    y = (doc as unknown as { lastAutoTable: { finalY: number } }).lastAutoTable.finalY + 10;
  }

  // --- Orders by Product ---
  if (ordersByProduct.length > 0) {
    // Check if we need a new page
    if (y > doc.internal.pageSize.getHeight() - 60) {
      doc.addPage();
      y = margin;
    }

    doc.setFontSize(13);
    doc.setFont("helvetica", "bold");
    doc.setTextColor(30, 30, 30);
    doc.text("Orders by Product", margin, y);
    y += 7;

    const productRows = ordersByProduct.map((p) => [
      productLabel(p.productName, p.defaultUnit),
      p.orderCount.toString(),
      formatQty(p.totalQuantity),
      `${p.percentage.toFixed(1)}%`,
    ]);

    autoTable(doc, {
      startY: y,
      head: [["Product", "Orders", "Total Quantity", "Share"]],
      body: productRows,
      margin: { left: margin, right: margin },
      theme: "grid",
      headStyles: {
        fillColor: [23, 37, 84],
        textColor: [255, 255, 255],
        fontStyle: "bold",
        fontSize: 9,
      },
      bodyStyles: { fontSize: 9 },
      columnStyles: {
        0: { cellWidth: 60 },
        1: { cellWidth: 30, halign: "center" },
        2: { cellWidth: 40, halign: "center" },
        3: { cellWidth: 30, halign: "center" },
      },
    });
  }

  // Save the PDF
  doc.save("mis-report.pdf");
}

// ============================================
// Skeleton
// ============================================

function TableSkeleton() {
  return (
    <div className="space-y-3">
      {Array.from({ length: 5 }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-4 rounded-lg border border-gray-100 bg-gray-50 p-3"
        >
          <div className="h-4 w-20 animate-pulse rounded bg-gray-200" />
          <div className="h-4 w-28 animate-pulse rounded bg-gray-200" />
          <div className="h-4 w-24 animate-pulse rounded bg-gray-200" />
          <div className="ml-auto h-4 w-16 animate-pulse rounded bg-gray-200" />
        </div>
      ))}
    </div>
  );
}

// ============================================
// MisReportTable Component
// ============================================

interface MisReportTableProps {
  orders: MisReportOrderDto[];
  isLoading?: boolean;
  summary?: MisReportSummaryDto | null;
  ordersByCompany?: MisReportByCompanyDto[];
  ordersByProduct?: MisReportByProductDto[];
}

export function MisReportTable({
  orders,
  isLoading = false,
  summary = null,
  ordersByCompany = [],
  ordersByProduct = [],
}: MisReportTableProps) {
  const [page, setPage] = useState(1);
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

  const totalPages = Math.ceil(orders.length / PAGE_SIZE);
  const displayPage = page > totalPages ? 1 : page;

  const paginatedOrders = useMemo(() => {
    const start = (displayPage - 1) * PAGE_SIZE;
    return orders.slice(start, start + PAGE_SIZE);
  }, [orders, displayPage]);

  const toggleRow = (orderId: string) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(orderId)) {
        next.delete(orderId);
      } else {
        next.add(orderId);
      }
      return next;
    });
  };

  return (
    <div className="rounded-xl border border-gray-200/80 bg-white shadow-sm">
      {/* Header */}
      <div className="flex items-center justify-between border-b border-gray-100 px-5 py-3.5">
        <div>
          <h2 className="text-base font-semibold text-navy-900">Order Details</h2>
          <p className="text-xs text-gray-400">
            {orders.length} order{orders.length !== 1 ? "s" : ""} found
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="secondary"
            size="sm"
            onClick={() => downloadCSV(orders)}
            disabled={isLoading || orders.length === 0}
            className="gap-1.5"
          >
            <Download className="h-3.5 w-3.5" />
            Download CSV
          </Button>
          <Button
            variant="secondary"
            size="sm"
            onClick={() => downloadPDF(orders, summary, ordersByCompany, ordersByProduct)}
            disabled={isLoading || orders.length === 0}
            className="gap-1.5"
          >
            <FileText className="h-3.5 w-3.5" />
            Download PDF
          </Button>
        </div>
      </div>

      {/* Table */}
      {isLoading ? (
        <div className="p-5">
          <TableSkeleton />
        </div>
      ) : orders.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-12 text-gray-400">
          <Package className="mb-3 h-10 w-10" />
          <p className="text-sm font-medium">No orders found</p>
          <p className="text-xs">Try adjusting your filters</p>
        </div>
      ) : (
        <>
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead>
                <tr className="border-b border-gray-200 text-left">
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Order #
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Company
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Community
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Status
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Items
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Qty
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Date
                  </th>
                  <th className="px-5 py-3 text-xs font-medium uppercase tracking-wider text-gray-400">
                    Products
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {paginatedOrders.map((order) => (
                  <tr
                    key={order.orderId}
                    className="group transition-colors hover:bg-gray-50/50"
                  >
                    <td className="whitespace-nowrap px-5 py-3 text-sm font-medium text-navy-900">
                      {displayValue(order.orderNumber)}
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 text-sm text-gray-700">
                      {displayValue(order.companyName)}
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 text-sm text-gray-500">
                      {displayValue(order.departmentName)}
                    </td>
                    <td className="px-5 py-3">
                      <StatusBadge status={order.status} />
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 text-sm text-gray-700">
                      {order.totalItems}
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 text-sm font-medium text-gray-900">
                      {formatQty(order.totalQuantity)}
                    </td>
                    <td className="whitespace-nowrap px-5 py-3 text-sm text-gray-500">
                      {formatDate(order.createdAt)}
                    </td>
                    <td className="px-5 py-3">
                      <button
                        onClick={() => toggleRow(order.orderId)}
                        className="text-xs text-blue-600 hover:text-blue-800"
                      >
                        {order.productNames.length} product
                        {order.productNames.length !== 1 ? "s" : ""}
                        {expandedRows.has(order.orderId) ? " ▲" : " ▼"}
                      </button>
                      {expandedRows.has(order.orderId) && (
                        <div className="mt-1.5 flex flex-wrap gap-1">
                          {order.productNames.map((name, idx) => (
                            <span
                              key={idx}
                              className="inline-block rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600"
                            >
                              {productLabel(name, order.productUnits?.[idx])}
                            </span>
                          ))}
                        </div>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-between border-t border-gray-100 px-5 py-3">
              <p className="text-xs text-gray-400">
                Page {displayPage} of {totalPages}
              </p>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setPage(Math.max(1, displayPage - 1))}
                  disabled={displayPage <= 1}
                  className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
                >
                  <ChevronLeft className="h-4 w-4" />
                </button>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(
                  (p) => (
                    <button
                      key={p}
                      onClick={() => setPage(p)}
                      className={`rounded-lg px-2.5 py-1 text-xs font-medium transition-colors ${
                        p === displayPage
                          ? "bg-navy-900 text-white"
                          : "text-gray-500 hover:bg-gray-100"
                      }`}
                    >
                      {p}
                    </button>
                  )
                )}
                <button
                  onClick={() => setPage(Math.min(totalPages, displayPage + 1))}
                  disabled={displayPage >= totalPages}
                  className="rounded-lg p-1.5 text-gray-400 hover:bg-gray-100 hover:text-gray-600 disabled:opacity-30 disabled:cursor-not-allowed"
                >
                  <ChevronRight className="h-4 w-4" />
                </button>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}
