"use client";

import { useEffect, useState } from "react";
import DateRangeFilter from "@/components/DateRangeFilter";
import DownloadButton from "@/components/DownloadButton";
import apiClient from "@/lib/apiClient";
import { logger } from "@/lib/logger";

interface RevenueData extends Record<string, unknown> {
  date: string;
  totalClicks: number;
  netRevenue: number;
}

interface Pagination {
  currentPage: number;
  totalPages: number;
  totalRecords: number;
  limit: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}

const formatDate = (date: Date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};

// Calculate last 7 days range
const today = new Date();
const end = new Date(today);
end.setDate(today.getDate() );
const start = new Date(end);
start.setDate(end.getDate() - 6);

export default function TotalRevenueReport() {
  const entriesPerPage = 10; // Fixed entries per page
  const [data, setData] = useState<RevenueData[]>([]);
  const [pagination, setPagination] = useState<Pagination | null>(null);

  const [currentPage, setCurrentPage] = useState(1);
  const [dateRange, setDateRange] = useState<{
    startDate: string;
    endDate: string;
  }>({
    startDate: formatDate(start),
    endDate: formatDate(end),
  });
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchRevenueReport = async () => {
      setLoading(true);
      try {
        const fromDate = dateRange.startDate;
        const toDate = dateRange.endDate;

        const response = await apiClient.get("/partner/reports/revenue", {
          params: {
            fromDate,
            toDate,
            page: currentPage,
            limit: entriesPerPage,
          },
          withCredentials: true,
        });

        const apiData = response.data?.data?.data;

        if (apiData) {
          const mapped: RevenueData[] =
            apiData.daily?.map((item: Record<string, unknown>) => ({
              date: item.date as string,
              totalClicks: item.cc as number,
              netRevenue: Number(item.rev) || 0,
            })) || [];

          setData(mapped);
          setPagination(apiData.pagination);
        } else {
          setData([]);
          setPagination(null);
        }
      } catch (error) {
        logger.error("Failed to fetch revenue report:", error);
        setData([]);
        setPagination(null);
      } finally {
        setLoading(false);
      }
    };

    fetchRevenueReport();
  }, [dateRange, currentPage]);

  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-secondary text-md-start">
              Total Revenue Report
            </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">
            {
              data.length > 0 && (
                <DownloadButton
                  apiEndpoint="/partner/reports/revenue/download"
                  params={{
                    fromDate: dateRange.startDate,
                    toDate: dateRange.endDate,
                  }}
                  filename={`revenue-report-${dateRange.startDate}-to-${dateRange.endDate}`}
                  disabled={loading}
                />
              )
            }
            <DateRangeFilter
              onApply={(range) => setDateRange(range)}
              initialRange={dateRange}
            />
          </div>
        </div>

        {/* Table Card */}
        <div className="card shadow-sm p-4">
          <div className="card-body p-0 table-responsive scrollbar">
            <table className="table table-hover mb-0">
              <thead>
                <tr>
                  <th className="fw-semibold text-center">Date</th>
                  <th className="fw-semibold text-center">Total Clicks</th>
                  <th className="fw-semibold text-center">Net Revenue</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={3} className="text-center py-4 text-muted">
                      Generating report data...
                    </td>
                  </tr>
                ) : data.length ? (
                  data.map((row, idx) => (
                    <tr key={idx}>
                      <td className="text-center">{row.date}</td>
                      <td className="text-center">
                        {row.totalClicks.toLocaleString()}
                      </td>
                      <td className="text-center">
                        ${row.netRevenue.toFixed(2)}
                      </td>
                    </tr>
                  ))
                ) : (
                  <tr>
                    <td colSpan={3} className="text-center py-4 text-muted">
                      No data available for the selected date range.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* ✅ Pagination only if data exists & totalRecords > limit */}
          {pagination &&
            data.length > 0 && (
              <div className="d-flex justify-content-between align-items-center mt-2">
                <small className="text-muted">
                  Showing{" "}
                  {`${(currentPage - 1) * entriesPerPage + 1} to ${Math.min(
                    currentPage * entriesPerPage,
                    pagination.totalRecords
                  )} of ${pagination.totalRecords} entries`}
                </small>

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

          {/* Important Notes */}
          <h3 className="smallHeading mt-3">Important Notes:</h3>
          <ul className="list ps-3 mb-3">
            <li>
              All reports are in <strong>Pacific Standard Time (PST).</strong>
            </li>
            <li>
              All figures shown are <strong>estimates only</strong>. Final
              payments are based on advertiser-reported conversions.
            </li>
            <li>
              If a <strong>negative value</strong> appears in the Events column,
              it may be due to:
            </li>
            <li>Reversed advertiser complaints,</li>
            <li>Adjustments for previously missed clicks,</li>
            <li>Other reconciliation reasons.</li>
          </ul>
          <p className="mb-3">
            These are <strong>credits</strong> being returned to your account
            and may not correspond to the reported day.
          </p>
          <ul className="list ps-3 mb-3">
            <li>
              We are committed to accuracy and fair compensation. Our goal is to
              ensure all publishers are paid correctly.
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
}
