'use client';

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

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 { PortalIncomeGroupDetail } from '@/lib/mock-data/types';
import PieChartWidget from '@/components/charts/PieChartWidget';

// ─── 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 IncomeDetailView({ 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="space-y-6">
      <h1 className="text-xl font-bold text-divisi-text-primary">Grupos de Ingresos Más Altos</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">
            <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>
    </div>
  );
}

export default function IncomeGroupsPage() {
  return <IncomeDetailView data={clientPortal.incomeGroupDetails} />;
}
