import React, { useState, useEffect, useCallback } from "react";
import { __ } from "@wordpress/i18n";
import { buildUrl } from "@libs/url";
import RetentionFilters from "./components/RetentionFilters";
import SummaryCards from "./components/SummaryCards";
import ChurnReasonsChart from "./components/ChurnReasonsChart";
import RetentionOfferChart from "./components/RetentionOfferChart";
import TrendChart from "./components/TrendChart";
import ActivityLogs from "./components/ActivityLogs";

const getDefaultDates = () => {
  const end = new Date();
  const start = new Date();
  start.setDate(start.getDate() - 30);

  const format = (d) => d.toISOString().split("T")[0];
  return { startDate: format(start), endDate: format(end) };
};

const RetentionAnalyticsPage = () => {
  const env = window.arraySubsRetention || {};
  const defaults = getDefaultDates();

  const [startDate, setStartDate] = useState(defaults.startDate);
  const [endDate, setEndDate] = useState(defaults.endDate);
  const [productIds, setProductIds] = useState([]);

  const [summaryData, setSummaryData] = useState(null);
  const [summaryLoading, setSummaryLoading] = useState(true);

  const fetchSummary = useCallback(async () => {
    setSummaryLoading(true);

    try {
      const params = {
        start_date: startDate,
        end_date: endDate,
      };

      if (productIds.length > 0) {
        params.product_ids = productIds.join(",");
      }

      const url = buildUrl(
        `${env.apiBaseUrl}arraysubs/v1/retention-analytics/summary`,
        params,
      );

      const response = await fetch(url, {
        headers: {
          "X-WP-Nonce": env.nonce,
        },
      });

      if (!response.ok) {
        throw new Error(__("Failed to fetch analytics data", "arraysubs"));
      }

      const result = await response.json();
      setSummaryData(result.content || result);
    } catch (error) {
      console.error("Retention analytics fetch error:", error);
      setSummaryData(null);
    } finally {
      setSummaryLoading(false);
    }
  }, [startDate, endDate, productIds, env.apiBaseUrl, env.nonce]);

  useEffect(() => {
    if (startDate && endDate) {
      fetchSummary();
    }
  }, [fetchSummary, startDate, endDate]);

  const handleFilterChange = (filters) => {
    if (filters.startDate) setStartDate(filters.startDate);
    if (filters.endDate) setEndDate(filters.endDate);
    if (filters.productIds !== undefined) setProductIds(filters.productIds);
  };

  return (
    <div className="woocommerce-layout arraysubs-retention-analytics-page">
      <div className="woocommerce-layout__header arraysubs-retention-analytics-page__header">
        <div className="woocommerce-layout__header-wrapper arraysubs-retention-analytics-page__header-wrapper">
          <div className="arraysubs-retention-analytics-page__header-copy">
            <h1 className="woocommerce-layout__header-heading arraysubs-retention-analytics-page__title">
              {__("Retention", "arraysubs")}
            </h1>
          </div>
        </div>
      </div>

      <div className="woocommerce-layout__main arraysubs-retention-analytics-page__main">
        <div className="woocommerce-analytics-report arraysubs-retention-analytics">
          <div className="arraysubs-retention-analytics__toolbar arraysubs-retention-analytics__section arraysubs-retention-analytics__section--filters">
            <RetentionFilters
              startDate={startDate}
              endDate={endDate}
              productIds={productIds}
              onFilterChange={handleFilterChange}
              apiBaseUrl={env.apiBaseUrl}
              nonce={env.nonce}
            />
          </div>

          <div className="arraysubs-retention-analytics__report-card arraysubs-retention-analytics__section arraysubs-retention-analytics__section--summary">
            <SummaryCards
              data={summaryData?.cards}
              loading={summaryLoading}
              currency={env.currency}
            />
          </div>

          <div className="arraysubs-retention-analytics__section arraysubs-retention-analytics__section--summary">
            <div className="arraysubs-retention-analytics__charts arraysubs-retention-analytics__section--charts">
              <div className="arraysubs-retention-analytics__charts-row">
                <ChurnReasonsChart
                  data={summaryData?.reasons}
                  loading={summaryLoading}
                  totalCancellations={
                    summaryData?.cards?.total_cancellations || 0
                  }
                />
                <RetentionOfferChart
                  data={summaryData?.offers}
                  loading={summaryLoading}
                />
              </div>

              <TrendChart data={summaryData?.trends} loading={summaryLoading} />
            </div>
          </div>

          <div className="arraysubs-retention-analytics__report-card arraysubs-retention-analytics__section arraysubs-retention-analytics__section--logs">
            <ActivityLogs
              startDate={startDate}
              endDate={endDate}
              productIds={productIds}
              apiBaseUrl={env.apiBaseUrl}
              nonce={env.nonce}
              currency={env.currency}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default RetentionAnalyticsPage;
