'use client';

import { useState, useEffect, useCallback } from 'react';
import Link from 'next/link';
import { MetricCard, PeriodSelector, PeriodType } from '@/components/dashboard';
import TierGate from '@/components/ui/TierGate';
import { formatPeriodLabel } from '@/lib/stats-utils';
import styles from './stats.module.css';

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

interface TopLink {
  href: string;
  count: number;
  title?: string;
}

interface DashboardStats {
  traffic: MetricData;
  inquiries: MetricData;
  clicks: {
    amsoil: MetricData;
    internal: MetricData;
    social: MetricData;
    external: MetricData;
  };
  topLinks?: {
    amsoil: TopLink[];
    internal: TopLink[];
    social: TopLink[];
    external: TopLink[];
  };
  period: {
    type: string;
    start: string;
    end: string;
    previousStart: string;
    previousEnd: string;
  };
  /** Present when admin is supporting a dealer who doesn't normally have analytics access */
  adminBypass?: { dealerTier: string };
}

type ClickCategory = 'amsoil' | 'internal' | 'social' | 'external';

const categoryLabels: Record<ClickCategory, string> = {
  amsoil: 'AMSOIL Links',
  internal: 'Internal Links',
  social: 'Social Links',
  external: 'External Links',
};

/**
 * Format a URL for display
 */
