'use client';

/**
 * Analytics Detail Page — Tabbed drill-down view for analytics data.
 *
 * Displays detailed tables and summary panels for:
 * - Top Songs (MEJORES CANCIONES)
 * - Income Groups (GRUPOS DE INGRESOS MÁS ALTOS)
 * - Territories (TERRITORIOS PRINCIPALES)
 * - Exploitation Sources (RESUMEN DE FUENTES DE EXPLOTACIÓN)
 *
 * Accessed via "Ver más" links on the analytics cards.
 */

import { useState, useMemo, Suspense } from 'react';
import { useSearchParams } from 'next/navigation';
import { clientPortal } from '@/lib/mock-data';
import { useCompactCurrencyFormatter } from '@/lib/hooks/useCurrencyFormatter';
import { chartColorArray } from '@/lib/constants/theme';
import type {
  PortalSongDetail,
  PortalIncomeGroupDetail,
  PortalTerritoryDetail,
  PortalSourceDetail,
} from '@/lib/mock-data/types';
import PieChartWidget from '@/components/charts/PieChartWidget';
import BarChartWidget from '@/components/charts/BarChartWidget';

// ─── Types ───────────────────────────────────────────────────────────────────

type TabId = 'songs' | 'income' | 'territories' | 'sources';

interface TabConfig {
  id: TabId;
  label: string;
}

const TABS: TabConfig[] = [
  { id: 'songs', label: 'MEJORES CANCIONES' },
  { id: 'income', label: 'GRUPOS DE INGRESOS MÁS ALTOS' },
  { id: 'territories', label: 'TERRITORIOS PRINCIPALES' },
  { id: 'sources', label: 'RESUMEN DE FUENTES DE EXPLOTACIÓN' },
];

// ─── 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>
  );
}

// ─── Tab Content Components ──────────────────────────────────────────────────

