import React, { useEffect, useMemo, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import { __, sprintf } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import { ToastContainer, useToast } from "@libs/toast";
import { buildUrl } from "@/libs/url";

const formatFeatureValue = (feature) => {
  if (feature?.type === "toggle") {
    const normalizedValue = String(feature?.value || "").toLowerCase();

    return ["yes", "true", "1", "on"].includes(normalizedValue)
      ? __("Yes", "arraysubs")
      : __("No", "arraysubs");
  }

  return feature?.value || "—";
};

const formatUsageValue = (usage) => {
  if (!usage) {
    return "—";
  }

  return `${usage.used} / ${
    usage.is_unlimited ? __("Unlimited", "arraysubs") : usage.limit
  }`;
};

const FeatureTable = ({
  title,
  subscriptionId,
  subscriptionLink,
  features,
  showUsage,
}) => {
  const headingColumns = showUsage ? 4 : 3;

  return (
    <table className="arraysubs-member-insight__table">
      <thead>
        <tr>
          <th colSpan={headingColumns}>
            <div className="arraysubs-member-insight__table-actions">
              <span>{title}</span>
              {subscriptionId && subscriptionLink ? (
                <Link to={subscriptionLink}>
                  {sprintf(__("Subscription #%d", "arraysubs"), subscriptionId)}
                </Link>
              ) : null}
            </div>
          </th>
        </tr>
        <tr>
          <th>{__("Feature", "arraysubs")}</th>
          <th>{__("Type", "arraysubs")}</th>
          <th>{__("Entitlement", "arraysubs")}</th>
          {showUsage ? <th>{__("Usage", "arraysubs")}</th> : null}
        </tr>
      </thead>
      <tbody>
        {features.map((feature) => (
          <tr key={feature.id || feature.name}>
            <td>{feature.name}</td>
            <td>{feature.type}</td>
            <td>{formatFeatureValue(feature)}</td>
            {showUsage ? <td>{formatUsageValue(feature.usage)}</td> : null}
          </tr>
        ))}
      </tbody>
    </table>
  );
};

const SubscriptionFeatureLog = () => {
  const location = useLocation();
  const { env } = window.arraySubs;
  const { toasts, showToast, removeToast } = useToast();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);

  const userId = useMemo(() => {
    const params = new URLSearchParams(location.search);
    return params.get("user_id") || "";
  }, [location.search]);

  useEffect(() => {
    if (!userId) {
      setLoading(false);
      setData(null);
      return undefined;
    }

    const fetchFeatureLog = async () => {
      setLoading(true);

      try {
        const response = await fetch(
          buildUrl(`${env.apiBaseUrl}arraysubs/v1/features/log`, {
            user_id: userId,
          }),
          {
            headers: {
              "X-WP-Nonce": env.nonce,
            },
          },
        );

        const result = await response.json();

        if (!response.ok) {
          throw new Error(
            result?.message || __("Failed to load feature log.", "arraysubs"),
          );
        }

        setData(result.content);
      } catch (error) {
        showToast(error.message, "error");
      } finally {
        setLoading(false);
      }
    };

    fetchFeatureLog();
    return undefined;
  }, [env.apiBaseUrl, env.nonce, showToast, userId]);

  if (loading) {
    return (
      <DefaultPageLayout title={__("Loading...", "arraysubs")}>
        <div className="arraysubs-loading">
          {__("Loading feature log...", "arraysubs")}
        </div>
      </DefaultPageLayout>
    );
  }

  if (!userId) {
    return (
      <DefaultPageLayout title={__("Feature Log", "arraysubs")}>
        <p>
          {__("A member is required to view the feature log.", "arraysubs")}
        </p>
        <Link to="/manage-members" className="button">
          {__("Back to Members", "arraysubs")}
        </Link>
      </DefaultPageLayout>
    );
  }

  if (!data) {
    return (
      <DefaultPageLayout title={__("Feature Log", "arraysubs")}>
        <p>{__("Feature log could not be loaded.", "arraysubs")}</p>
        <Link to={`/manage-members/${userId}`} className="button">
          {__("Back to Member", "arraysubs")}
        </Link>
      </DefaultPageLayout>
    );
  }

  const {
    customer,
    aggregation_mode: aggregationMode,
    features_data: featuresData,
    show_usage_in_admin: showUsageInAdmin,
  } = data;

  const isPerSubscription = aggregationMode === "per_subscription";

  return (
    <DefaultPageLayout
      title={__("Feature Log", "arraysubs")}
      subtitle={customer?.name || ""}
    >
      <div className="arraysubs-member-insight arraysubs-subscription-feature-log">
        <div className="arraysubs-member-insight__section arraysubs-member-insight__section--open">
          <div className="arraysubs-member-insight__section-body">
            <p>
              <strong>{__("Customer:", "arraysubs")}</strong> {customer?.name}
            </p>
            {customer?.email ? (
              <p>
                <strong>{__("Email:", "arraysubs")}</strong> {customer.email}
              </p>
            ) : null}

            <div className="arraysubs-member-insight__table-actions">
              <Link to={`/manage-members/${customer?.id || userId}`}>
                {__("Back to Member", "arraysubs")}
              </Link>
            </div>
          </div>
        </div>

        <div className="arraysubs-member-insight__section arraysubs-member-insight__section--open">
          <div className="arraysubs-member-insight__section-body">
            {isPerSubscription ? (
              featuresData?.length ? (
                featuresData.map((group) => (
                  <div
                    className="arraysubs-member-insight__table-wrapper"
                    key={group.subscription_id}
                  >
                    <FeatureTable
                      title={group.product_name}
                      subscriptionId={group.subscription_id}
                      subscriptionLink={`/subscriptions/detail/${group.subscription_id}`}
                      features={group.features || []}
                      showUsage={showUsageInAdmin}
                    />
                  </div>
                ))
              ) : (
                <p>
                  {__(
                    "No active subscription features were found.",
                    "arraysubs",
                  )}
                </p>
              )
            ) : featuresData?.length ? (
              <FeatureTable
                title={__("Combined Features", "arraysubs")}
                features={featuresData}
                showUsage={showUsageInAdmin}
              />
            ) : (
              <p>{__("No active features were found.", "arraysubs")}</p>
            )}
          </div>
        </div>
      </div>

      <ToastContainer toasts={toasts} removeToast={removeToast} />
    </DefaultPageLayout>
  );
};

export default SubscriptionFeatureLog;
