"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { Check, Edit2, HelpCircle, X } from "react-feather";
import DateRangeFilter from "@/components/DateRangeFilter";
import GlobalLoadingOverlay from "@/components/ui/GlobalLoadingOverlay";
import { useToast } from "@/components/ui/ToastContext";
import apiClient, { getApiErrorMessage } from "@/lib/apiClient";
import { normalizeAdvertisingModel } from "@/lib/advertisingModel";
import type { AdvertisingModelTab } from "@/components/AdvertisingModelTabs";
import type {
  AnalyticsCard,
  CreatorListItem,
  DashboardData,
  DateRange,
} from "@/components/dashboard/types";

const CREATOR_STATUS_UI: Record<
  CreatorListItem["status"],
  { label: string; isRemoved: boolean; isInvited: boolean }
> = {
  ACTIVE: { label: "Active", isRemoved: false, isInvited: false },
  INACTIVE: { label: "Inactive", isRemoved: true, isInvited: false },
  REMOVED: { label: "Inactive", isRemoved: true, isInvited: false },
  INVITED: { label: "Invited", isRemoved: false, isInvited: true },
  PENDING: { label: "Invited", isRemoved: false, isInvited: true },
  ACCEPTED: { label: "Active", isRemoved: false, isInvited: false },
  REJECTED: { label: "Rejected", isRemoved: true, isInvited: false },
};

interface AgencyDashboardProps {
  /** Active CPC/CPA tab — used for fetch context + model-specific rev share updates. */
  advertisingModel: AdvertisingModelTab;
  modelTabs?: ReactNode;
  safeData: DashboardData;
  isLoading: boolean;
  isFetching: boolean;
  isError: boolean;
  dateRange: DateRange;
  onApplyDateRange: (range: DateRange) => void;
  currentPage: number;
  totalPages: number;
  totalItems: number;
  itemsPerPage: number;
  onPageChange: (page: number) => void;
  analyticsCards: AnalyticsCard[];
  formatCurrency: (num: number) => string;
  formatNumber: (num: number) => string;
  onCreatorRemoved?: () => Promise<unknown> | void;
  /** Refetch agency dashboard after a successful rev-share update (same tab). */
  onRevenueShareUpdated?: () => Promise<unknown> | void;
}

