'use client';

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

import { useMemo } from 'react';
import { clientPortal } from '@/lib/mock-data';
import { useCompactCurrencyFormatter } from '@/lib/hooks/useCurrencyFormatter';
import { chartColorArray } from '@/lib/constants/theme';
import type { PortalTerritoryDetail } from '@/lib/mock-data/types';
import BarChartWidget from '@/components/charts/BarChartWidget';

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

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 TerritoriesDetailView({ 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="space-y-6">
      <h1 className="flex items-center gap-2 text-xl font-bold text-divisi-text-primary">
        <svg className="h-5 w-5 text-divisi-accent flex-shrink-0" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10" />
          <line x1="2" y1="12" x2="22" y2="12" />
          <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
        </svg>
        Territorios Principales
      </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">
            <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>
    </div>
  );
}

export default function TerritoriesPage() {
  return <TerritoriesDetailView data={clientPortal.territoryDetails} />;
}
