"use client";

import { useEffect, useState } from "react";
import PerformanceAnalyticsStatCard, {
  formatCompactAnalyticsNumber,
  getPerformanceAnalyticsStatCards,
} from "@/components/PerformanceAnalyticsStatCard";
import apiClient from "@/lib/apiClient";
import { logger } from "@/lib/logger";

interface InstagramInsights {
  impressions: number;
  reach: number;
  engagement: number;
  saved: number;
  shares: number;
}

interface BoostStats {
  impressions: number;
  clicks: number;
  spend: number;
}

interface InstagramAnalyticsPost {
  id: number;
  ig_post_id: string;
  caption: string;
  status: string;
  media_url: string;
  media_type?: "IMAGE" | "VIDEO" | "CAROUSEL_ALBUM" | string;
  dm_count: number;
  like_count: number;
  comments_count: number;
  sm_count: number;
  click?: number;
  revenue?: number;
  insights_fetched_at?: string;
  insights?: InstagramInsights | null;
  boost_stats?: BoostStats | null;
}

interface InstagramAnalyticsResponse {
  success: boolean;
  message: string;
  data: {
    posts: InstagramAnalyticsPost[];
    total_count: number;
    pagination: {
      limit: number;
      page: number;
      total_pages: number;
      has_more: boolean;
    };
    sm_totals: {
      total_likes: number;
      total_comments: number;
      total_dms: number;
      total_sm_count: number;
      total_revenue: number;
    };
  };
}

type SortKey = "validClicks" | "netRevenue" | "refreshedAt";

const PAGE_SIZE = 3;

const formatInsightsFetchedAt = (value?: string) => {
  if (!value) return "-";

  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return "-";

  const day = date.getDate();
  const getOrdinal = (n: number) => {
    const rem10 = n % 10;
    const rem100 = n % 100;
    if (rem10 === 1 && rem100 !== 11) return "st";
    if (rem10 === 2 && rem100 !== 12) return "nd";
    if (rem10 === 3 && rem100 !== 13) return "rd";
    return "th";
  };

  const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
  const month = monthNames[date.getMonth()];
  const year = date.getFullYear();

  let hours = date.getHours();
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const ampm = hours >= 12 ? "pm" : "am";
  hours = hours % 12;
  if (hours === 0) hours = 12;

  return `${day}${getOrdinal(day)} ${month} ${year} ${hours}:${minutes} ${ampm}`;
};

const normalizeStatus = (status: string) => {
  if (status === "start") return "Active";
  if (status === "pause") return "Paused";
  return status;
};

