import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import DefaultPageLayout from "@/components/DefaultPageLayout";
import ProOnlyMessage from "@/components/ProOnlyMessage";
import { getRouteVisiblity } from "@libs/menu-visibility";
import { ToastContainer, useToast } from "@libs/toast";
import { buildUrl } from "@/libs/url";
import { formatDateTimeForSite } from "@/libs/dateTime";
import {
  RefreshCw,
  CheckCircle,
  XCircle,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

const StatusBadge = ({ status }) => {
  if (status === "failed") {
    return (
      <span className="arraysubs-job-status arraysubs-job-status--failed">
        <XCircle size={14} />
        <span>{__("Failed", "arraysubs")}</span>
      </span>
    );
  }

  return (
    <span className="arraysubs-job-status arraysubs-job-status--success">
      <CheckCircle size={14} />
      <span>{__("Success", "arraysubs")}</span>
    </span>
  );
};

const JobContent = () => {
  const { env } = window.arraySubs;
  const { toasts, showToast, removeToast } = useToast();
  const [loading, setLoading] = useState(true);
  const [logs, setLogs] = useState([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const [page, setPage] = useState(1);
  const perPage = 30;

  const [filters, setFilters] = useState({
    date_from: "",
    date_to: "",
  });

  const fetchLogs = useCallback(
    async (currentPage = 1, currentFilters = filters) => {
      setLoading(true);
      try {
        const params = {
          page: currentPage,
          per_page: perPage,
        };

        if (currentFilters.date_from) {
          params.date_from = currentFilters.date_from;
        }
        if (currentFilters.date_to) {
          params.date_to = currentFilters.date_to;
        }

        const url = buildUrl(
          `${env.apiBaseUrl}arraysubs/v1/audits/scheduled-job-logs`,
          params,
        );
        const response = await fetch(url, {
          headers: { "X-WP-Nonce": env.nonce },
        });

        if (!response.ok) {
          throw new Error(
            __("Failed to fetch scheduled-job logs", "arraysubs"),
          );
        }

        const result = await response.json();
        setLogs(result.content?.logs || []);
        setTotal(result.content?.total || 0);
        setTotalPages(result.content?.total_pages || 0);
        setPage(result.content?.page || 1);
      } catch (error) {
        showToast(error.message, "error");
      } finally {
        setLoading(false);
      }
    },
    [env, filters],
  );

  useEffect(() => {
    fetchLogs(1, filters);
  }, []);

  const handleFilterChange = (key, value) => {
    const updated = { ...filters, [key]: value };
    setFilters(updated);
    fetchLogs(1, updated);
  };

  const handlePageChange = (newPage) => {
    if (newPage < 1 || newPage > totalPages) {
      return;
    }
    fetchLogs(newPage, filters);
  };

  const handleReset = () => {
    const reset = { date_from: "", date_to: "" };
    setFilters(reset);
    fetchLogs(1, reset);
  };

  const formatTimestamp = (ts) => {
    if (!ts) {
      return "\u2014";
    }
    return formatDateTimeForSite(ts, "\u2014");
  };

  const formatHookLabel = (hook) => {
    if (!hook) {
      return "\u2014";
    }
    return hook
      .replace("arraysubs_", "")
      .replace(/_/g, " ")
      .replace(/\b\w/g, (c) => c.toUpperCase());
  };

  return (
    <>
      {/* Date Range Filter */}
      <div className="arraysubs-audit-filters">
        <div className="arraysubs-audit-filters__row">
          <label className="arraysubs-job-filter-label">
            {__("From", "arraysubs")}
          </label>
          <input
            type="date"
            value={filters.date_from}
            onChange={(e) => handleFilterChange("date_from", e.target.value)}
            className="arraysubs-audit-filters__date"
          />

          <label className="arraysubs-job-filter-label">
            {__("To", "arraysubs")}
          </label>
          <input
            type="date"
            value={filters.date_to}
            onChange={(e) => handleFilterChange("date_to", e.target.value)}
            className="arraysubs-audit-filters__date"
          />

          <button
            type="button"
            className="button button-small"
            onClick={handleReset}
          >
            {__("Reset", "arraysubs")}
          </button>

          <button
            type="button"
            className="button button-small"
            onClick={() => fetchLogs(page, filters)}
            disabled={loading}
          >
            <RefreshCw size={14} className={loading ? "arraysubs-spin" : ""} />
          </button>
        </div>
      </div>

      {/* Job Logs Table */}
      <div className="arraysubs-audit-table-wrap">
        {loading && logs.length === 0 ? (
          <p className="arraysubs-loading">
            {__("Loading scheduled-job logs...", "arraysubs")}
          </p>
        ) : logs.length === 0 ? (
          <p className="arraysubs-audit-empty">
            {__(
              "No scheduled-job logs found. Logs are recorded when Action Scheduler runs subscription jobs.",
              "arraysubs",
            )}
          </p>
        ) : (
          <table className="wp-list-table widefat fixed striped arraysubs-audit-table">
            <thead>
              <tr>
                <th className="arraysubs-audit-table__col--date">
                  {__("Date", "arraysubs")}
                </th>
                <th className="arraysubs-job-table__col--status">
                  {__("Status", "arraysubs")}
                </th>
                <th className="arraysubs-job-table__col--hook">
                  {__("Job", "arraysubs")}
                </th>
                <th className="arraysubs-job-table__col--detail">
                  {__("Details", "arraysubs")}
                </th>
              </tr>
            </thead>
            <tbody>
              {logs.map((log) => (
                <tr
                  key={log.id}
                  className={
                    log.job_status === "failed"
                      ? "arraysubs-job-row--failed"
                      : ""
                  }
                >
                  <td className="arraysubs-audit-table__col--date">
                    {formatTimestamp(log.date_timestamp)}
                  </td>
                  <td className="arraysubs-job-table__col--status">
                    <StatusBadge status={log.job_status} />
                  </td>
                  <td className="arraysubs-job-table__col--hook">
                    <span className="arraysubs-job-hook-label">
                      {formatHookLabel(log.job_hook)}
                    </span>
                    {log.subscription_id > 0 && (
                      <a
                        href={`#/subscriptions/detail/${log.subscription_id}`}
                        className="arraysubs-audit-sub-link arraysubs-job-sub-link"
                      >
                        #{log.subscription_id}
                      </a>
                    )}
                  </td>
                  <td
                    className="arraysubs-job-table__col--detail"
                    dangerouslySetInnerHTML={{ __html: log.content }}
                  />
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="arraysubs-audit-pagination">
          <button
            type="button"
            className="button button-small"
            disabled={page <= 1}
            onClick={() => handlePageChange(page - 1)}
          >
            <ChevronLeft size={16} />
            {__("Previous", "arraysubs")}
          </button>
          <span className="arraysubs-audit-pagination__info">
            {__("Page", "arraysubs")} {page} {__("of", "arraysubs")}{" "}
            {totalPages}
            <span className="arraysubs-audit-pagination__total">
              ({total} {__("total", "arraysubs")})
            </span>
          </span>
          <button
            type="button"
            className="button button-small"
            disabled={page >= totalPages}
            onClick={() => handlePageChange(page + 1)}
          >
            {__("Next", "arraysubs")}
            <ChevronRight size={16} />
          </button>
        </div>
      )}

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

const ScheduledJobLogs = () => {
  const menuItems = window.arraySubs?.menu?.items || [];
  const visibility = getRouteVisiblity("/audits/scheduled-job-logs", menuItems);
  const isProActive = visibility === 1;

  return (
    <DefaultPageLayout
      title={__("Scheduled-Job Logs", "arraysubs")}
      subtitle={
        isProActive
          ? __(
              "Execution history for all scheduled subscription jobs.",
              "arraysubs",
            )
          : ""
      }
    >
      {isProActive ? <JobContent /> : <ProOnlyMessage />}
    </DefaultPageLayout>
  );
};

export default ScheduledJobLogs;