export default function AgencyDashboard({
  advertisingModel,
  modelTabs,
  safeData,
  isLoading,
  isFetching,
  isError,
  dateRange,
  onApplyDateRange,
  currentPage,
  totalPages,
  totalItems,
  itemsPerPage,
  onPageChange,
  analyticsCards,
  formatCurrency,
  formatNumber,
  onCreatorRemoved,
  onRevenueShareUpdated,
}: AgencyDashboardProps) {
  const showToast = useToast();
  const activeModel = normalizeAdvertisingModel(advertisingModel);
  const [editingRowId, setEditingRowId] = useState<string | null>(null);
  const [draftShareValue, setDraftShareValue] = useState<string>("");
  const [pendingRemoveId, setPendingRemoveId] = useState<string | null>(null);
  const [isRemovingCreator, setIsRemovingCreator] = useState(false);
  const [isUpdatingShare, setIsUpdatingShare] = useState(false);
  /** Keyed by `${model}:${creatorId}` so CPC/CPA edits do not leak across tabs. */
  const [localShares, setLocalShares] = useState<Record<string, number>>({});
  const [localRemoved, setLocalRemoved] = useState<Record<string, boolean>>({});

  const skeleton = isLoading ? "placeholder-glow" : "";

  const shareKey = (creatorId: string) => `${activeModel}:${creatorId}`;

  // Close in-progress share edit when switching CPC/CPA tabs.
  useEffect(() => {
    setEditingRowId(null);
    setDraftShareValue("");
  }, [activeModel]);

  // Only use relevant fields from API response for creator list
  const resolvedRows = useMemo(() => {
    return safeData.creatorList.map((row) => {
      const key = `${activeModel}:${row.id}`;
      return {
        id: row.id,
        creator_name: row.creator_name,
        instagram_account: row.instagram_account,
        tiktok_account: row.tiktok_account,
        status: localRemoved[row.id] ? "INACTIVE" : row.status,
        valid_clicks: row.valid_clicks,
        net_revenue_before_share: row.net_revenue_before_share,
        net_revenue_after_share: row.net_revenue_after_share,
        revenue_share_percentage:
          localShares[key] !== undefined
            ? localShares[key]
            : row.revenue_share_percentage,
      };
    });
  }, [safeData.creatorList, localRemoved, localShares, activeModel]);

  const handleEditShare = (row: CreatorListItem) => {
    if (row.status === "INVITED") {
      return;
    }

    setEditingRowId(row.id);
    setDraftShareValue(String(row.revenue_share_percentage));
  };

  const handleSaveShare = async (row: CreatorListItem) => {
    const trimmedValue = draftShareValue.trim();
    const parsed = Number(trimmedValue);
    if (!trimmedValue || Number.isNaN(parsed)) {
      showToast("Please enter a valid revenue share value.");
      return;
    }

    if (parsed < 0 || parsed > 100) {
      showToast("Revenue share must be between 0 and 100.");
      return;
    }

    const next = parsed;
    const key = shareKey(row.id);

    try {
      setIsUpdatingShare(true);

      const response = await apiClient.patch(
        `/dashboard/agency/creators/${row.id}/revenue-share`,
        {
          revenueSharePercentage: next,
          reason: "Updated as per agreement",
          // Model-specific override for this tab only (CPC ≠ CPA when both set).
          model: activeModel,
        },
      );

      if (!response?.data?.success) {
        throw new Error(
          response?.data?.message || "Failed to update revenue share",
        );
      }

      setLocalShares((prev) => ({
        ...prev,
        [key]: next,
      }));

      setEditingRowId(null);
      setDraftShareValue("");
      showToast(response.data.message || "Revenue share updated successfully");

      // Refresh metrics so after-rev-share revenue matches the new % for this tab.
      if (onRevenueShareUpdated) {
        await onRevenueShareUpdated();
        setLocalShares((prev) => {
          const nextMap = { ...prev };
          delete nextMap[key];
          return nextMap;
        });
      }
    } catch (error: unknown) {
      showToast(
        getApiErrorMessage(
          error,
          "Failed to update revenue share. Please try again.",
        ),
      );
    } finally {
      setIsUpdatingShare(false);
    }
  };

  const confirmRemoveCreator = async () => {
    if (!pendingRemoveId) {
      return;
    }

    try {
      setIsRemovingCreator(true);

      const response = await apiClient.delete(
        `/dashboard/agency/creators/${pendingRemoveId}`,
      );

      if (!response?.data?.success) {
        throw new Error(response?.data?.message || "Failed to remove creator");
      }

      setLocalRemoved((prev) => ({
        ...prev,
        [pendingRemoveId]: true,
      }));
      setPendingRemoveId(null);
      showToast(response.data.message || "Creator removed successfully");
      await onCreatorRemoved?.();
    } catch (error) {
      showToast(
        getApiErrorMessage(error, "Failed to remove creator. Please try again."),
      );
    } finally {
      setIsRemovingCreator(false);
    }
  };

  return (
    <div className="pcoded-main-container webContent">
      <GlobalLoadingOverlay
        show={isLoading || isFetching || isRemovingCreator || isUpdatingShare}
      />
      <div className="pcoded-content">
        {modelTabs}
        <div className="row align-items-center">
          <div className="col-md-6 col-12 text-md-start text-center mb-md-0 mb-2">
            <h3 className="text-xl fw-500 mb-1">
              Creator Management Dashboard
            </h3>
            <p className={`mb-0 text-18 ${skeleton}`}>
              {new Date().toLocaleString("en-US", {
                month: "short",
                day: "2-digit",
              })}{" "}
              <span className="fw-semibold mb-0 text-18 earn-text">
                {isLoading ? (
                  <span className="placeholder col-3"></span>
                ) : (
                  formatCurrency(safeData?.currentMonthRevenue || 0)
                )}
              </span>
              <button
                type="button"
                className="no-bg-btn"
                data-bs-toggle="popover"
                data-bs-placement="right"
                data-bs-content="This is your revenue for the current month."
              >
                &nbsp; <HelpCircle className="earn-info" />
              </button>
            </p>
            {isError && (
              <p className="text-danger mt-1 mb-0">
                Unable to load dashboard data. Please try again.
              </p>
            )}
          </div>
        </div>

        <div className="bg-color-white shadow-none rounded-4 my-4 px-3 py-4">
          <div className="border-bottom pb-4 mb-4">
            <div className="row align-items-center">
              <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 text-md-start text-center mb-md-0 mb-2">
                <h3 className="thirdHeading text-capitalize mb-0">
                  Aggregated Metrics
                </h3>
              </div>
              <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 d-flex justify-content-md-end justify-content-center mb-0">
                <div id="reportrange" className="btn-first small-btn">
                  <span className="mb-0 text-white">
                    <DateRangeFilter
                      initialRange={dateRange}
                      onApply={(range) => onApplyDateRange(range)}
                    />
                  </span>
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="feather feather-chevron-down"
                  >
                    <polyline points="6 9 12 15 18 9" />
                  </svg>
                </div>
              </div>
            </div>
          </div>

          <div className="row g-2 g-xl-3 mb-2">
            {analyticsCards.map((card, index) => (
              <div
                key={index}
                className="col-lg-4 col-md-4 col-12 d-lg-flex align-items-stretch"
              >
                <div
                  className={`card ${card.bg} shadow-none border rounded-4 w-100 p-0 mb-3`}
                >
                  <div
                    className={`card-body text-lg-start text-md-center text-center p-3 ${skeleton}`}
                  >
                    <div className="row align-items-center">
                      <div className="col-lg-8 col-md-12 col-12">
                        <h5 className="color-content fw-normal mt-0">
                          {card.title}
                        </h5>
                        <h3 className="m-0 p-0">
                          {isLoading ? "-" : card.value}
                        </h3>
                      </div>
                      <div className="col-lg-4 col-md-12 col-12 text-center">
                        <Image
                          src={card.img}
                          className="mx-auto d-block"
                          width={96}
                          height={56}
                          style={{
                            height: 56,
                            width: "auto",
                            objectFit: "contain",
                          }}
                          unoptimized
                          alt=""
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>

          <div className="mb-3">
            <div className="row align-items-center">
              <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 text-md-start text-center mb-md-0 mb-2">
                <h3 className="thirdHeading text-capitalize mb-0">
                  Creator List
                </h3>
              </div>
              <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12 d-flex justify-content-md-end justify-content-center mb-0">
                <Link
                  href="/invite-creator"
                  className="btn-first small-btn px-3 mb-0"
                >
                  Invite Creator
                </Link>
              </div>
            </div>
          </div>

          <div className="table-responsive scrollbar">
            <div
              className="dataTables_wrapper no-footer"
              id="DataTables_Table_0_wrapper"
            >
              <table className="table mb-0 deeplinks-table text-center dataTable no-footer">
                <thead className="thead-dark">
                  <tr>
                    <th className="align-middle text-center lh-1">
                      Creator Name
                    </th>
                    <th className="align-middle text-center lh-1">
                      Instagram Account
                    </th>
                    <th className="align-middle text-center lh-1">
                      TikTok Account
                    </th>
                    <th className="align-middle text-center lh-1">Status</th>
                    <th className="align-middle text-center lh-1">
                      Valid Clicks
                    </th>
                    <th className="align-middle text-center lh-1">
                      Net Revenue
                      <br />
                      <small className="text-sm color-black m-0">
                        (Before Rev Share)
                      </small>
                    </th>
                    <th className="align-middle text-center lh-1">
                      Net Revenue
                      <br />
                      <small className="text-sm color-black m-0">
                        (After Rev Share)
                      </small>
                    </th>
                    <th className="align-middle text-center lh-1">
                      <span className="d-inline-flex align-items-center justify-content-center gap-1">
                        <small className="text-sm color-black fw-700 m-0">
                          Your Revenue Share
                        </small>
                        <button
                          type="button"
                          className="no-bg-btn d-inline-flex align-items-center"
                          data-bs-toggle="popover"
                          data-bs-placement="top"
                          data-bs-content="This is the percentage of earnings you keep. For example, if set to 20%, you receive 20% and the influencer receives 80%."
                          aria-label="Revenue share information"
                        >
                          <HelpCircle size={14} className="earn-info" />
                        </button>
                      </span>
                    </th>
                    <th className="align-middle text-center lh-1">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {!isLoading && resolvedRows.length === 0 && (
                    <tr>
                      <td className="align-middle text-center py-4" colSpan={9}>
                        No creators found for the selected date range.
                      </td>
                    </tr>
                  )}

                  {resolvedRows.map((row) => {
                    const isEditing = editingRowId === row.id;
                    const {
                      label: statusLabel,
                      isRemoved,
                      isInvited,
                    } = CREATOR_STATUS_UI[row.status];

                    return (
                      <tr key={row.id}>
                        <td className="align-middle">{row.creator_name}</td>
                        <td className="align-middle">
                          {row.instagram_account || "-"}
                        </td>
                        <td className="align-middle">
                          {row.tiktok_account || "-"}
                        </td>
                        <td className="align-middle">
                          <p
                            className={`text-xs h-32 rounded-pill d-flex justify-content-center text-center align-items-center completed-text mb-0 mx-auto ${
                              isRemoved
                                ? "color-red bg-color-light2 border fw-400"
                                : isInvited
                                  ? "pending-text bg-color-yellow-light border-0 fw-400"
                                  : ""
                            }`}
                            style={{ width: 110 }}
                          >
                            {statusLabel}
                          </p>
                        </td>
                        <td className="align-middle">
                          {formatNumber(row.valid_clicks)}
                        </td>
                        <td className="align-middle">
                          {formatCurrency(row.net_revenue_before_share)}
                        </td>
                        <td className="align-middle">
                          {formatCurrency(row.net_revenue_after_share)}
                        </td>
                        <td className="align-middle">
                          <div className="d-inline-flex align-items-center gap-2">
                            {isEditing ? (
                              <>
                                <input
                                  className="outline-0 shadow-0 rounded-3 w-48 h-32 border border-color-light4 text-md fw-500 m-0 p-2"
                                  type="number"
                                  min={0}
                                  max={100}
                                  value={draftShareValue}
                                  onChange={(e) => {
                                    const nextValue = e.target.value;

                                    // Allow clearing while editing.
                                    if (nextValue === "") {
                                      setDraftShareValue("");
                                      return;
                                    }

                                    // Number input can still accept exponent/decimal characters
                                    // in some browsers. Block anything except digits.
                                    if (!/^\d+$/.test(nextValue)) {
                                      return;
                                    }

                                    // Prevent entering values outside 0-100.
                                    const parsedValue = Number(nextValue);
                                    if (parsedValue < 0 || parsedValue > 100) {
                                      return;
                                    }

                                    setDraftShareValue(nextValue);
                                  }}
                                  onKeyDown={(e) => {
                                    if (
                                      ["e", "E", "+", "-", "."].includes(e.key)
                                    ) {
                                      e.preventDefault();
                                    }
                                  }}
                                  style={{ width: 56 }}
                                />
                                <button
                                  type="button"
                                  className="btn btn-link p-0"
                                  aria-label="Save"
                                  disabled={isUpdatingShare}
                                  onClick={() => void handleSaveShare(row)}
                                >
                                  <Check size={18} color="#198754" />
                                </button>
                                <button
                                  type="button"
                                  className="btn btn-link p-0"
                                  aria-label="Cancel"
                                  disabled={isUpdatingShare}
                                  onClick={() => {
                                    setEditingRowId(null);
                                    setDraftShareValue("");
                                  }}
                                >
                                  <X size={18} color="var(--color-red)" />
                                </button>
                              </>
                            ) : (
                              <>
                                {/* Always show revenue_share_percentage from API (or local edit) */}
                                <span>
                                  {Math.round(row.revenue_share_percentage)}%
                                </span>
                                {!isRemoved && !isInvited && (
                                  <button
                                    type="button"
                                    className="btn btn-link p-0"
                                    aria-label="Edit revenue share"
                                    onClick={() => handleEditShare(row)}
                                  >
                                    <Edit2 size={18} color="var(--bg-third)" />
                                  </button>
                                )}
                              </>
                            )}
                          </div>
                        </td>
                        <td className="align-middle">
                          {isRemoved ? (
                            <Link
                              href="/invite-creator"
                              className="button-style btn-outline-first small-btn w-fit-content h-32 px-3 text-xs"
                              style={{ width: 134 }}
                            >
                              Invite again
                            </Link>
                          ) : (
                            <button
                              type="button"
                              className="button-style btn-outline-second small-btn w-fit-content h-32 px-3 text-xs"
                              data-bs-toggle="modal"
                              data-bs-target="#removeCreatorModal"
                              style={{ width: 134 }}
                              onClick={() => setPendingRemoveId(row.id)}
                            >
                              Remove Creator
                            </button>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>

              {!isLoading && totalPages > 0 && totalItems > 0 && (
                <>
                  <div
                    className="dataTables_info"
                    id="DataTables_Table_0_info"
                    role="status"
                    aria-live="polite"
                  >
                    {`Showing ${(currentPage - 1) * itemsPerPage + 1} to ${Math.min(
                      currentPage * itemsPerPage,
                      totalItems,
                    )} of ${formatNumber(totalItems)} entries`}
                  </div>

                  <div
                    className="dataTables_paginate paging_simple_numbers"
                    id="DataTables_Table_0_paginate"
                  >
                    <Link
                      href="#"
                      className={`paginate_button previous ${currentPage === 1 ? "disabled" : ""}`}
                      aria-controls="DataTables_Table_0"
                      aria-disabled={currentPage === 1}
                      role="button"
                      tabIndex={currentPage === 1 ? -1 : 0}
                      id="DataTables_Table_0_previous"
                      onClick={(e) => {
                        e.preventDefault();
                        if (currentPage !== 1) {
                          onPageChange(currentPage - 1);
                        }
                      }}
                    >
                      Previous
                    </Link>

                    <span>
                      <Link
                        href="#"
                        className="paginate_button current"
                        aria-controls="DataTables_Table_0"
                        role="button"
                        aria-current="page"
                        tabIndex={0}
                        onClick={(e) => e.preventDefault()}
                      >
                        {currentPage}
                      </Link>
                    </span>

                    <Link
                      href="#"
                      className={`paginate_button next ${currentPage === totalPages ? "disabled" : ""}`}
                      aria-controls="DataTables_Table_0"
                      aria-disabled={currentPage === totalPages}
                      role="button"
                      tabIndex={currentPage === totalPages ? -1 : 0}
                      id="DataTables_Table_0_next"
                      onClick={(e) => {
                        e.preventDefault();
                        if (currentPage !== totalPages) {
                          onPageChange(currentPage + 1);
                        }
                      }}
                    >
                      Next
                    </Link>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        <section
          className="modal fade my-modal"
          id="removeCreatorModal"
          aria-hidden="true"
        >
          <div className="modal-dialog modal-dialog-centered">
            <div className="modal-content rounded-4">
              <div className="modal-body text-center p-3">
                <div className="modal-name mb-0 d-flex justify-content-end">
                  <button
                    type="button"
                    className="btn-close opacity-50"
                    data-bs-dismiss="modal"
                    aria-label="Close"
                  />
                </div>
                <h5 className="congratulations text-capitalize color-content mb-2">
                  Remove Creator?
                </h5>
                <p className="text-sm mb-3 px-md-4">
                  This will remove the creator from your agency. Historical data
                  will remain intact, but new activity will not be tracked under
                  your account.
                </p>
                <div className="card-btn-area justify-content-center mb-2 mt-3 px-md-4 d-flex flex-column flex-md-row gap-2">
                  <button
                    type="button"
                    className="w-100 h-32 text-sm btn-second btn-second-pink small-btn"
                    data-bs-dismiss="modal"
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    className="w-100 h-32 text-sm btn-first btn-first-pink small-btn"
                    data-bs-dismiss="modal"
                    disabled={isRemovingCreator}
                    onClick={confirmRemoveCreator}
                  >
                    {isRemovingCreator ? "Removing..." : "Confirm Remove"}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
}
