/* eslint-disable @typescript-eslint/no-explicit-any */
import Image from "next/image";
import Link from "next/link";
import { useCallback, useEffect, useState } from "react";
import { getInvoices, getReceipts } from "../../../Api/OrderApi";
import moment from "moment-timezone";
import {
  amountFormat,
  cryptoHandler,
  formatDate,
  stringFormatterQuoteStart,
} from "../../../lib/Helper";
import NoData from "../../NoDataContainer/NoData";
import Modal from "../../Modal/Modal";
import AccountFilter from "../../Modal/Filters/AccountFilter";

interface Invoice {
  invoice_number: string;
  status: string;
  total_orders: number;
  period_start: string;
  period_end: string;
  invoice_date: string;
  total_amount: number;
}

interface Receipt {
  receipt_number: string;
  customer_name: string;
  payment_method: string;
  amount: number;
  payment_date: string;
  notes: string;
}

export default function NotificationsIndex() {
  const [activeTab, setActiveTab] = useState("invoices");
  const [invoices, setInvoices] = useState<Invoice[]>([]);
  const [receipts, setReceipts] = useState<Receipt[]>([]);
  const [loading, setLoading] = useState(false);
  const [filterModal, setFilterModal] = useState<boolean>(false);
  const [filters, setFilters] = useState<any>({
    dateRange: {
      start: "",
      end: "",
    },
    status: "",
    amountRange: {
      min: 0,
      max: 0,
    },
  });

  const fetchInvoices = useCallback(async () => {
    try {
      setLoading(true);
      // Prepare filter parameters for API
      const params: any = {
        start_date: filters.dateRange.start || undefined,
        end_date: filters.dateRange.end || undefined,
        status: filters.status || undefined,
        min_amount:
          filters.amountRange.min > 0 ? filters.amountRange.min : undefined,
        max_amount:
          filters.amountRange.max > 0 ? filters.amountRange.max : undefined,
      };

      const data = await getInvoices(params);
      setInvoices(data);
    } catch (error) {
      console.error("Error fetching invoices:", error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  const fetchReceipts = useCallback(async () => {
    try {
      setLoading(true);
      // Prepare filter parameters for API
      const params: any = {
        start_date: filters.dateRange.start || undefined,
        end_date: filters.dateRange.end || undefined,
        min_amount:
          filters.amountRange.min > 0 ? filters.amountRange.min : undefined,
        max_amount:
          filters.amountRange.max > 0 ? filters.amountRange.max : undefined,
      };

      const data = await getReceipts(params);
      setReceipts(data);
    } catch (error) {
      console.error("Error fetching receipts:", error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  useEffect(() => {
    if (activeTab === "invoices") {
      fetchInvoices();
    } else {
      fetchReceipts();
    }
  }, [activeTab, fetchInvoices, fetchReceipts]);

  const toggleFilter = () => setFilterModal(!filterModal);
  const onSaveFilter = (filter: any) => {
    setFilters(filter);
    toggleFilter();
  };
  return (
    <>
      <style>
        {`
          .tabs-rounded a:first-child {
              border-top-left-radius: 10px!important;
              border-bottom-left-radius: 10px!important;
          }
          .adjust-content { margin: 20px 5px; }
        `}
      </style>
      <div className="page-content innerPageWrap ordersPageWrap oder-list-page overflow-visible">
        <div className="header header-fixed header-logo-app innerHeader">
          <Link href="/account" className="header-title header-subtitle">
            My Accounts
          </Link>
          <Link href="/dashboard" className="header-icon header-icon-1">
            <i className="fas fa-arrow-left" />
          </Link>
          <a
            href="#"
            onClick={toggleFilter}
            className="color-theme show-on-theme-light header-icon header-icon-2 font-16"
          >
            <i className="fa fa-filter" />
          </a>
        </div>        

        <div className="my-account-tab mt-0">
          <div className="row mb-0 m-0 innerContentWrap orders-list">
            <div className="clear-filter-badge d-float-center justify-content-end">
              <div className="badge rounded-s d-float-center bg-blue-dark" role="clear">
                <strong className="alert-icon-text color-white ps-1">INV-000066</strong>&nbsp;|&nbsp;            
                <i className="fa fa-times font-14"></i>            
              </div>
              <div className="badge rounded-s d-float-center bg-blue-dark" role="clear">
                <strong className="alert-icon-text color-white ps-1">999.000</strong>&nbsp;|&nbsp;            
                <i className="fa fa-times font-14"></i>            
              </div>
              <div className="badge rounded-s d-float-center bg-red-dark ms-2" role="clear">
                <i className="fa fa-times font-14"></i>&nbsp;|&nbsp;
                <strong className="alert-icon-text color-white ps-0">Clear All</strong>           
              </div>
            </div>
            <div
              className="tab-controls tabs-small tabs-rounded px-0"
              data-highlight="bg-purple"
            >
              <a
                href="#"
                className={`rounded-01 font-600 ${
                  activeTab === "invoices" ? "bg-purple no-click" : ""
                }`}
                onClick={(e) => {
                  e.preventDefault();
                  setActiveTab("invoices");
                }}
              >
                <i className="ri ri-file-text-line me-1" /> Invoices (
                {invoices.length})
              </a>
              <a
                href="#"
                className={`rounded-01 font-600 ${
                  activeTab === "receipts" ? "bg-purple no-click" : ""
                }`}
                onClick={(e) => {
                  e.preventDefault();
                  setActiveTab("receipts");
                }}
              >
                <i className="ri ri-file-list-line me-1" /> Receipts ({receipts.length}
                )
              </a>
            </div>
            <div className="card card-style bg-transparent pb-0 m-0 p-0">
              <div className="content adjust-content my-0" id="tab-group-3">
                <div className="clearfix mb-3" />
                {loading ? (
                  <div className="text-center p-4">
                    <i className="fa fa-spinner fa-spin fa-2x"></i>
                  </div>
                ) : (
                  <div
                    data-bs-parent="#tab-group-3"
                    className="collapse row my-orders-row mb-0 show"
                    id="tab-8"
                  >
                    {activeTab === "invoices" ? (
                      invoices?.length > 0 ? (
                        invoices.map((invoice: any, index) => (
                          <div key={index} className="col-lg-3 order-list-box">
                            <div className="card card-style mb-3 mx-0">
                              <div className="content">
                                <div className="maindiv">
                                  <div className="w-100">
                                    <div className="card-info d-float-center justify-content-between">
                                      <h6 className="font-400 font-14 mb-2 d-float-center">
                                        <Link
                                          target="_blank"
                                          className="color-blue"
                                          href={`/invoice-view?id=${cryptoHandler(
                                            invoice?.id,
                                            "encrypt"
                                          )}`}
                                        >
                                          {invoice.invoiceNumber}
                                        </Link>
                                      </h6>
                                      <div className="d-float-center gap-10">
                                        <span
                                          className={`badge ${
                                            invoice.isPaid
                                              ? "badge-success"
                                              : "bg-danger"
                                          } rounded-xl font-12 px-2`}
                                        >
                                          {invoice.isPaid ? "Paid" : "Un Paid"}
                                        </span>
                                        <i className="fa text-end fa fa-ellipsis-v font-14 color-primary"></i>
                                      </div>
                                    </div>
                                    <div>
                                      <h6 className="font-500 font-16 mb-2 d-float-center">
                                        <span className="font-700 text-dark">
                                          {/* {
                                            invoice?.order
                                              ?.destinationCustomerName
                                          } */}
                                          BHD {invoice.totalAmount}
                                        </span>
                                      </h6>
                                    </div>
                                    <div className="d-float-center justify-content-between delivery-time mt-0 mb-2">
                                      <h6 className="font-13 font-400 mt-0 mb-0 d-float-center">
                                        {/* <Image
                                          className="order-icons img-fluid"
                                          src="/images/icons/calendar-icon.svg"
                                          alt="Calendar Icon"
                                          width={32}
                                          height={32}
                                        /> */}
                                        {/* Due Date:{" "} */}
                                        {moment(invoice.dueDate).format(
                                          "MMM DD, YYYY"
                                        )} 
                                        &nbsp;to&nbsp;
                                        {moment(invoice.dueDate).format(
                                          "MMM DD, YYYY"
                                        )}
                                      </h6>
                                    </div>
                                    <hr className="my-2" />
                                    <div className="d-float-center justify-content-between order-info-icons">
                                      <h6 className="font-400 font-13 mb-1">
                                        <span>
                                          <i
                                            className="ri ri-calendar-line me-1"
                                            aria-hidden="true"
                                          />
                                          {moment(invoice.createdAt).format(
                                            "MMM DD, YYYY"
                                          )}
                                        </span>
                                      </h6>
                                      {/* <div className="d-float-center wallet">
                                        <Image
                                          className="order-icons img-fluid"
                                          src="/images/icons/wallet.svg"
                                          alt="Calendar Icon"
                                          width={32}
                                          height={32}
                                        />
                                        <h6 className="font-13 font-700 mb-0">
                                          <span className="color-red-dark">
                                            {invoice.totalAmount}
                                          </span>
                                        </h6>
                                      </div> */}
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        ))
                      ) : (
                        <NoData />
                      )
                    ) : receipts?.length > 0 ? (
                      receipts.map((receipt: any, index) => (
                        <div key={index} className="col-lg-3 order-list-box">
                          <div className="card card-style mb-3 mx-0">
                            <div className="content">
                              <div className="maindiv">
                                <div className="w-100">
                                  <div className="card-info d-float-center justify-content-between">
                                    <h6 className="font-400 font-14 mb-2 d-float-center">
                                      <a className="color-blue"                                           
                                      href={`/receipt-view?id=${cryptoHandler(
                                            receipt?.id,
                                            "encrypt"
                                          )}`}>
                                        {receipt?.receiptNumber}
                                      </a>
                                    </h6>
                                    <i className="fa text-end fa fa-ellipsis-v font-14 color-primary"></i>
                                  </div>
                                  <h6 className="font-500 font-16 mb-2 d-float-center">
                                      <span className="font-700 text-dark">
                                        {receipt?.invoice?.order
                                          ?.created_by_details?.firstName ||
                                        receipt?.invoice?.order
                                          ?.created_by_details?.lastName
                                          ? `${receipt?.invoice?.order?.created_by_details?.firstName} ${receipt?.invoice?.order?.created_by_details?.lastName}`
                                          : ""}
                                      </span>
                                    </h6>
                                  <div className="d-float-center justify-content-between order-info-icons">
                                    <h6 className="font-400 font-13 mb-1">
                                      <span>
                                        Paid by:{" "}
                                        <b>
                                          {stringFormatterQuoteStart(
                                            receipt.paymentMethod || ""
                                          )}
                                        </b>
                                      </span>
                                    </h6>
                                    <div className="d-float-center wallet">
                                      <Image
                                        className="order-icons img-fluid"
                                        src="/images/icons/wallet.svg"
                                        alt="Calendar Icon"
                                        width={32}
                                        height={32}
                                      />
                                      <h6 className="font-13 font-700 mb-0">
                                        <span className="color-red-dark">
                                          {amountFormat(receipt.amount || 0)}
                                        </span>
                                      </h6>
                                    </div>
                                  </div>
                                  <h6 className="font-400 font-13 mb-0 mt-1">
                                    <span>
                                      <i
                                        className="ri ri-calendar-line me-1"
                                        aria-hidden="true"
                                      />
                                      {formatDate(receipt.createdAt || "")}
                                    </span>
                                  </h6>
                                  <hr className="my-2" />
                                  <div className="d-float-center justify-content-between delivery-time mt-0 mb-0">
                                    <h6 className="font-13 font-400 mt-0 mb-0 d-float-center">
                                      Note: {receipt.notes}
                                    </h6>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      ))
                    ) : (
                      <NoData />
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
      {filterModal && (
        <Modal
          show={filterModal}
          onHide={toggleFilter}
          header={false}
          title=""
          fullscreen={"xl"}
          centered={true}
          classname="custom-center-modal"
          position={"top"}
        >
          <AccountFilter onHide={toggleFilter} onSaveFilter={onSaveFilter} />
        </Modal>
      )}
    </>
  );
}
