import { Typography } from "@komi-app/components";
import "./ReportStats.scss";
import moment from "moment";
import {
  useCampaignAnalyticsQuery,
  useCampaignClickStatsQuery,
} from "../queries";
import { useMemo } from "react";

export interface Props {
  campaignId: string;
}

const CampaignReportStatsV2 = ({ campaignId }: Props) => {
  const { data: clickStats } = useCampaignClickStatsQuery(campaignId);

  const { data: analytics } = useCampaignAnalyticsQuery(campaignId);

  const { totalClicks, totalUniqueClicks } = useMemo(() => {
    if (!clickStats) return { totalClicks: 0, totalUniqueClicks: 0 };

    return {
      totalClicks: clickStats.clicks.reduce(
        (total, link) => total + link.totalClicks,
        0
      ),
      totalUniqueClicks: clickStats.clicks.reduce(
        (total, link) => total + link.uniqueClicks,
        0
      ),
    };
  }, [clickStats]);

  return (
    <div className="stats-sections">
      <section className="rates-section">
        <div className="rates-section-heading">
          <Typography.Body strong>Link Clicks</Typography.Body>
        </div>
        <table className="click-through-rate-table">
          <thead>
            <tr>
              <th>
                <Typography.Body level={2} strong color="gray-800">
                  Links Clicked
                </Typography.Body>
              </th>
              <th>
                <Typography.Body level={2} strong color="gray-800">
                  Unique Clicks
                </Typography.Body>
              </th>
              <th>
                <Typography.Body level={2} strong color="gray-800">
                  Total Clicks
                </Typography.Body>
              </th>
            </tr>
          </thead>
          <tbody>
            {!clickStats || clickStats?.clicks.length === 0 ? (
              Array(3)
                .fill({})
                .map((_, i) => (
                  <tr key={i}>
                    <td>
                      <Typography.Body level={2} color="gray-800">
                        --
                      </Typography.Body>
                    </td>
                    <td>
                      <Typography.Body level={2} color="gray-800">
                        --
                      </Typography.Body>
                    </td>
                    <td>
                      <Typography.Body level={2} color="gray-800">
                        --
                      </Typography.Body>
                    </td>
                  </tr>
                ))
            ) : (
              <>
                {clickStats.clicks.map((link, i) => (
                  <tr key={i}>
                    <td>
                      <Typography.Body level={2} color="gray-800">
                        {link.text || link.url}
                      </Typography.Body>
                    </td>
                    <td>
                      <Typography.Body level={2} color="gray-800">
                        {link.uniqueClicks}
                      </Typography.Body>
                    </td>
                    <td>
                      <Typography.Body level={2} color="gray-800">
                        {link.totalClicks}
                      </Typography.Body>
                    </td>
                  </tr>
                ))}
                <tr>
                  <td>
                    <Typography.Body level={2} color="gray-800">
                      Total
                    </Typography.Body>
                  </td>
                  <td>
                    <Typography.Body
                      level={2}
                      color="gray-800"
                    >
                      {totalUniqueClicks}
                    </Typography.Body>
                  </td>
                  <td>
                    <Typography.Body level={2} color="gray-800">
                      {totalClicks}
                    </Typography.Body>
                  </td>
                </tr>
              </>
            )}
          </tbody>
        </table>
      </section>
      <section className="rates-section">
        <div className="rates-section-heading">
          <Typography.Body strong>Open rate</Typography.Body>
        </div>
        <div className="open-rate-detail-list">
          <div className="open-rate-detail">
            <div className="open-rate-detail-label">
              <Typography.Body level={2} strong color="gray-800">
                Total opens
              </Typography.Body>
            </div>
            <div className="open-rate-detail-separator"></div>
            <div className="open-rate-detail-value">
              <Typography.Body level={2} color="gray-800">
                {analytics?.stats ? analytics.stats?.opened : "--"}
              </Typography.Body>
            </div>
          </div>

          <div className="open-rate-detail">
            <div className="open-rate-detail-label">
              <Typography.Body level={2} strong color="gray-800">
                Last opened
              </Typography.Body>
            </div>
            <div className="open-rate-detail-separator"></div>
            <div className="open-rate-detail-value">
              <Typography.Body level={2} color="gray-800">
                {analytics?.timestamps?.lastOpened
                  ? formatDate(analytics?.timestamps?.lastOpened)
                  : "--"}
              </Typography.Body>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
};

export default CampaignReportStatsV2;

function formatDate(value: number | string): string {
  try {
    const convertedDateTime = new Date(
      typeof value === "string" ? value : value * 1000
    );
    return moment(convertedDateTime).format("MMM DD, yyyy h:mmA");
  } catch (error) {
    return "--";
  }
}
