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

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,
    },
    invoiceNumber: "",
  });
  const [showDropdown, setShowDropdown] = useState<string | null>(null);
  const dropdownContainerRefs = useRef<Record<string, HTMLDivElement | null>>(
    {}
  );
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const isClickInside = Object.values(dropdownContainerRefs.current).some(
        (ref) => ref && ref.contains(event.target as Node)
      );
      if (!isClickInside) {
        setShowDropdown(null);
      }
    };

    // document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  const fetchInvoices = useCallback(async () => {
    try {
      setLoading(true);
      // Prepare filter parameters for API
      const params: any = {
        created_from: filters.dateRange.start || undefined,
        created_to: filters.dateRange.end || undefined,
        is_paid: false,
        status: filters.status || undefined,
        payment_status: 1,
        invoice_amount_from:
          filters.amountRange.min > 0 ? filters.amountRange.min : undefined,
          invoice_amount_to:
          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 = {
        created_from: filters.dateRange.start || undefined,
        created_to: filters.dateRange.end || undefined,
        receipt_amount_from:
          filters.amountRange.min > 0 ? filters.amountRange.min : undefined,
          receipt_amount_to:
          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();
      fetchReceipts();
    } else {
      fetchReceipts();
    }
  }, [activeTab, fetchInvoices, fetchReceipts]);

  // Keyboard shortcut for clearing all filters
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      // Ctrl+Shift+C to clear all filters
      if (event.ctrlKey && event.shiftKey && event.key === "C") {
        event.preventDefault();
        handleClearAllFilters();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const toggleFilter = () => setFilterModal(!filterModal);
  const onSaveFilter = (filter: any) => {
    setFilters(filter);
    toggleFilter();
  };
  const handleStatusFilter = (value: string) =>
    setFilters({ ...filters, status: value });

  // Filter handling functions
  const clearIndividualFilter = (filterType: string) => {
    setFilters((prev: any) => {
      const newFilters = { ...prev };
      if (filterType === "invoiceNumber") {
        // Remove invoice number filter
        delete newFilters.invoiceNumber;
      } else if (filterType === "amount") {
        // Reset amount range
        newFilters.amountRange = { min: 0, max: 0 };
      } else if (filterType === "dateRange") {
        // Reset date range
        newFilters.dateRange = { start: "", end: "" };
      } else if (filterType === "status") {
        // Reset status
        newFilters.status = "";
      }
      return newFilters;
    });
  };

  const clearAllFilters = () => {
    // Reset all filters to default values
    setFilters({
      dateRange: {
        start: "",
        end: "",
      },
      status: "",
      amountRange: {
        min: 0,
        max: 0,
      },
      invoiceNumber: "",
    });

    // Close filter modal if it's open
    if (filterModal) {
      setFilterModal(false);
    }

    // Reset active tab to default state
    setActiveTab("invoices");

    // Optional: Show a brief success message
    // You can add a toast notification here if you have a notification system
  };

  // Get applied filter badges
  const getFilterBadges = () => {
    const badges = [];

    if (filters.invoiceNumber) {
      badges.push({
        type: "invoiceNumber",
        label: filters.invoiceNumber,
        color: "bg-blue-dark",
      });
    }

    if (filters.amountRange.min > 0 || filters.amountRange.max > 0) {
      const amountLabel =
        filters.amountRange.min > 0 && filters.amountRange.max > 0
          ? `${filters.amountRange.min} - ${filters.amountRange.max}`
          : filters.amountRange.min > 0
          ? `Min: ${filters.amountRange.min}`
          : `Max: ${filters.amountRange.max}`;

      badges.push({
        type: "amount",
        label: amountLabel,
        color: "bg-blue-dark",
      });
    }

    if (filters.dateRange.start || filters.dateRange.end) {
      const dateLabel =
        filters.dateRange.start && filters.dateRange.end
          ? `${moment(filters.dateRange.start).format("MMM DD, YYYY")} - ${moment(filters.dateRange.end).format("MMM DD, YYYY")}`
          : moment(filters.dateRange.start).format("MMM DD, YYYY") || moment(filters.dateRange.end).format("MMM DD, YYYY");

      badges.push({
        type: "dateRange",
        label: dateLabel,
        color: "bg-blue-dark",
      });
    }

    return badges;
  };

  // Enhanced clear all with SweetAlert
  const handleClearAllFilters = () => {
    // Check if SweetAlert is available
    if (typeof window !== "undefined" && (window as any).Swal) {
      Swal.fire({
        title: "Clear All Filters?",
        text: "Are you sure you want to clear all applied filters?",
        icon: "warning",
        showCancelButton: true,
        reverseButtons: true,
        customClass: {
          confirmButton: "delybell-primary px-4",
          cancelButton: "delybell-dark",
        },
        confirmButtonText: "Yes, clear all!",
        cancelButtonText: "Cancel",
      }).then((result: any) => {
        if (result.isConfirmed) {
          clearAllFilters();
          Swal.fire({
            title: "Cleared!",
            text: "All filters have been cleared successfully.",
            icon: "success",
            reverseButtons: true,
            customClass: {
              confirmButton: "delybell-primary px-4",
              cancelButton: "delybell-dark",
            },
          });
        }
      });
    } else {
      // Fallback to regular confirm if SweetAlert is not available
      Swal.fire({
        title: "Clear All Filters?",
        text: "Are you sure you want to clear all applied filters?",
        icon: "warning",
        showCancelButton: true,
        reverseButtons: true,
        customClass: {
          confirmButton: "delybell-primary px-4",
          cancelButton: "delybell-dark",
        },
        confirmButtonText: "Yes, clear all!",
        cancelButtonText: "Cancel",
      }).then((result: any) => {
        if (result.isConfirmed) {
          clearAllFilters();
        }
      });
    }
  };

  // Check if any filters are applied (excluding status)
  const hasActiveFilters = () => {
    return (
      filters.dateRange.start ||
      filters.dateRange.end ||
      filters.amountRange.min > 0 ||
      filters.amountRange.max > 0 ||
      filters.invoiceNumber
    );
  };
  const toggleDropdown = (orderId: string) => {
    setShowDropdown(showDropdown === orderId ? null : orderId);
  };
  const handleView = (invoice: any, type = "invoice") => {
    const url =
      type === "receipt"
        ? `/receipt-view?id=${cryptoHandler(invoice?.id, "encrypt")}`
        : `/invoice-view?id=${cryptoHandler(invoice?.id, "encrypt")}`;
    window.open(url, "_blank");
  };
  return (
    <>
      <style>
        {`
          .tabs-rounded a:first-child {
              border-top-left-radius: 10px!important;
              border-bottom-left-radius: 10px!important;
          }
          .adjust-content { margin: 20px 5px; }
                    .dropdown-menu.show {    
            font-size: 12px;
            background: #f7deff;
            border-color: #dedbdb;
          }
        `}
      </style>
      <div className="page-content innerPageWrap ordersPageWrap oder-list-page overflow-visible">
        <div className="header header-fixed header-logo-app innerHeader">
          <Link href="/invoices" className="header-title header-subtitle">
            Invoice
          </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">
            {hasActiveFilters() && (
              <div className="clear-filter-badge d-float-center justify-content-end">
                {getFilterBadges().map((badge, index) => (
                  <div
                    key={index}
                    className="badge rounded-s d-float-center bg-blue-dark"
                    role="clear"
                  >
                    <strong className="alert-icon-text color-white ps-1">
                      {badge.label}
                    </strong>
                    &nbsp;|&nbsp;
                    <i
                      className="fa fa-times font-14"
                      onClick={() => clearIndividualFilter(badge.type)}
                    ></i>
                  </div>
                ))}
                <div
                  className="badge rounded-s d-float-center bg-red-dark ms-2"
                  role="clear"
                  onClick={handleClearAllFilters}
                >
                  <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");
                  handleStatusFilter("unpaid");
                }}
              >
                <i className="ri ri-file-text-line me-1" /> Unpaid Invoices (
                {invoices.length})
              </a>
              <a
                href="#"
                className={`rounded-01 font-600 ${
                  activeTab === "receipts" ? "bg-purple no-click" : ""
                }`}
                onClick={(e) => {
                  e.preventDefault();
                  setActiveTab("receipts");
                  handleStatusFilter("paid");
                }}
              >
                <i className="ri ri-file-list-line me-1" /> Paid Invoices (
                {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"
                                    ref={(el) => {
                                      dropdownContainerRefs.current[
                                        invoice.id
                                      ] = el;
                                    }}
                                  >
                                    <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?.generatedInvoiceId}
                                        </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?.isCompletelyPaid
                                            ? "Paid"
                                            : "Un Paid"}
                                        </span>
                                        <a
                                          href="#"
                                          onClick={(e) => {
                                            e.preventDefault();
                                            toggleDropdown(invoice.id);
                                          }}
                                          className="ms-auto"
                                        >
                                          <i className="fa text-end fa fa-ellipsis-v font-14 color-primary"></i>
                                        </a>
                                        {showDropdown === invoice.id && (
                                          <div
                                            className="dropdown-menu show position-absolute end-0 mt-2"
                                            style={{
                                              zIndex: 9999,
                                              right: 0,
                                              minWidth: "120px",
                                            }}
                                            onClick={(e) => e.stopPropagation()}
                                          >
                                            <button
                                              type="button"
                                              className="dropdown-item d-flex align-items-center gap-2"
                                              style={{ cursor: "pointer" }}
                                              onClick={(e) => {
                                                e.preventDefault();
                                                e.stopPropagation();
                                                handleView(invoice);
                                              }}
                                            >
                                              <i className="fa fa-eye"></i> View
                                            </button>
                                          </div>
                                        )}
                                      </div>
                                    </div>
                                    <div>
                                      <h6 className="font-500 font-16 mb-2 d-float-center">
                                        <span className="font-700 text-dark">
                                          {/* {
                                            invoice?.order
                                              ?.destinationCustomerName
                                          } */}
                                          {invoice?.payableAmount
                                            ? amountFormatWithCurrency(
                                                invoice?.payableAmount || 0
                                              )
                                            : ""}
                                        </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?.createdAt).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">
                                      {invoice?.notes ? (
                                        <h6 className="font-13 font-400 mt-0 mb-0 d-float-center">
                                          Note: {invoice?.notes}
                                        </h6>
                                      ) : (
                                        <h6 className="font-400 font-13 mb-1">
                                          <span>
                                            <i
                                              className="ri ri-calendar-line me-1"
                                              aria-hidden="true"
                                            />
                                            {moment(invoice?.dueDate).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"
                                  ref={(el) => {
                                    dropdownContainerRefs.current[receipt.id] =
                                      el;
                                  }}
                                >
                                  <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?.generatedReceiptId}
                                      {/* </a> */}
                                    </h6>
                                    {/* <a
                                      href="#"
                                      onClick={(e) => {
                                        e.preventDefault();
                                        toggleDropdown(receipt.id);
                                      }}
                                      className="ms-auto"
                                    >
                                      <i className="fa text-end fa fa-ellipsis-v font-14 color-primary"></i>
                                    </a> */}
                                    {showDropdown === receipt.id && (
                                      <div
                                        className="dropdown-menu show position-absolute end-0 mt-2"
                                        style={{
                                          zIndex: 9999,
                                          right: 0,
                                          minWidth: "120px",
                                        }}
                                        onClick={(e) => e.stopPropagation()}
                                      >
                                        <button
                                          type="button"
                                          className="dropdown-item d-flex align-items-center gap-2"
                                          style={{ cursor: "pointer" }}
                                          onClick={(e) => {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            handleView(receipt, "receipt");
                                          }}
                                        >
                                          <i className="fa fa-eye"></i> View
                                        </button>
                                      </div>
                                    )}{" "}
                                  </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?.name || ""
                                          )}
                                        </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?.paidAmount || 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}
            initialFilters={filters}
          />
        </Modal>
      )}
    </>
  );
}
