'use client';

/**
 * Exploitation Sources Page — Standalone page for the Sources analytics detail view.
 *
 * Renders the SourcesTab content from the analytics detail page as its own route.
 * Accessible via sidebar navigation under Analítica > Exploitation Sources.
 */

import { useState, useMemo } from 'react';
import { clientPortal } from '@/lib/mock-data';
import { useCompactCurrencyFormatter } from '@/lib/hooks/useCurrencyFormatter';
import { chartColorArray } from '@/lib/constants/theme';
import type { PortalSourceDetail } from '@/lib/mock-data/types';

// ─── Helper Components ───────────────────────────────────────────────────────

function ChevronIcon({ expanded }: { expanded: boolean }) {
  return (
    <svg
      className={`h-4 w-4 text-divisi-text-secondary transition-transform duration-200 ${
        expanded ? 'rotate-90' : ''
      }`}
      fill="none"
      viewBox="0 0 24 24"
      stroke="currentColor"
      strokeWidth={2}
    >
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
    </svg>
  );
}

function PercentageBadge({ value }: { value: number }) {
  const isPositive = value >= 0;
  return (
    <span className={`text-xs font-medium ${isPositive ? 'text-green-400' : 'text-red-400'}`}>
      {isPositive ? '+' : ''}{value.toFixed(1)}%
    </span>
  );
}

function TotalEarningsCard({ total, trend }: { total: number; trend: number }) {
  const fmtMoney = useCompactCurrencyFormatter();
  return (
    <div className="rounded-xl border border-divisi-border bg-divisi-card p-4">
      <p className="text-xs text-divisi-text-secondary uppercase tracking-wide">Ganancias totales</p>
      <p className="mt-1 text-2xl font-bold text-divisi-text-primary">{fmtMoney(total)}</p>
      <PercentageBadge value={trend} />
    </div>
  );
}

// ─── Main Component ──────────────────────────────────────────────────────────

function SourcesDetailView({ data }: { data: PortalSourceDetail[] }) {
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());
  const fmtMoney = useCompactCurrencyFormatter();
  const sorted = useMemo(
    () => [...data].sort((a, b) => b.currentPeriodAmount - a.currentPeriodAmount),
    [data]
  );
  const total = sorted.reduce((sum, s) => sum + s.currentPeriodAmount, 0);
  const totalLast = sorted.reduce((sum, s) => sum + s.lastPeriodAmount, 0);
  const trend = totalLast > 0 ? ((total - totalLast) / totalLast) * 100 : 0;

  const toggleRow = (platform: string) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(platform)) next.delete(platform);
      else next.add(platform);
      return next;
    });
  };

  return (
    <div className="space-y-6">
      <h1 className="text-xl font-bold text-divisi-text-primary">Resumen de Fuentes de Explotación</h1>
      <div className="flex flex-col gap-6 lg:flex-row">
        {/* Left Panel */}
        <div className="w-full space-y-4 lg:w-[30%]">
          <TotalEarningsCard total={total} trend={trend} />
          <div className="rounded-xl border border-divisi-border bg-divisi-card p-4">
            <ul className="space-y-3">
              {sorted.slice(0, 10).map((source, i) => {
                const pct = total > 0 ? (source.currentPeriodAmount / total) * 100 : 0;
                return (
                  <li key={source.platform} className="space-y-1">
                    <div className="flex items-center justify-between gap-2">
                      <span className="text-sm text-divisi-text-primary truncate">
                        {source.platform}
                      </span>
                      <div className="flex items-center gap-2">
                        <span className="text-xs text-divisi-text-primary">
                          {fmtMoney(source.currentPeriodAmount)}
                        </span>
                        <PercentageBadge value={source.percentageChange} />
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <div className="h-1.5 flex-1 rounded-full bg-divisi-bg">
                        <div
                          className="h-1.5 rounded-full transition-all"
                          style={{
                            width: `${Math.min(pct, 100)}%`,
                            backgroundColor: chartColorArray[i % chartColorArray.length],
                          }}
                        />
                      </div>
                      <span className="text-xs text-divisi-text-secondary w-10 text-right">
                        {pct.toFixed(1)}%
                      </span>
                    </div>
                  </li>
                );
              })}
            </ul>
          </div>
        </div>

        {/* Right Panel - Table */}
        <div className="w-full lg:w-[70%]">
          <div className="rounded-xl border border-divisi-border bg-divisi-card overflow-hidden">
            <div className="grid grid-cols-[40px_1fr_140px_180px] gap-2 border-b border-divisi-border px-4 py-3 text-xs font-semibold uppercase text-divisi-text-secondary">
              <span>#</span>
              <span>Las 20 Fuentes</span>
              <span className="text-right">Último Período</span>
              <span className="text-right">Período Actual</span>
            </div>
            <div className="divide-y divide-divisi-border">
              {sorted.map((source, i) => {
                const isExpanded = expandedRows.has(source.platform);
                return (
                  <div key={source.platform}>
                    <div
                      className="grid grid-cols-[40px_1fr_140px_180px] gap-2 px-4 py-3 items-center cursor-pointer hover:bg-white/[0.02] transition-colors"
                      onClick={() => toggleRow(source.platform)}
                    >
                      <span className="text-sm text-divisi-text-secondary">{i + 1}</span>
                      <div className="flex items-center gap-2">
                        <ChevronIcon expanded={isExpanded} />
                        <span className="text-sm font-medium text-divisi-text-primary">
                          {source.platform}
                        </span>
                      </div>
                      <span className="text-sm text-divisi-text-secondary text-right">
                        {fmtMoney(source.lastPeriodAmount)}
                      </span>
                      <div className="flex items-center justify-end gap-2">
                        <span className="text-sm text-divisi-text-primary">
                          {fmtMoney(source.currentPeriodAmount)}
                        </span>
                        <PercentageBadge value={source.percentageChange} />
                      </div>
                    </div>
                    {isExpanded && (
                      <div className="grid grid-cols-3 gap-4 px-4 pb-3 pt-1 pl-14 bg-white/[0.01]">
                        <div>
                          <p className="text-xs text-divisi-text-secondary">Top Canción</p>
                          <p className="text-sm text-divisi-text-primary">{source.topSong}</p>
                          <p className="text-xs text-divisi-text-secondary">{fmtMoney(source.topSongAmount)}</p>
                        </div>
                        <div>
                          <p className="text-xs text-divisi-text-secondary">Categoría superior</p>
                          <p className="text-sm text-divisi-text-primary">{source.topCategory}</p>
                          <p className="text-xs text-divisi-text-secondary">{fmtMoney(source.topCategoryAmount)}</p>
                        </div>
                        <div>
                          <p className="text-xs text-divisi-text-secondary">Territorio superior</p>
                          <p className="text-sm text-divisi-text-primary">{source.topTerritory}</p>
                          <p className="text-xs text-divisi-text-secondary">{fmtMoney(source.topTerritoryAmount)}</p>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default function SourcesPage() {
  return <SourcesDetailView data={clientPortal.sourceDetails} />;
}
