"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> {
  [key: string]: unknown;
  date: string;
  tqScore: string;
  validClicks: number;
  fraudClicks: number;
  dropClicks: number;
  ctr: string;
  netRevenue: number;
  estCon: number;
  advCon: number;
}

interface TotalStats {
  tq?: string;
  cc: number;
  fc: number;
  dc: number;
  ctr: string;
  rev: number;
  conv: number;
  adv_conv: number;
}
interface Pagination {
  currentPage: number;
  totalPages: number;
  totalRecords: number;
  limit: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}

// Format date as YYYY-MM-DD
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 default 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 RevenueReportPage() {
  const entriesPerPage = 10; // Fixed entries per page
  const [data, setData] = useState<RevenueData[]>([]);
  const [totalStats, setTotalStats] = useState<TotalStats | null>(null);
  const [currentPage, setCurrentPage] = useState(1);

  const [dateRange, setDateRange] = useState<{
    startDate: string;
    endDate: string;
  }>({
    startDate: formatDate(start),
    endDate: formatDate(end),
  });
  const [pagination, setPagination] = useState<Pagination | null>(null);
  const [loading, setLoading] = useState(false);

  // Fetch data whenever date range, page, or entriesPerPage changes
  useEffect(() => {
    const fetchCPCReports = async () => {
      try {
        setLoading(true);
        const response = await apiClient.get("/partner/reports/cpc", {
          params: {
            fromDate: dateRange.startDate,
            toDate: dateRange.endDate,
            page: currentPage,
            limit: entriesPerPage,
          },
          withCredentials: true,
        });

        const stats = response.data?.data?.data?.stats || [];
        const total = response.data?.data?.data?.totalStats || null;

        const formattedData = stats.map((item: Record<string, unknown>) => ({
          date: item.date as string,
          tqScore: item.tq as string,
          validClicks: item.cc as number,
          fraudClicks: item.fc as number,
          dropClicks: item.dc as number,
          ctr: item.ctr as string,
          netRevenue: Number((item.rev as number).toFixed(2)),
          estCon: item.conv as number,
          advCon: item.adv_conv as number,
        }));

        setData(formattedData);
        setTotalStats(total);
        setPagination(response.data.data?.data?.pagination || null);
      } catch (error) {
        logger.error("Failed to fetch revenue per click data:", error);
        setData([]);
        setTotalStats(null);
        setPagination(null);
      } finally {
        setLoading(false);
      }
    };

    fetchCPCReports();
  }, [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-md-start text-secondary">
              Revenue Per Click 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/cpc/download"
                params={{
                  fromDate: dateRange.startDate,
                  toDate: dateRange.endDate,
                }}
                filename={`cpc-report-${dateRange.startDate}-to-${dateRange.endDate}`}
                disabled={loading}
              />
            )}
            <DateRangeFilter
              onApply={(range) => setDateRange(range)}
              initialRange={dateRange} // <-- last 7 days visible in filter by default
            />
          </div>
        </div>

        {/* Table */}
        <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 small">Date</th>
                  <th className="fw-semibold text-center small">TQ Score</th>
                  <th className="fw-semibold text-center small">
                    Valid Clicks
                  </th>
                  <th className="fw-semibold text-center small">
                    Fraud Clicks
                  </th>
                  <th className="fw-semibold text-center small">
                    Drop. Clicks
                  </th>
                  <th className="fw-semibold text-center small">CTR</th>
                  <th className="fw-semibold text-center small">Net Revenue</th>
                  <th className="fw-semibold text-center small">Est Con.</th>
                  <th className="fw-semibold text-center small">Adv Con.</th>
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr>
                    <td colSpan={9} 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 small">{row.date}</td>
                        <td className="text-center small">
                          {Math.round(Number(row.tqScore))}%
                        </td>
                        <td className="text-center small">{row.validClicks}</td>
                        <td className="text-center small">{row.fraudClicks}</td>
                        <td className="text-center small">{row.dropClicks}</td>
                        <td className="text-center small">
                          {Math.round(Number(row.ctr))}%
                        </td>
                        <td className="text-center small">
                          ${row.netRevenue.toFixed(2)}
                        </td>
                        <td className="text-center small">{row.estCon}</td>
                        <td className="text-center small">{row.advCon}</td>
                      </tr>
                    ))}
                    {totalStats && (
                      <tr className="table-light fw-bold">
                        <td className="text-center small fw-semibold">Total</td>
                        <td className="text-center small">
                          {/* {Math.round(Number(totalStats.tq))}%  will not display this  */}
                        </td>
                        <td className="text-center small">{totalStats.cc}</td>
                        <td className="text-center small">{totalStats.fc}</td>
                        <td className="text-center small">{totalStats.dc}</td>
                        <td className="text-center small">
                          {Math.round(Number(totalStats.ctr))}%
                        </td>
                        <td className="text-center small">
                          ${totalStats.rev.toFixed(2)}
                        </td>
                        <td className="text-center small">{totalStats.conv}</td>
                        <td className="text-center small">
                          {totalStats.adv_conv}
                        </td>
                      </tr>
                    )}
                  </>
                ) : (
                  <tr>
                    <td colSpan={9} className="text-center py-4 text-muted">
                      No data available for the selected date.
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>

          {/* Pagination */}
          {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>
  );
}
