"use client";

import React, { useState } from "react";
import { jsPDF } from "jspdf";
import "jspdf-autotable";
import { Button } from "@/components/ui/button";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useProductReportQuery } from "@/redux/services/reports.api";

declare module "jspdf" {
  interface jsPDF {
    autoTable: (options: any) => jsPDF;
  }
}

interface TableRow {
  name: string;
  category: string;
  orderCount: number;
  totalQuantity: number;
  productId: string;
}

// Sample data for the table (replace this with your actual data)
// const tableData: TableRow[] = [
//   {
//     name: "All Natural OVEN READY Turkey(14-16lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "67198361511ef64d147d33fc",
//   },
//   {
//     name: "All Natural OVEN READY Turkey(24-26lbs)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 5,
//     productId: "67198373511ef64d147d3414",
//   },
//   {
//     name: "All Natural OVEN READYTurkey(16-20bs)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 4,
//     productId: "6719836a511ef64d147d3408",
//   },
//   {
//     name: "All Natural Turkey raw(24-26lbs)",
//     category: "Turkey",
//     orderCount: 2,
//     totalQuantity: 9,
//     productId: "67198311511ef64d147d33a8",
//   },
//   {
//     name: "All-Natural OVEN READY Turkey raw ( 10-14lb)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 5,
//     productId: "67198357511ef64d147d33f0",
//   },
//   {
//     name: "All-Natural Turkey (10-14lbs)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 2,
//     productId: "67198343511ef64d147d33d8",
//   },
//   {
//     name: "All-Natural Turkey raw(14-16lbs)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 1,
//     productId: "67198300511ef64d147d339c",
//   },
//   {
//     name: "All-Natural Turkey raw(16-20lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "6719834e511ef64d147d33e4",
//   },
//   {
//     name: "Bell & Evans - Oven Ready  Medium Turkey(18-20lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "671983ab511ef64d147d3450",
//   },
//   {
//     name: "Bell & Evans - Oven Ready Large Turkey(24-26lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "671983b7511ef64d147d345c",
//   },
//   {
//     name: "Bell & Evans - Oven Ready Small Turkey(12-14 lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "67198396511ef64d147d3444",
//   },
//   {
//     name: "Bell & Evans Large Turkey raw(24-26lbs)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 5,
//     productId: "6719838c511ef64d147d3438",
//   },
//   {
//     name: "Bell & Evans Medium Turkey raw(18-20lbs)",
//     category: "Turkey",
//     orderCount: 1,
//     totalQuantity: 1,
//     productId: "67198384511ef64d147d342c",
//   },
//   {
//     name: "Bell & Evans Small Turkey (12-14 lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "6719837c511ef64d147d3420",
//   },
//   {
//     name: "O/R Large Turkey(24-26lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "67198339511ef64d147d33cc",
//   },
//   {
//     name: "O/R Medium Turkey(16-18lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "6719832f511ef64d147d33c0",
//   },
//   {
//     name: "O/R Small Turkey(14-16lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "67198326511ef64d147d33b4",
//   },
//   {
//     name: "Small Turkey (14-16lbs)",
//     category: "Turkey",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "671982ef511ef64d147d3390",
//   },
//   {
//     name: "test 0006",
//     category: "Chicken",
//     orderCount: 0,
//     totalQuantity: 0,
//     productId: "672161af2708d3548e38d91e",
//   },
// ];

const ITEMS_PER_PAGE = 10;

interface PDFTableComponentProps {
  Branch?: string;
  From: string;
  To?: string;
}

