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

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;
}

interface FilterState {
  dateRange: {
    start: string;
    end: string;
  };
  status: string;
  amountRange: {
    min: number | string;
    max: number | 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<FilterState>({
    dateRange: {
      start: "",
      end: "",
    },
    status: "",
    amountRange: {
      min: "",
      max: "",
    },
  });
  const [showAllOrders, setShowAllOrders] = useState<{
    [key: number]: boolean;
  }>({});

  // Check if any filters are active
  const hasActiveFilters = () => {
    return (
      filters.dateRange.start ||
      filters.dateRange.end ||
      filters.status ||
      filters.amountRange.min ||
      filters.amountRange.max
    );
  };

  // Clear specific filter
  const clearFilter = (filterType: string, subType?: string) => {
    setFilters(prev => {
      const newFilters = { ...prev };
      
      if (filterType === 'dateRange' && subType) {
        newFilters.dateRange = {
          ...newFilters.dateRange,
          [subType]: ""
        };
      } else if (filterType === 'amountRange' && subType) {
        newFilters.amountRange = {
          ...newFilters.amountRange,
          [subType]: ""
        };
      } else if (filterType === 'status') {
        newFilters.status = "";
      }
      
      return newFilters;
    });
  };

  // Clear all filters
  const clearAllFilters = () => {
    setFilters({
      dateRange: {
        start: "",
        end: "",
      },
      status: "",
      amountRange: {
        min: "",
        max: "",
      },
    });
  };

  const fetchInvoices = useCallback(async () => {
    try {
      setLoading(true);
      const params: any = {
        start_date: filters.dateRange.start || undefined,
        end_date: filters.dateRange.end || undefined,
        status: filters.status || undefined,
        min_amount: filters.amountRange.min || undefined,
        max_amount: filters.amountRange.max || undefined,
      };
      const data = await getToSettlements(params);
      setInvoices(data);
    } catch (error) {
      console.error("Error fetching invoices:", error);
    } finally {
      setLoading(false);
    }
  }, [filters]);

  const fetchReceipts = useCallback(async () => {
    try {
      setLoading(true);
      const params: any = {
        start_date: filters.dateRange.start || undefined,
        end_date: filters.dateRange.end || undefined,
        status: filters.status || undefined,
        min_amount: filters.amountRange.min || undefined,
        max_amount: filters.amountRange.max || undefined,
      };
      const data = await getCompletedSettlements(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]);

  const toggleFilter = () => setFilterModal(!filterModal);
  const onSaveFilter = (filter: FilterState) => {
    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; }
          .settled-orders-list {
            max-height: 100px;
            overflow-y: auto;
          }
          .clear-filter-badge {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-bottom: 15px;
          }
          .filter-badge {
            cursor: pointer;
            transition: opacity 0.2s;
          }
          .filter-badge:hover {
            opacity: 0.8;
          }
        `}
      </style>
      <div className="page-content innerPageWrap ordersPageWrap oder-list-page overflow-visible">
        <div className="header header-fixed header-logo-app innerHeader">
          <Link href="/settlements" className="header-title header-subtitle">
            Settlements
          </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">
            {/* Active Filter Badges */}
            {hasActiveFilters() && (
              <div className="clear-filter-badge d-float-center justify-content-end">
                {filters.dateRange.start && (
                  <div
                    className="badge rounded-s d-float-center bg-blue-dark filter-badge"
                    onClick={() => clearFilter('dateRange', 'start')}
                  >
                    <strong className="alert-icon-text color-white ps-1">
                      From: {formatDate(filters.dateRange.start)}
                    </strong>
                    &nbsp;|&nbsp;
                    <i className="fa fa-times font-14"></i>
                  </div>
                )}
                {filters.dateRange.end && (
                  <div
                    className="badge rounded-s d-float-center bg-blue-dark filter-badge"
                    onClick={() => clearFilter('dateRange', 'end')}
                  >
                    <strong className="alert-icon-text color-white ps-1">
                      To: {formatDate(filters.dateRange.end)}
                    </strong>
                    &nbsp;|&nbsp;
                    <i className="fa fa-times font-14"></i>
                  </div>
                )}
                {filters.amountRange.min && (
                  <div
                    className="badge rounded-s d-float-center bg-blue-dark filter-badge"
                    onClick={() => clearFilter('amountRange', 'min')}
                  >
                    <strong className="alert-icon-text color-white ps-1">
                      Min: {amountFormat(String(filters.amountRange.min))}
                    </strong>
                    &nbsp;|&nbsp;
                    <i className="fa fa-times font-14"></i>
                  </div>
                )}
                {filters.amountRange.max && (
                  <div
                    className="badge rounded-s d-float-center bg-blue-dark filter-badge"
                    onClick={() => clearFilter('amountRange', 'max')}
                  >
                    <strong className="alert-icon-text color-white ps-1">
                      Max: {amountFormat(String(filters.amountRange.max))}
                    </strong>
                    &nbsp;|&nbsp;
                    <i className="fa fa-times font-14"></i>
                  </div>
                )}
                {filters.status && (
                  <div
                    className="badge rounded-s d-float-center bg-blue-dark filter-badge"
                    onClick={() => clearFilter('status')}
                  >
                    <strong className="alert-icon-text color-white ps-1">
                      Status: {filters.status}
                    </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 filter-badge"
                  onClick={clearAllFilters}
                >
                  <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" /> To settle (
                {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" /> Settled (
                {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((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-700 font-14 mb-2 d-float-center">
                                        {receipt?.settlementId}
                                      </h6>
                                      <span
                                        className={`badge ${
                                          getSettlementStatusInfo(
                                            receipt?.status?.id,
                                            receipt
                                          )?.color
                                        } rounded-xl font-12 px-2`}
                                      >
                                        {
                                          getSettlementStatusInfo(
                                            receipt?.status?.id,
                                            receipt
                                          )?.text
                                        }
                                      </span>
                                    </div>
                                    <h6 className="font-500 font-16 mb-2 d-float-center">
                                      <span className="font-700 text-dark">
                                        {receipt?.order_details?.pickupCustomerName}
                                      </span>
                                    </h6>
                                    <div className="d-float-center justify-content-between order-info-icons">
                                      <h6 className="font-400 font-13 mb-1">
                                        Payment Method:{" "}
                                        <b>
                                          {stringFormatterQuoteStart(
                                            receipt?.codPaymentMethod?.name || ""
                                          )}
                                        </b>
                                      </h6>
                                      <div className="d-float-center wallet">
                                        <Image
                                          className="order-icons img-fluid"
                                          src="/images/icons/wallet.svg"
                                          alt="Wallet Icon"
                                          width={32}
                                          height={32}
                                        />
                                        <h6 className="font-13 font-700 mb-0">
                                          <span className="color-red-dark">
                                            {amountFormatWithCurrency(
                                              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"
                                        />
                                        {moment(receipt.transactionAt).format("MMM DD, YYYY")}
                                      </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">
                                        {receipt?.paymentNotes
                                          ? `Note: ${receipt?.paymentNotes}`
                                          : receipt?.transactionReference
                                          ? `Transaction ID: ${receipt?.transactionReference}`
                                          :  receipt?.order_details?.generatedOrderId ? `Order ID: ${receipt?.order_details?.generatedOrderId}` : ``}
                                      </h6>
                                    </div>
                                    {/* Show settled orders */}
                                    {receipt.settled_orders &&
                                      receipt.settled_orders.length > 0 && (
                                        <div className="mt-2">
                                          <h6 className="font-13 font-700 mb-1">
                                            Settled Orders:
                                          </h6>
                                          <ul className="settled-orders-list">
                                            {(showAllOrders[index]
                                              ? receipt.settled_orders
                                              : receipt.settled_orders.slice(
                                                  0,
                                                  3
                                                )
                                            ).map((order: any) => (
                                              <li key={order.id}>
                                                {order.generatedOrderId} -{" "}
                                                {order.codAmount} (
                                                {order.codPaymentMethod?.name})
                                              </li>
                                            ))}
                                          </ul>
                                          {receipt.settled_orders.length >
                                            3 && (
                                            <button
                                              className="btn btn-link p-0"
                                              style={{ fontSize: "13px" }}
                                              onClick={() =>
                                                setShowAllOrders((prev) => ({
                                                  ...prev,
                                                  [index]: !prev[index],
                                                }))
                                              }
                                            >
                                              {showAllOrders[index]
                                                ? "Show less"
                                                : `+${
                                                    receipt.settled_orders
                                                      .length - 3
                                                  } more`}
                                            </button>
                                          )}
                                        </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-700 font-14 mb-2 d-float-center">
                                      {receipt?.settlementId}
                                    </h6>
                                    <span
                                      className={`badge ${
                                        getSettlementStatusInfo(
                                          receipt?.status?.id,
                                          receipt
                                        )?.color
                                      } rounded-xl font-12 px-2`}
                                    >
                                      {
                                        getSettlementStatusInfo(
                                          receipt?.status?.id,
                                          receipt
                                        )?.text
                                      }
                                    </span>
                                  </div>
                                  <h6 className="font-500 font-16 mb-2 d-float-center">
                                    <span className="font-700 text-dark">
                                      {receipt?.customer_details?.companyName}
                                    </span>
                                  </h6>
                                  <div className="d-float-center justify-content-between order-info-icons">
                                    <h6 className="font-400 font-13 mb-1">
                                      Paid by:{" "}
                                      <b>
                                        {stringFormatterQuoteStart(
                                          receipt?.settlementPaymentMode
                                            ?.name || ""
                                        )}
                                      </b>
                                    </h6>
                                    <div className="d-float-center wallet">
                                      <Image
                                        className="order-icons img-fluid"
                                        src="/images/icons/wallet.svg"
                                        alt="Wallet Icon"
                                        width={32}
                                        height={32}
                                      />
                                      <h6 className="font-13 font-700 mb-0">
                                        <span className="color-red-dark">
                                          {amountFormat(
                                            receipt?.totalCalculatedAmount || 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"
                                      />
                                      {receipt.settlementPeriodStartDate &&
                                      receipt.settlementPeriodEndDate ? (
                                        <>
                                          {formatDate(
                                            receipt.settlementPeriodStartDate
                                          )}{" "}
                                          to{" "}
                                          {formatDate(
                                            receipt.settlementPeriodEndDate
                                          )}
                                        </>
                                      ) : receipt.settlementPeriodStartDate ? (
                                        formatDate(
                                          receipt.settlementPeriodStartDate
                                        )
                                      ) : receipt.settlementPeriodEndDate ? (
                                        formatDate(
                                          receipt.settlementPeriodEndDate
                                        )
                                      ) : (
                                        "No period"
                                      )}
                                    </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">
                                      {receipt?.paymentNotes
                                        ? `Note: ${receipt?.paymentNotes}`
                                        : receipt?.transactionReference
                                        ? `Transaction ID: ${receipt?.transactionReference}`
                                        : ``}
                                    </h6>
                                  </div>
                                  {/* Show settled orders */}
                                  {receipt.settled_orders &&
                                    receipt.settled_orders.length > 0 && (
                                      <div className="mt-2">
                                        <h6 className="font-13 font-700 mb-1">
                                          Settled Orders:
                                        </h6>
                                        <ul className="settled-orders-list">
                                          {(showAllOrders[index]
                                            ? receipt.settled_orders
                                            : receipt.settled_orders.slice(0, 3)
                                          ).map((order: any) => (
                                            <li key={order.id}>
                                              {order.generatedOrderId} -{" "}
                                              {order.codAmount} (
                                              {order.codPaymentMethod?.name})
                                            </li>
                                          ))}
                                        </ul>
                                        {receipt.settled_orders.length > 3 && (
                                          <button
                                            className="btn btn-link p-0"
                                            style={{ fontSize: "13px" }}
                                            onClick={() =>
                                              setShowAllOrders((prev) => ({
                                                ...prev,
                                                [index]: !prev[index],
                                              }))
                                            }
                                          >
                                            {showAllOrders[index]
                                              ? "Show less"
                                              : `+${
                                                  receipt.settled_orders.length -
                                                  3
                                                } more`}
                                          </button>
                                        )}
                                      </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"}
        >
          <SettlementFilter 
            onHide={toggleFilter} 
            onSaveFilter={onSaveFilter}
            initialFilters={filters}
          />
        </Modal>
      )}
    </>
  );
}