function formatUrl(href: string): string {
  if (!href || href.trim() === '') return '(empty)';
  if (href === '/') return 'Homepage';

  // Remove protocol
  let formatted = href.replace(/^https?:\/\//, '');
  // Remove trailing slash
  formatted = formatted.replace(/\/$/, '');
  // Remove www.
  formatted = formatted.replace(/^www\./, '');

  return formatted;
}

export default function StatsPage() {
  const [period, setPeriod] = useState<PeriodType>('30d');
  const [customStart, setCustomStart] = useState<string>();
  const [customEnd, setCustomEnd] = useState<string>();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedCategory, setSelectedCategory] = useState<ClickCategory | null>(null);

  const fetchStats = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      let url = `/api/stats/dashboard?period=${period}&includeTopLinks=true`;
      if (period === 'custom' && customStart && customEnd) {
        url += `&start=${customStart}&end=${customEnd}`;
      }

      const response = await fetch(url);
      const data = await response.json();

      if (!response.ok) {
        if (data.error === 'upgrade_required') {
          setError('upgrade_required');
        } else {
          setError(data.message || 'Failed to load stats');
        }
        return;
      }

      setStats(data);
    } catch {
      setError('Failed to load stats');
    } finally {
      setLoading(false);
    }
  }, [period, customStart, customEnd]);

  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

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

  const handleCategoryClick = (category: ClickCategory) => {
    setSelectedCategory(selectedCategory === category ? null : category);
  };

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

  if (error === 'upgrade_required') {
    return (
      <TierGate
        title="Enhanced Tier Required"
        description="Site Analytics shows you how your dealer site is performing with detailed traffic and engagement metrics."
        features={[
          'Traffic and pageview metrics',
          'Lead and inquiry tracking',
          'Click analytics by category (AMSOIL, internal, social, external)',
          'Top performing links breakdown',
          'Custom date range analysis',
          'Year-over-year comparisons',
        ]}
        requiredTier="enhanced"
        backLink={{ href: '/dashboard', text: 'Back to Dashboard' }}
      />
    );
  }

  const selectedLinks = selectedCategory && stats?.topLinks?.[selectedCategory];
  const locked = !!stats?.adminBypass;
  const dealerTierLabel = stats?.adminBypass
    ? stats.adminBypass.dealerTier.charAt(0).toUpperCase() + stats.adminBypass.dealerTier.slice(1)
    : null;

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Link href="/dashboard" className={styles.backLink}>
          ← Back to Dashboard
        </Link>
        <h1 className={styles.title}>Site Analytics</h1>
        <p className={styles.subtitle}>Track your site&apos;s performance and visitor engagement</p>
      </div>

      {locked && dealerTierLabel && (
        <div className={styles.adminBypassBanner}>
          Admin support view — this dealer is on the <strong>{dealerTierLabel}</strong> plan and
          does not have access to analytics. Metrics are shown for support purposes only.
        </div>
      )}

      <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 stats...</span>
        </div>
      ) : error ? (
        <div className={styles.error}>
          <p>{error}</p>
          <button className={styles.retryButton} onClick={fetchStats}>
            Try Again
          </button>
        </div>
      ) : stats ? (
        <>
          <section className={styles.section}>
            <h2 className={styles.sectionTitle}>Overview</h2>
            <div className={styles.metricsGrid}>
              <MetricCard
                label="Traffic"
                value={stats.traffic.current}
                subLabel="Total Pageviews"
                changePercent={stats.traffic.changePercent}
                locked={locked}
              />
              <MetricCard
                label="Inquiries"
                value={stats.inquiries.current}
                subLabel="Form Submissions"
                changePercent={stats.inquiries.changePercent}
                locked={locked}
              />
            </div>
          </section>

          <section className={styles.section}>
            <h2 className={styles.sectionTitle}>Link Clicks</h2>
            <p className={styles.sectionHint}>Click a category to see top links</p>
            <div className={styles.clicksGrid}>
              <ClickCard
                category="amsoil"
                label="AMSOIL Links"
                value={stats.clicks.amsoil.current}
                subLabel="Shop & Product Links"
                changePercent={stats.clicks.amsoil.changePercent}
                isSelected={selectedCategory === 'amsoil'}
                onClick={() => handleCategoryClick('amsoil')}
                locked={locked}
              />
              <ClickCard
                category="internal"
                label="Internal Links"
                value={stats.clicks.internal.current}
                subLabel="Site Navigation"
                changePercent={stats.clicks.internal.changePercent}
                isSelected={selectedCategory === 'internal'}
                onClick={() => handleCategoryClick('internal')}
                locked={locked}
              />
              <ClickCard
                category="social"
                label="Social Links"
                value={stats.clicks.social.current}
                subLabel="Social Media"
                changePercent={stats.clicks.social.changePercent}
                isSelected={selectedCategory === 'social'}
                onClick={() => handleCategoryClick('social')}
                locked={locked}
              />
              <ClickCard
                category="external"
                label="External Links"
                value={stats.clicks.external.current}
                subLabel="Other Websites"
                changePercent={stats.clicks.external.changePercent}
                isSelected={selectedCategory === 'external'}
                onClick={() => handleCategoryClick('external')}
                locked={locked}
              />
            </div>

            {/* Full-width breakdown panel */}
            {selectedCategory && (
              <div className={styles.breakdownPanel}>
                <h3 className={styles.breakdownTitle}>Top {categoryLabels[selectedCategory]}</h3>
                {selectedLinks && selectedLinks.length > 0 ? (
                  <ul className={styles.linkList}>
                    {selectedLinks.map((link, index) => (
                      <li key={index} className={styles.linkItem}>
                        <span className={styles.linkRank}>{index + 1}</span>
                        <span className={styles.linkHref} title={link.href}>
                          {link.title || formatUrl(link.href)}
                        </span>
                        <span className={styles.linkCount}>{link.count} clicks</span>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p className={styles.noData}>No link clicks recorded yet</p>
                )}
              </div>
            )}
          </section>

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

/**
 * Simple click card component (non-expandable)
 */
function ClickCard({
  label,
  subLabel,
  value,
  changePercent,
  isSelected,
  onClick,
  locked,
}: {
  category?: ClickCategory;
  label: string;
  subLabel: string;
  value: number;
  changePercent: number;
  isSelected: boolean;
  onClick: () => void;
  locked?: boolean;
}) {
  const isPositive = changePercent >= 0;

  return (
    <button
      className={`${styles.clickCard} ${isSelected ? styles.clickCardSelected : ''} ${locked ? styles.clickCardLocked : ''}`}
      onClick={onClick}
      disabled={locked}
      // A disabled control has no pressed/unpressed state in the a11y model,
      // so omit aria-pressed entirely while locked.
      aria-pressed={locked ? undefined : isSelected}
    >
      <span className={styles.clickCardLabel}>{label}</span>
      <div className={styles.clickCardValueRow}>
        <span className={styles.clickCardValue}>{value.toLocaleString()}</span>
        <span
          className={`${styles.clickCardChange} ${isPositive ? styles.positive : styles.negative}`}
        >
          {isPositive ? '↑' : '↓'} {Math.abs(changePercent).toFixed(1)}%
        </span>
      </div>
      <span className={styles.clickCardSubLabel}>{subLabel}</span>
    </button>
  );
}
