"use client";
import React, { useState } from "react";
import { Form, Image, Table } from "react-bootstrap";
import styles from "@/styles/Component/Dashboard/Invoices.module.scss";
import useFetchData from "@/components/App/useFetchData";
import { useRequest } from "@/components/App/request";
import { Formik, Form as FormikForm } from "formik";
import * as Yup from "yup";
// import Filter from "./components/Filter";
import { SuspenseLoader } from "@/components/App/Loader";
import { toastrC } from "@/utils/helpers";
import Filter from "./components/Filter";
const validationSchema = Yup.object().shape({
  selectedInvoices: Yup.array()
    .min(1, "Please select at least one invoice")
    .required("Selection is required")
});

interface InvoiceItem {
  id: string;
  date: string;
  description: string;
  invoice: string;
  amount: number;
  invoice_number: string;
  credit: number;
  plan_id: string;
  method: string;
  plan: {
    id: number;
    name: string;
    price_id: number | null;
    price: number;
    credit: number;
    expiry: number | null;
    expiry_date: number | null;
    description: string;
    status: number;
    deleted_at: number | null;
    created_at: string;
    updated_at: string;
  };
}

interface InvoicesResponse {
  [year: string]: InvoiceItem[];
}

const Invoices = () => {
  const { request } = useRequest();
  const [timeFilter, setTimeFilter] = useState("all");

  const { data: invoiceData, isLoading } =
    useFetchData<InvoicesResponse[]>("GET_INVOICES");

  if (isLoading) return <SuspenseLoader />;
  if (!invoiceData) return <p>No data found</p>;

  const years = Object.keys(invoiceData).sort(
    (a, b) => parseInt(a) - parseInt(b)
  );

  const allInvoices: InvoiceItem[] =
    timeFilter === "all"
      ? years.flatMap(year => invoiceData[year])
      : invoiceData[timeFilter];

  const sortedInvoices = [...allInvoices].sort((a, b) => {
    return new Date(b.date).getTime() - new Date(a.date).getTime();
  });

  const handleSubmit = async values => {
    try {
      const downloadPromises = values.selectedInvoices.map(async invoiceId => {
        console.log({ invoiceId });
        const response = await request(
          "DOWNLOAD_INVOICE",
          {},
          { id: `${invoiceId}` },
          { responseType: "blob" }
        );

        // Convert to Base64 and trigger download
        //@ts-expect-error "iNVALID"
        const blob = new Blob([response], { type: "application/pdf" });

        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = `invoice-${invoiceId}.pdf`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      });

      await Promise.all(downloadPromises);
    } catch (error) {
      console.error("Error downloading invoices:", error);
      toastrC(error.message ?? "Something went wrong", "error", "error");
    }
  };

  const handleDownloadInvoice = async (id: string,invoice_number: string) => {
    try {
      const response = await request(
        "DOWNLOAD_INVOICE",
        null,
        { id: `${id}` },
        { responseType: "blob" }
      );

      // Ensure response is a valid Blob
      if (!response || !(response instanceof Blob)) {
        toastrC("Invalid response, expected a Blob", "error", "error");
        return;
      }

      // Create a download link
      const url = window.URL.createObjectURL(response);
      const a = document.createElement("a");
      const today = new Date().toISOString().split("T")[0];
      a.href = url;

      a.download = (invoice_number) != null ? `${today}-${invoice_number}.pdf` : `${today}.pdf` ;
      // a.download = `${today}-${invoice_number}.pdf`;

      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error("Error downloading invoice:", error);
      toastrC(error.message ?? "Something went wrong", "error", "error");
    }
  };

  const handleViewInvoice = async (id: string) => {
    try {
      const response = await request(
        "VIEW_INVOICE",
        null,
        { id: `${id}` },
        { responseType: "blob" }
      );

      //@ts-expect-error "iNVALID"
      const blob = new Blob([response], { type: "application/pdf" });
      const blobUrl = URL.createObjectURL(blob);

      window.open(blobUrl, "_blank");

      // Clean up the object URL after some time to free memory
      setTimeout(() => URL.revokeObjectURL(blobUrl), 10000);
    } catch (error) {
      console.error("Error viewing invoice:", error);
      toastrC(error.message ?? "Something went wrong", "error", "error");
    }
  };

  return (
    <div className={styles.InvoicesBlock}>
      <div className={styles.LeadsLimitationHead}>
        <h1>Invoices</h1>
        <Filter
          years={years}
          selectedArea={timeFilter}
          setSelectedArea={setTimeFilter}
        />
      </div>
      <Formik
        initialValues={{ selectedInvoices: [] }}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        {({ values, setFieldValue, handleSubmit }) => {
          const selectedInvoicesSet = new Set(values.selectedInvoices); // Convert Set back to work with Formik

          const toggleInvoiceSelection = (invoiceId: string) => {
            if (selectedInvoicesSet.has(invoiceId)) {
              selectedInvoicesSet.delete(invoiceId);
            } else {
              selectedInvoicesSet.add(invoiceId);
            }
            // Convert back to array when setting Formik field
            setFieldValue("selectedInvoices", Array.from(selectedInvoicesSet));
          };

          // Toggle "Select All":
          const toggleSelectAll = () => {
            if (selectedInvoicesSet.size === sortedInvoices.length) {
              // Unselect all: pass an empty array (not a new Set)
              setFieldValue("selectedInvoices", []);
            } else {
              // Select all invoice IDs:
              const allIds = sortedInvoices.map(invoice => invoice.id);
              setFieldValue("selectedInvoices", allIds);
            }
          };

          // console.log(
          //   selectedInvoicesSet.size,
          //   sortedInvoices.length,
          //   selectedInvoicesSet,
          //   sortedInvoices
          // );
          return (
            <FormikForm onSubmit={handleSubmit}>
              <div className="customTableCard text-center">
                <Table responsive>
                  <thead className="text-center">
                    <tr>
                      <th>Select</th>
                      <th>Date</th>
                      <th>Description</th>
                      <th>Method</th>                      
                      <th>Invoice Number</th>
                      <th>Amount</th>
                      <th>Credits</th>
                      <th>Action</th>
                    </tr>
                  </thead>
                  <tbody className="text-center">
                    <tr>
                      <td className="" style={{borderRight:'0px'}}>
                        {/* <div className="d-flex align-items-center h-100"> */}
                          <Form.Check
                            type="checkbox"
                            label=''
                            className={`${styles.InvoicesCheckBox} customCheckBox`}
                            onChange={toggleSelectAll}
                            checked={
                              selectedInvoicesSet.size === sortedInvoices.length
                            }
                          />
                        {/* </div> */}
                      </td>
                      <td  style={{ textAlign:'center',borderRight:'0px'}}>
                        {`${selectedInvoicesSet.size} Bills Selected`}
                      </td>
                      <td colSpan={5}>
                            &nbsp;
                      </td>

                      <td className="lightGreyBg">
                        <div className="cursor-pointer d-flex align-items-center justify-content-center h-100">
                          {selectedInvoicesSet?.size > 0 && (
                            <button
                              type="submit"
                              className="border-0 bg-transparent"
                            >
                              <Image
                                src="/assets/downloadIcon1.png"
                                alt="Download Invoice"
                              />
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                    {sortedInvoices.map((item, index) => (
                      <tr key={index}>
                        <td>
                          <Form.Check
                            type="checkbox"
                            checked={selectedInvoicesSet.has(item.id)}
                            onChange={() => toggleInvoiceSelection(item.id)}
                            label=""
                            className={`${styles.InvoicesCheckBox} customCheckBox`}
                          />
                        </td>
                        <td>{item.date}</td>
                        <td>{item.description}</td>
                        <td>{item.method}</td>                        
                        <td>{item.invoice_number}</td>
                        <td>£ {item.amount}</td>
                        <td>{item.credit}</td>
                        <td>
                          <div className="d-flex align-items-center justify-content-center h-100 gap-2">
                            <button
                              type="button"
                              className="border-0 bg-transparent"
                              onClick={() => {
                                handleViewInvoice(item.id);
                              }}
                            >
                              <Image
                                src="/assets/eyesIcon.png"
                                alt="View Invoice"
                              />
                            </button>
                            <button
                              type="button"
                              className="border-0 bg-transparent"
                              onClick={() => {
                                handleDownloadInvoice(item.id, item.invoice_number);
                              }}
                            >
                              <Image
                                src="/assets/downloadIcon1.png"
                                alt="Download Invoice"
                              />
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </Table>
              </div>
            </FormikForm>
          );
        }}
      </Formik>
    </div>
  );
};

export default Invoices;