function SongsTab({ data }: { data: PortalSongDetail[] }) {
  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 = (id: string) => {
    setExpandedRows((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  return (
    <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((song, i) => {
              const pct = total > 0 ? (song.currentPeriodAmount / total) * 100 : 0;
              return (
                <li key={song.id} className="space-y-1">
                  <div className="flex items-start justify-between gap-2">
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-medium text-divisi-text-primary truncate">
                        {i + 1}. {song.title}
                      </p>
                      <p className="text-xs text-divisi-text-secondary truncate">
                        {song.composers.join(', ')}
                      </p>
                    </div>
                    <span className="flex-shrink-0 text-xs font-medium text-divisi-text-primary">
                      {fmtMoney(song.currentPeriodAmount)}
                    </span>
                  </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">
          {/* Table Header */}
          <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 Mejores Canciones</span>
            <span className="text-right">Último Período</span>
            <span className="text-right">Período Actual</span>
          </div>
          {/* Table Body */}
          <div className="divide-y divide-divisi-border">
            {sorted.map((song, i) => {
              const isExpanded = expandedRows.has(song.id);
              return (
                <div key={song.id}>
                  <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(song.id)}
                  >
                    <span className="text-sm text-divisi-text-secondary">{i + 1}</span>
                    <div className="min-w-0 flex items-center gap-2">
                      <ChevronIcon expanded={isExpanded} />
                      <div className="min-w-0">
                        <p className="text-sm font-medium text-divisi-text-primary truncate">
                          {song.title}
                        </p>
                        <p className="text-xs text-divisi-text-secondary truncate">
                          {song.composers.join(', ')}
                        </p>
                      </div>
                    </div>
                    <span className="text-sm text-divisi-text-secondary text-right">
                      {fmtMoney(song.lastPeriodAmount)}
                    </span>
                    <div className="flex items-center justify-end gap-2">
                      <span className="text-sm text-divisi-text-primary">
                        {fmtMoney(song.currentPeriodAmount)}
                      </span>
                      <PercentageBadge value={song.percentageChange} />
                    </div>
                  </div>
                  {/* Expanded sub-row */}
                  {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">Categoría superior</p>
                        <p className="text-sm text-divisi-text-primary">{song.topCategory}</p>
                        <p className="text-xs text-divisi-text-secondary">{fmtMoney(song.topCategoryAmount)}</p>
                      </div>
                      <div>
                        <p className="text-xs text-divisi-text-secondary">Fuente principal</p>
                        <p className="text-sm text-divisi-text-primary">{song.topSource}</p>
                        <p className="text-xs text-divisi-text-secondary">{fmtMoney(song.topSourceAmount)}</p>
                      </div>
                      <div>
                        <p className="text-xs text-divisi-text-secondary">Territorio superior</p>
                        <p className="text-sm text-divisi-text-primary">{song.topTerritory}</p>
                        <p className="text-xs text-divisi-text-secondary">{fmtMoney(song.topTerritoryAmount)}</p>
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function IncomeTab({ data }: { data: PortalIncomeGroupDetail[] }) {
  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, g) => sum + g.currentPeriodAmount, 0);
  const totalLast = sorted.reduce((sum, g) => sum + g.lastPeriodAmount, 0);
  const trend = totalLast > 0 ? ((total - totalLast) / totalLast) * 100 : 0;

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

  const chartData = sorted.map((g) => ({ name: g.category, value: g.currentPeriodAmount }));

  return (
    <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">
          <PieChartWidget data={chartData} height={220} innerRadius={50} />
        </div>
        <div className="rounded-xl border border-divisi-border bg-divisi-card p-4">
          <ul className="space-y-2">
            {sorted.map((group, i) => (
              <li key={group.category} className="flex items-center gap-2">
                <div
                  className="h-3 w-3 rounded-sm flex-shrink-0"
                  style={{ backgroundColor: chartColorArray[i % chartColorArray.length] }}
                />
                <span className="text-sm text-divisi-text-primary flex-1 truncate">
                  {group.category}
                </span>
                <span className="text-xs text-divisi-text-secondary">
                  {fmtMoney(group.currentPeriodAmount)}
                </span>
              </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>Grupos De Ingresos Más Altos</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((group, i) => {
              const isExpanded = expandedRows.has(group.category);
              return (
                <div key={group.category}>
                  <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(group.category)}
                  >
                    <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">
                        {group.category}
                      </span>
                    </div>
                    <span className="text-sm text-divisi-text-secondary text-right">
                      {fmtMoney(group.lastPeriodAmount)}
                    </span>
                    <div className="flex items-center justify-end gap-2">
                      <span className="text-sm text-divisi-text-primary">
                        {fmtMoney(group.currentPeriodAmount)}
                      </span>
                      <PercentageBadge value={group.percentageChange} />
                    </div>
                  </div>
                  {isExpanded && (
                    <div className="pl-14 pr-4 pb-3 bg-white/[0.01] space-y-2">
                      {group.subCategories.map((sub) => (
                        <div
                          key={sub.name}
                          className="grid grid-cols-[1fr_140px_180px] gap-2 items-center"
                        >
                          <span className="text-xs text-divisi-text-secondary">{sub.name}</span>
                          <span className="text-xs text-divisi-text-secondary text-right">
                            {fmtMoney(sub.lastPeriodAmount)}
                          </span>
                          <div className="flex items-center justify-end gap-2">
                            <span className="text-xs text-divisi-text-primary">
                              {fmtMoney(sub.currentPeriodAmount)}
                            </span>
                            <PercentageBadge value={sub.percentageChange} />
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

function TerritoriesTab({ data }: { data: PortalTerritoryDetail[] }) {
  const fmtMoney = useCompactCurrencyFormatter();
  const sorted = useMemo(
    () => [...data].sort((a, b) => b.currentPeriodAmount - a.currentPeriodAmount),
    [data]
  );
  const total = sorted.reduce((sum, t) => sum + t.currentPeriodAmount, 0);
  const totalLast = sorted.reduce((sum, t) => sum + t.lastPeriodAmount, 0);
  const trend = totalLast > 0 ? ((total - totalLast) / totalLast) * 100 : 0;

  const chartData = sorted.slice(0, 10).map((t) => ({
    country: t.country,
    amount: t.currentPeriodAmount,
  }));

  return (
    <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">
          <BarChartWidget
            data={chartData}
            xKey="country"
            bars={[{ dataKey: 'amount', color: '#06b6d4', name: 'Ingresos' }]}
            height={220}
            layout="vertical"
          />
        </div>
        <div className="rounded-xl border border-divisi-border bg-divisi-card p-4">
          <ul className="space-y-2">
            {sorted.slice(0, 10).map((territory, i) => (
              <li key={territory.country} className="flex items-center gap-2">
                <div
                  className="h-3 w-3 rounded-sm flex-shrink-0"
                  style={{ backgroundColor: chartColorArray[i % chartColorArray.length] }}
                />
                <span className="text-sm text-divisi-text-primary flex-1 truncate">
                  {territory.country}
                </span>
                <span className="text-xs text-divisi-text-secondary">
                  {fmtMoney(territory.currentPeriodAmount)}
                </span>
              </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>Los 32 Territorios Principales</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((territory, i) => (
              <div
                key={territory.country}
                className="grid grid-cols-[40px_1fr_140px_180px] gap-2 px-4 py-3 items-center"
              >
                <span className="text-sm text-divisi-text-secondary">{i + 1}</span>
                <span className="text-sm font-medium text-divisi-text-primary uppercase">
                  {territory.country}
                </span>
                <span className="text-sm text-divisi-text-secondary text-right">
                  {fmtMoney(territory.lastPeriodAmount)}
                </span>
                <div className="flex items-center justify-end gap-2">
                  <span className="text-sm text-divisi-text-primary">
                    {fmtMoney(territory.currentPeriodAmount)}
                  </span>
                  <PercentageBadge value={territory.percentageChange} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function SourcesTab({ 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="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>
  );
}

// ─── Inner Page Component (uses useSearchParams) ─────────────────────────────

function AnalyticsDetailContent() {
  const searchParams = useSearchParams();
  const tabParam = searchParams.get('tab') as TabId | null;
  const initialTab: TabId = tabParam && TABS.some((t) => t.id === tabParam) ? tabParam : 'songs';
  const [activeTab, setActiveTab] = useState<TabId>(initialTab);

  const selectedPeriod = clientPortal.periods[0];

  return (
    <div className="space-y-6">
      {/* Period Selector */}
      <div className="flex items-center gap-2">
        <span className="text-sm text-divisi-text-secondary">Período de regalías:</span>
        <span className="rounded-lg border border-divisi-border bg-divisi-card px-3 py-2 text-sm text-divisi-text-primary">
          {selectedPeriod?.label ?? 'N/A'}
        </span>
      </div>

      {/* Tab Navigation */}
      <div className="border-b border-divisi-border">
        <nav className="flex gap-6 overflow-x-auto" aria-label="Analytics detail tabs">
          {TABS.map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id)}
              className={`whitespace-nowrap pb-3 text-xs font-semibold uppercase tracking-wide transition-colors ${
                activeTab === tab.id
                  ? 'border-b-2 border-divisi-accent text-divisi-accent'
                  : 'text-divisi-text-secondary hover:text-divisi-text-primary'
              }`}
            >
              {tab.label}
            </button>
          ))}
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'songs' && <SongsTab data={clientPortal.songDetails} />}
      {activeTab === 'income' && <IncomeTab data={clientPortal.incomeGroupDetails} />}
      {activeTab === 'territories' && <TerritoriesTab data={clientPortal.territoryDetails} />}
      {activeTab === 'sources' && <SourcesTab data={clientPortal.sourceDetails} />}
    </div>
  );
}

// ─── Page Export ──────────────────────────────────────────────────────────────

export default function AnalyticsDetailPage() {
  return (
    <Suspense fallback={<div className="text-divisi-text-secondary p-4">Cargando...</div>}>
      <AnalyticsDetailContent />
    </Suspense>
  );
}
