'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { MetricCard } from '@/components/dashboard/MetricCard';
import { PeriodSelector, PeriodType } from '@/components/dashboard';
import { formatPeriodLabel } from '@/lib/stats-utils';
import styles from './PlatformAnalyticsPanel.module.css';

interface MetricData {
  current: number;
  previous: number;
  changePercent: number;
}

interface PerformanceStats {
  traffic: MetricData;
  inquiries: MetricData;
  clicks: {
    amsoil: MetricData;
    internal: MetricData;
    social: MetricData;
    external: MetricData;
  };
  period: {
    type: string;
    start: string;
    end: string;
    previousStart: string;
    previousEnd: string;
  };
}

export function PlatformAnalyticsPanel() {
  const [period, setPeriod] = useState<PeriodType>('30d');
  const [customStart, setCustomStart] = useState<string>();
  const [customEnd, setCustomEnd] = useState<string>();
  const [stats, setStats] = useState<PerformanceStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // Bumped by the retry button so a manual reload runs through the same
  // AbortController-managed effect (and is cancelled on unmount) as the
  // period-driven fetches, rather than firing an uncancellable fetch.
  const [reloadKey, setReloadKey] = useState(0);

  const fetchStats = useCallback(
    async (signal?: AbortSignal) => {
      setLoading(true);
      setError(null);
      try {
        const params = new URLSearchParams({ period });
        if (period === 'custom' && customStart && customEnd) {
          params.set('start', customStart);
          params.set('end', customEnd);
        }
        const res = await fetch(`/api/admin/performance?${params}`, { signal });
        const data = await res.json();
        if (signal?.aborted) return;
        if (!res.ok) {
          // Prefer the human-readable message; fall back to the machine code.
          setError(data.message || data.error || 'Failed to load stats');
          return;
        }
        setStats(data);
      } catch {
        // An aborted request is expected on rapid period switches — ignore it
        // so a stale fetch can't overwrite the newer one's state.
        if (signal?.aborted) return;
        setError('Failed to load stats');
      } finally {
        if (!signal?.aborted) setLoading(false);
      }
    },
    [period, customStart, customEnd]
  );

  useEffect(() => {
    // Cancel the previous fetch when the period changes (or a retry is
    // requested) so a slower stale response can't land after (and clobber)
    // the newer one, and so an in-flight fetch is aborted on unmount.
    const controller = new AbortController();
    fetchStats(controller.signal);
    return () => controller.abort();
  }, [fetchStats, reloadKey]);

  const handlePeriodChange = (newPeriod: PeriodType, start?: string, end?: string) => {
    setPeriod(newPeriod);
    setCustomStart(start);
    setCustomEnd(end);
  };

  const getPeriodLabel = () => {
    if (!stats) return '';
    return formatPeriodLabel(stats.period.type, stats.period.start, stats.period.end);
  };

  return (
    <div className={styles.container}>
      <div className={styles.periodHeader}>
        <span className={styles.periodLabel}>{getPeriodLabel()}</span>
        <PeriodSelector value={period} onChange={handlePeriodChange} allowCustomRange />
      </div>

      {loading ? (
        <div className={styles.loading}>
          <div className={styles.spinner} />
          <span>Loading...</span>
        </div>
      ) : error ? (
        <div className={styles.error}>
          <p>{error}</p>
          <button className={styles.retryButton} onClick={() => setReloadKey((k) => k + 1)}>
            Try Again
          </button>
        </div>
      ) : stats ? (
        <>
          <section className={styles.section}>
            <h3 className={styles.sectionTitle}>Overview</h3>
            <div className={styles.metricsGrid}>
              <MetricCard
                label="Traffic"
                value={stats.traffic.current}
                subLabel="Total Pageviews"
                changePercent={stats.traffic.changePercent}
              />
              <MetricCard
                label="Inquiries"
                value={stats.inquiries.current}
                subLabel="Form Submissions"
                changePercent={stats.inquiries.changePercent}
              />
            </div>
          </section>

          <section className={styles.section}>
            <h3 className={styles.sectionTitle}>Link Clicks</h3>
            <div className={styles.clicksGrid}>
              <MetricCard
                label="AMSOIL"
                value={stats.clicks.amsoil.current}
                subLabel="Shop & Product Links"
                changePercent={stats.clicks.amsoil.changePercent}
              />
              <MetricCard
                label="Internal"
                value={stats.clicks.internal.current}
                subLabel="Site Navigation"
                changePercent={stats.clicks.internal.changePercent}
              />
              <MetricCard
                label="Social"
                value={stats.clicks.social.current}
                subLabel="Social Media"
                changePercent={stats.clicks.social.changePercent}
              />
              <MetricCard
                label="External"
                value={stats.clicks.external.current}
                subLabel="Other Websites"
                changePercent={stats.clicks.external.changePercent}
              />
            </div>
          </section>

          <p className={styles.comparisonNote}>
            Comparing to previous period: {stats.period.previousStart} to {stats.period.previousEnd}
          </p>
        </>
      ) : null}
    </div>
  );
}
