"use client";

import { useEffect, useState } from "react";
import { Download } from "react-feather";
import DateRangeFilter from "@/components/DateRangeFilter";
import DownloadButton from "@/components/DownloadButton";
import apiClient from "@/lib/apiClient"; // axios instance
import { logger } from "@/lib/logger";

interface Invoice {
  [key: string]: unknown;
  vid: string;
  name: string;
  amount: number;
  dueDate: string;
  affiliate_id: number;
  invoice: string;
  billLineItems: string;
  paymentStatus: string;
  createdTime: string;
  updatedTime: string;
}

interface InvoiceApiResponse {
  invoices: Invoice[];
  pagination: {
    currentPage: number;
    totalPages: number;
    totalRecords: number;
    limit: number;
    hasNextPage: boolean;
    hasPrevPage: boolean;
  };
}

export default function InvoiceHistory() {
  const [data, setData] = useState<Invoice[]>([]);
  const [loading, setLoading] = useState(true);
  const [entriesPerPage, setEntriesPerPage] = useState(10);
  const [currentPage, setCurrentPage] = useState(1);

  // track selected date range
  const [dateRange, setDateRange] = useState<{
    startDate: string;
    endDate: string;
  } | null>(null);

  const [totalPages, setTotalPages] = useState(1);

  useEffect(() => {
    async function fetchInvoiceData() {
      setLoading(true);
      try {
        const params: Record<string, string | number> = {
          page: currentPage,
          limit: entriesPerPage,
        };

        if (dateRange) {
          params.fromDate = dateRange.startDate;
          params.toDate = dateRange.endDate;
        }

        const res = await apiClient.get("/partner/reports/invoice-history", {
          params,
        });

        const responseData: InvoiceApiResponse =
          res.data?.data?.data || {}; // matches swagger structure

        setData(responseData.invoices || []);
        setTotalPages(responseData.pagination?.totalPages || 1);
      } catch (err) {
        logger.error("Failed to fetch invoice data:", err);
        setData([]);
      } finally {
        setLoading(false);
      }
    }

    fetchInvoiceData();
  }, [dateRange, currentPage, entriesPerPage]);

  const handleEntriesChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setEntriesPerPage(Number(e.target.value));
    setCurrentPage(1);
  };

  return (
    <div className="pcoded-main-container bg-light webContent">
      <div className="pcoded-content">
        {/* Heading & Controls */}
        <div className="row mb-3 g-2 align-items-center">
          <div className="col-12 col-md">
            <h5 className="fw-bold mb-0 text-center text-md-start">
              Invoice History
            </h5>
          </div>

          <div className="col-12 col-md-auto d-flex flex-column flex-sm-row gap-2 justify-content-center justify-content-md-end">
            <DateRangeFilter onApply={(range) => setDateRange(range)} />
            <DownloadButton data={data} filename="invoice-history" />
          </div>
        </div>

        {/* Table Card */}
        <div className="card shadow-sm p-4">
          <div className="mb-2">
            <label className="d-flex align-items-center gap-2">
              Show
              <select
                className="form-select form-select-sm"
                style={{ width: "auto" }}
                value={entriesPerPage}
                onChange={handleEntriesChange}
              >
                {[5, 10, 25, 50].map((num) => (
                  <option key={num} value={num}>
                    {num}
                  </option>
                ))}
              </select>
              entries
            </label>
          </div>
          <div className="card-body p-0 table-responsive scrollbar">
            {loading ? (
              <p className="text-center py-4">Loading...</p>
            ) : (
              <table className="table table-hover mb-0">
                <thead>
                  <tr>
                    <th className="fw-bold text-center small">ID</th>
                    <th className="fw-bold text-center small">Amount ($)</th>
                    <th className="fw-bold text-center small">Due Date</th>
                    <th className="fw-bold text-center small">Status</th>
                    <th className="fw-bold text-center small">Created At</th>
                    <th className="fw-bold text-center small">Updated At</th>
                    <th className="fw-bold text-center small">Download</th>
                  </tr>
                </thead>
                <tbody>
                  {data.map((row) => (
                    <tr key={row.vid}>
                      <td className="text-center small">
                        <small>{row.vid}</small>
                      </td>
                      <td className="text-center small">
                        <small>{row.amount}</small>
                      </td>
                      <td className="text-center small">
                        <small>{row.dueDate}</small>
                      </td>
                      <td className="text-center small">
                        <small>{row.paymentStatus}</small>
                      </td>
                      <td className="text-center small">
                        <small>{row.createdTime}</small>
                      </td>
                      <td className="text-center small">
                        <small>{row.updatedTime}</small>
                      </td>
                      <td className="text-center small">
                        <small>
                          <Download />
                        </small>
                      </td>
                    </tr>
                  ))}
                  {data.length === 0 && (
                    <tr>
                      <td colSpan={7} className="text-center text-muted py-4">
                        No invoices available.
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            )}
          </div>
          {/* Pagination */}
          <div className="d-flex justify-content-between align-items-center mt-2">
            <small className="text-muted">
              Showing{" "}
              {data.length === 0 ? 0 : (currentPage - 1) * entriesPerPage + 1} to{" "}
              {Math.min(currentPage * entriesPerPage, data.length)} of{" "}
              {data.length} entries
            </small>

            <nav>
              <ul className="pagination pagination-sm mb-0">
                <li
                  className={`page-item ${currentPage === 1 ? "disabled" : ""}`}
                >
                  <button
                    className="page-link bg-light border-0"
                    onClick={() => setCurrentPage((p) => p - 1)}
                  >
                    Previous
                  </button>
                </li>
                <li>
                  <span className="page-link">{currentPage}</span>
                </li>
                <li
                  className={`page-item ${currentPage === totalPages ? "disabled" : ""
                    }`}
                >
                  <button
                    className="page-link border-0 bg-light ms-1"
                    onClick={() => setCurrentPage((p) => p + 1)}
                  >
                    Next
                  </button>
                </li>
              </ul>
            </nav>
          </div>
        </div>
      </div>
    </div>
  );
}