// Update the component declaration
const PDFTableComponent: React.FC<PDFTableComponentProps> = ({
  Branch,
  From,
  To,
}) => {
  const { data, isLoading, error } = useProductReportQuery({
    startDate: From,
    endDate: To,
    branchId: Branch,
  });
  const [showPreview, setShowPreview] = useState<boolean>(false);
  const [pdfUrl, setPdfUrl] = useState<string>("");
  const [currentPage, setCurrentPage] = useState<number>(1);

  if (!data?.data[0].productStats) {
    return <p>No Data</p>;
  }
  const totalPages = Math.ceil(
    data?.data[0].productStats.length / ITEMS_PER_PAGE
  );

  const generatePDF = (): jsPDF => {
    const doc = new jsPDF();
    const pageWidth = doc.internal.pageSize.width;
    // Set up the header
    doc.setFontSize(18);
    doc.text("FOOD POPULARITY REPORT", 14, 20);

    doc.setDrawColor(0, 0, 0); // Black color
    doc.setLineWidth(0.1); // Thin line
    doc.line(14, 23, pageWidth - 14, 23); // Draw line across page with margins
    // doc.
    // Add the period
    doc.setFontSize(10);
    const currentDate = new Date().toLocaleDateString("en-US", {
      month: "2-digit",
      day: "2-digit",
      year: "numeric", // Changed to 'numeric' for full year
    });
    const periodText = `PERIOD:    ${From} ${To ? `- ${To}` : ""}`;
    doc.text(periodText, 14, 30); // Adjusted Y-coordinate to 40

    // Add the Iavarone Bros Reports text in the top right
    doc.setFontSize(10);

    doc.text("Inventory Management", pageWidth - 70, 20);
    doc.setFillColor(0, 0, 0);
    doc.rect(pageWidth - 40, 15.8, 22, 6, "F");
    doc.setTextColor(255, 255, 255);
    doc.text("REPORTS", pageWidth - 38, 20);
    doc.setTextColor(0, 0, 0);

    // // Add page number in top right
    // doc.text("4", pageWidth - 10, 15);

    // Set up the table
    const tableRows = data?.data[0].productStats.map((row) => [
      row.orderCount,
      row.totalQuantity,
      row.name,
    ]);

    doc.autoTable({
      head: [["HOW OFTEN", "HOW MUCH", "LONG TITLE"]],
      body: tableRows,
      startY: 35, // Adjusted startY to 50 to give space for the period text
      theme: "grid",
      styles: {
        fontSize: 10,
        cellPadding: 3,
      },
      headStyles: {
        fillColor: [66, 66, 66],
        textColor: 255,
        fontSize: 10,
        fontStyle: "bold",
      },
      alternateRowStyles: {
        fillColor: [245, 245, 245],
      },
    });

    return doc;
  };

  // const generatePDF = (): jsPDF => {
  //   const doc = new jsPDF();
  //   doc.setFontSize(16);
  //   doc.text("User Data Table", 14, 15);
  //   doc.setFontSize(10);
  //   doc.text(`Generated on: ${new Date().toLocaleString()}`, 14, 25);

  //   const tableRows = data?.data[0].productStats.map((row) => [
  //     row.orderCount,
  //     row.totalQuantity,
  //     row.name,
  //   ]);

  //   doc.autoTable({
  //     head: [["HOW OFTEN", "HOW MUCH", "LONG TITLE"]],
  //     body: tableRows,
  //     startY: 30,
  //     theme: "grid",
  //     styles: {
  //       fontSize: 10,
  //       cellPadding: 3,
  //     },
  //     headStyles: {
  //       fillColor: [66, 66, 66],
  //       textColor: 255,
  //       fontSize: 10,
  //       fontStyle: "bold",
  //     },
  //     alternateRowStyles: {
  //       fillColor: [245, 245, 245],
  //     },
  //   });

  //   return doc;
  // };

  const downloadPDF = (): void => {
    const doc = generatePDF();
    doc.save(
      `Popularity-Reports_${new Date().toLocaleDateString()}_${new Date().toLocaleTimeString()}.pdf`
    );
  };

  const viewPDF = (): void => {
    const doc = generatePDF();
    const pdfBlob = doc.output("blob");
    const url = URL.createObjectURL(pdfBlob);

    setPdfUrl(url);
    setShowPreview(true);
  };

  const handlePageChange = (newPage: number) => {
    setCurrentPage(newPage);
  };

  const displayedData = data?.data[0].productStats.slice(
    (currentPage - 1) * ITEMS_PER_PAGE,
    currentPage * ITEMS_PER_PAGE
  );

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-2xl font-bold mb-4">
        Reports From Date: {From} {To && `- ${To}`}
      </h1>

      {/* HTML Table */}
      <Table className="mb-4">
        <TableHeader>
          <TableRow>
            <TableHead>HOW OFTEN</TableHead>
            <TableHead>HOW MUCH</TableHead>
            <TableHead>LONG TITLE</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {displayedData.map((row, i) => (
            <TableRow key={i}>
              <TableCell>{row.orderCount}</TableCell>
              <TableCell>{row.totalQuantity}</TableCell>
              <TableCell>{row.name}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>

      {/* Actions */}
      <div className="flex space-x-4 mb-4">
        <Button variant={"appVariant"} onClick={viewPDF}>
          View PDF
        </Button>
        <Button variant={"appVariant"} onClick={downloadPDF}>
          Download PDF
        </Button>
      </div>

      {/* Pagination Controls */}
      <div className="flex justify-between items-center">
        <Button
          variant={"appVariant"}
          onClick={() => handlePageChange(Math.max(currentPage - 1, 1))}
          disabled={currentPage === 1}
        >
          Previous
        </Button>
        <span>
          Page {currentPage} of {totalPages}
        </span>
        <Button
          variant={"appVariant"}
          onClick={() =>
            handlePageChange(Math.min(currentPage + 1, totalPages))
          }
          disabled={currentPage === totalPages}
        >
          Next
        </Button>
      </div>

      {/* PDF Preview Modal */}
      {showPreview && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white p-4 rounded-lg w-full h-full max-w-4xl max-h-[90vh]">
            <div className="flex justify-end mb-2">
              <Button
                variant={"appVariant"}
                onClick={() => {
                  setShowPreview(false);
                  URL.revokeObjectURL(pdfUrl);
                }}
              >
                Close
              </Button>
            </div>
            <iframe
              src={pdfUrl}
              className="w-full h-[calc(100%-3rem)]"
              title="PDF Preview"
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default PDFTableComponent;