export default function MediaBoostPerformanceAnalyticsPage() {
  const [posts, setPosts] = useState<InstagramAnalyticsPost[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [sortConfig, setSortConfig] = useState<{ key: SortKey; direction: "asc" | "desc" } | null>(null);
  const [smTotals, setSmTotals] = useState<InstagramAnalyticsResponse["data"]["sm_totals"] | null>(null);

  const fetchAnalytics = async (pageToLoad: number) => {
    setLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams({
        page: pageToLoad.toString(),
        limit: PAGE_SIZE.toString(),
        search: "",
      });

      const response = await apiClient.get<InstagramAnalyticsResponse>(
        `/ig/posts/partner-posts/analytics?${params.toString()}`
      );

      if (!response.data?.success || !response.data.data) {
        setError(response.data?.message || "Failed to load performance analytics.");
        setPosts([]);
        setSmTotals(null);
        setTotalCount(0);
        return;
      }

      const { posts, pagination, sm_totals } = response.data.data;

      setPosts(posts || []);
      setSmTotals(sm_totals || null);
      setPage(pagination?.page || pageToLoad);
      setTotalCount(response.data.data.total_count || posts.length || 0);
      setTotalPages(pagination?.total_pages || 1);
    } catch (err) {
      logger.error("Failed to fetch performance analytics", err);
      setError("Unable to load performance analytics right now. Please try again later.");
      setPosts([]);
      setSmTotals(null);
      setTotalCount(0);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAnalytics(page);
  }, [page]);

  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > totalPages || newPage === page || loading) return;
    setPage(newPage);
  };

  const handleSort = (key: SortKey) => {
    setSortConfig((current) => {
      if (current?.key === key) {
        return {
          key,
          direction: current.direction === "asc" ? "desc" : "asc",
        };
      }

      return {
        key,
        direction: "asc",
      };
    });
  };

  const sortedPosts = [...posts].sort((left, right) => {
    if (!sortConfig) return 0;

    const leftNetRevenue = (left.revenue ?? 0) - (left.boost_stats?.spend ?? 0);
    const rightNetRevenue = (right.revenue ?? 0) - (right.boost_stats?.spend ?? 0);
    const leftDate = left.insights_fetched_at ? new Date(left.insights_fetched_at).getTime() : 0;
    const rightDate = right.insights_fetched_at ? new Date(right.insights_fetched_at).getTime() : 0;

    const values = {
      validClicks: [(left.click ?? 0), (right.click ?? 0)],
      netRevenue: [leftNetRevenue, rightNetRevenue],
      refreshedAt: [leftDate, rightDate],
    } as const;

    const [leftValue, rightValue] = values[sortConfig.key];
    const difference = leftValue - rightValue;

    return sortConfig.direction === "asc" ? difference : -difference;
  });

  const getSortClassName = (key: SortKey) => {
    if (!sortConfig || sortConfig.key !== key) return "sorting";
    return sortConfig.direction === "asc" ? "sorting sorting_asc" : "sorting sorting_desc";
  };

  const statCards = getPerformanceAnalyticsStatCards({
    totalLikes: smTotals?.total_likes ?? 0,
    totalComments: smTotals?.total_comments ?? 0,
    totalValidClicks: smTotals?.total_sm_count ?? 0,
    totalNetRevenue: smTotals?.total_revenue ?? 0,
  });

  const showingStart = sortedPosts.length === 0 ? 0 : (page - 1) * PAGE_SIZE + 1;
  const showingEnd = sortedPosts.length === 0 ? 0 : Math.min((page - 1) * PAGE_SIZE + sortedPosts.length, totalCount);

  return (
    <div className="pcoded-main-container webContent">
      <div className="pcoded-content">
        <div className="row align-items-center align-items-md-end mb-md-0 mb-2">
          <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12 mt-3 text-md-start text-center">
            <h3 className="text-xl fw-500 mb-1">Performance Analytics</h3>
            <p className="text-md color-content mb-0">Track the performance and revenue for your Instagram boosted posts.</p>
          </div>
        </div>

        <div className="row g-2 g-xl-3 py-3 mb-3">
          {smTotals
            ? statCards.map((card) => (
                <PerformanceAnalyticsStatCard
                  key={card.label}
                  label={card.label}
                  value={card.value}
                  cardClassName={card.cardClassName}
                />
              ))
            : null}

          {/* Sample Data note : kept for testing purpose now, to be cleaned up later when real data is available */}
          <div className="col-md-12 col-12">
            <div className="card border shadow-none rounded-4 m-0 mb-3">
              <div className="card-body platform-cards">
                <div id="postTable_wrapper" className="dataTables_wrapper no-footer">
                  {error ? <div className="alert alert-danger mb-3">{error}</div> : null}
                  {/* Table structure inspired by DataTables.net with custom styling and React state management for sorting and pagination */}
                  <div className="table-responsive scrollbar">
                    <table className="table mb-0 deeplinks-table text-center dataTable no-footer" id="postTable">
                      <thead className="thead-dark">
                        <tr>
                          <th className="align-middle text-center color-content">Post</th>
                          <th className="align-middle text-center color-content">Caption</th>
                          <th className="align-middle text-center color-content">Status</th>
                          <th className="align-middle text-center color-content">Organic stats</th>
                          <th className="align-middle text-center color-content">Boosted stats</th>
                          <th
                            className={`align-middle text-center color-content ${getSortClassName("validClicks")}`}
                            tabIndex={0}
                            role="button"
                            onClick={() => handleSort("validClicks")}
                          >
                            Valid Clicks
                          </th>
                          <th
                            className={`align-middle text-center color-content ${getSortClassName("netRevenue")}`}
                            tabIndex={0}
                            role="button"
                            onClick={() => handleSort("netRevenue")}
                          >
                            Net Revenue
                          </th>
                          <th
                            className={`align-middle text-center color-content ${getSortClassName("refreshedAt")}`}
                            tabIndex={0}
                            role="button"
                            onClick={() => handleSort("refreshedAt")}
                          >
                            Refreshed At
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        {loading ? (
                          <tr>
                            <td colSpan={8} className="text-center py-4 text-muted">Loading performance analytics...</td>
                          </tr>
                        ) : sortedPosts.length === 0 ? (
                          <tr>
                            <td colSpan={8} className="text-center py-4 text-muted">No boosted post analytics available.</td>
                          </tr>
                        ) : (
                          sortedPosts.map((post) => {
                            const insights = post.insights || null;
                            const netRevenue = (post.revenue ?? 0) - (post.boost_stats?.spend ?? 0);

                            return (
                              <tr key={post.id}>
                                <td className="align-middle">
                                  <a href={post.media_url} className="d-block ig-post-img mx-auto my-0" target="_blank" rel="noopener noreferrer">
                                    {post.media_type === "VIDEO" ? (
                                      <video
                                        src={post.media_url}
                                        className="my-0 mx-auto"
                                      />
                                    ) : (
                                      <img
                                        src={post.media_url}
                                        alt="ig posts"
                                        className="my-0 mx-auto"
                                      />
                                    )}
                                  </a>
                                </td>
                                <td className="align-middle w-130">
                                  <p className="text-md text-limit-1 mb-0" title={post.caption}>{post.caption}</p>
                                </td>
                                <td className="align-middle"><p className="text-md completed-text mb-0">{normalizeStatus(post.status)}</p></td>
                                <td className="align-middle">
                                  <div className="d-flex justify-content-center flex-wrap gap-1">
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">DMs:</span> {formatCompactAnalyticsNumber(post.dm_count ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Likes:</span> {formatCompactAnalyticsNumber(post.like_count ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Comments:</span> {formatCompactAnalyticsNumber(post.comments_count ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Engagement:</span> {formatCompactAnalyticsNumber(insights?.engagement ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Shares:</span> {formatCompactAnalyticsNumber(insights?.shares ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Reach:</span> {formatCompactAnalyticsNumber(insights?.reach ?? 0)}</div>
                                  </div>
                                </td>
                                <td className="align-middle">
                                  <div className="d-flex justify-content-center flex-wrap gap-1">
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Impressions:</span> {formatCompactAnalyticsNumber(post.boost_stats?.impressions ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Clicks:</span> {formatCompactAnalyticsNumber(post.boost_stats?.clicks ?? 0)}</div>
                                    <div className="border text-sm fw-600 rounded-2 px-2 py-1 mb-0"><span className="opacity-75 text-sm fw-400 mb-0">Spend:</span> ${Number(post.boost_stats?.spend ?? 0).toFixed(2)}</div>
                                  </div>
                                </td>
                                <td className="align-middle"><p className="text-md mb-0">{formatCompactAnalyticsNumber(post.click ?? 0)}</p></td>
                                <td className="align-middle"><p className="text-md mb-0">${netRevenue.toFixed(2)}</p></td>
                                <td className="align-middle"><p className="text-start text-sm opacity-75 mb-0">{formatInsightsFetchedAt(post.insights_fetched_at)}</p></td>
                              </tr>
                            );
                          })
                        )}
                      </tbody>
                    </table>
                  </div>

                  {/* Pagination controls */}
                  {sortedPosts.length > 0 ? (
                    <>
                      <div className="dataTables_info" id="postTable_info" role="status" aria-live="polite">
                        Showing {showingStart}-{showingEnd} of {totalCount} posts
                      </div>
                      <div className="dataTables_paginate paging_simple_numbers" id="postTable_paginate">
                        <button
                          className={`paginate_button previous ${page <= 1 || loading ? "disabled" : ""}`}
                          disabled={page <= 1 || loading}
                          onClick={() => handlePageChange(page - 1)}
                        >
                          Previous
                        </button>
                        <span>
                          <span className="paginate_button current">{page}</span>
                        </span>
                        <button
                          className={`paginate_button next ${page >= totalPages || loading ? "disabled" : ""}`}
                          disabled={page >= totalPages || loading}
                          onClick={() => handlePageChange(page + 1)}
                        >
                          Next
                        </button>
                      </div>
                    </>
                  ) : null}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}