import { apiClient } from '@/lib/api-client';
import { useQuery } from '@tanstack/react-query';
import { Link, useLocation } from '@tanstack/react-router';
import {
  Building2,
  CalendarDays,
  ChevronDown,
  ChevronRight,
  Crosshair,
  Globe,
  Users,
} from 'lucide-react';
import { Fragment, useState } from 'react';
import { AdminLayout } from './admin-layout';

function countryFlag(countryCode: string): string {
  if (countryCode === 'LOCAL' || countryCode === 'XX') return '';
  const codePoints = countryCode
    .toUpperCase()
    .split('')
    .map((c) => 0x1f1e6 + c.charCodeAt(0) - 65);
  return String.fromCodePoint(...codePoints);
}

export function AdminPage() {
  const location = useLocation();
  const [expandedCountry, setExpandedCountry] = useState<string | null>(null);

  const complexesQuery = useQuery({
    queryKey: ['admin-complexes'],
    queryFn: () => apiClient.admin.listComplexes(),
  });

  const usersQuery = useQuery({
    queryKey: ['admin-users'],
    queryFn: () => apiClient.admin.listUsers(),
  });

  const geoQuery = useQuery({
    queryKey: ['admin-geo-stats'],
    queryFn: () => apiClient.admin.getGeoStats(),
  });

  const stats = {
    totalComplexes: complexesQuery.data?.length ?? 0,
    totalUsers: usersQuery.data?.length ?? 0,
    totalCourts: complexesQuery.data?.reduce((sum, c) => sum + c.courtCount, 0) ?? 0,
    totalBookings:
      complexesQuery.data?.reduce((sum, c) => sum + Math.round(c.avgBookingsPerDay * 30), 0) ?? 0,
  };

  const cards = [
    {
      label: 'Complejos',
      value: stats.totalComplexes,
      icon: Building2,
      color: 'text-blue-600',
      bg: 'bg-blue-100 dark:bg-blue-900/30',
    },
    {
      label: 'Usuarios',
      value: stats.totalUsers,
      icon: Users,
      color: 'text-emerald-600',
      bg: 'bg-emerald-100 dark:bg-emerald-900/30',
    },
    {
      label: 'Canchas',
      value: stats.totalCourts,
      icon: Crosshair,
      color: 'text-purple-600',
      bg: 'bg-purple-100 dark:bg-purple-900/30',
    },
    {
      label: 'Reservas (30d)',
      value: stats.totalBookings.toLocaleString(),
      icon: CalendarDays,
      color: 'text-amber-600',
      bg: 'bg-amber-100 dark:bg-amber-900/30',
    },
  ];

  return (
    <AdminLayout currentPath={location.pathname}>
      <div className="mb-8">
        <h1 className="text-2xl font-bold tracking-tight">Panel de Administración</h1>
        <p className="mt-1 text-sm text-muted-foreground">
          Gestioná complejos, planes y usuarios de Playzer.
        </p>
      </div>

      <div className="mb-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {cards.map((card) => {
          const Icon = card.icon;

          return (
            <div
              key={card.label}
              className="rounded-2xl border border-border/60 bg-card p-5 shadow-sm"
            >
              <div className="flex items-center gap-3">
                <div className={`rounded-xl p-2.5 ${card.bg}`}>
                  <Icon className={`size-5 ${card.color}`} />
                </div>

                <div>
                  <p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
                    {card.label}
                  </p>
                  <p className="text-2xl font-bold">{card.value}</p>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <div className="mb-6">
        <h2 className="mb-3 text-lg font-semibold">Acceso rápido</h2>

        <div className="grid gap-3 sm:grid-cols-3">
          <Link
            to="/admin/complexes"
            className="rounded-2xl border border-border/60 bg-card p-4 shadow-sm transition-colors hover:bg-accent"
          >
            <Building2 className="mb-2 size-5 text-blue-600" />
            <p className="font-medium">Complejos</p>
            <p className="text-xs text-muted-foreground">
              {stats.totalComplexes} complejos registrados
            </p>
          </Link>

          <Link
            to="/admin/plans"
            className="rounded-2xl border border-border/60 bg-card p-4 shadow-sm transition-colors hover:bg-accent"
          >
            <CalendarDays className="mb-2 size-5 text-emerald-600" />
            <p className="font-medium">Planes</p>
            <p className="text-xs text-muted-foreground">Administrar suscripciones</p>
          </Link>

          <Link
            to="/admin/users"
            className="rounded-2xl border border-border/60 bg-card p-4 shadow-sm transition-colors hover:bg-accent"
          >
            <Users className="mb-2 size-5 text-purple-600" />
            <p className="font-medium">Usuarios</p>
            <p className="text-xs text-muted-foreground">{stats.totalUsers} usuarios registrados</p>
          </Link>
        </div>
      </div>

      <div>
        <h2 className="mb-3 text-lg font-semibold">Usuarios por país / ciudad</h2>

        {geoQuery.isLoading && <p className="text-sm text-muted-foreground">Cargando...</p>}

        {geoQuery.data && geoQuery.data.countries.length === 0 && (
          <div className="rounded-2xl border border-border/60 bg-card p-8 text-center shadow-sm">
            <Globe className="mx-auto mb-2 size-8 text-muted-foreground" />
            <p className="text-sm text-muted-foreground">
              Aún no hay datos de geolocalización. Aparecerán a medida que los usuarios inicien
              sesión.
            </p>
          </div>
        )}

        {geoQuery.data && geoQuery.data.countries.length > 0 && (
          <div className="overflow-hidden rounded-2xl border border-border/60 bg-card shadow-sm">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-border/60">
                  <th className="w-8 px-4 py-3" />
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">País</th>
                  <th className="px-4 py-3 text-right font-medium text-muted-foreground">
                    Usuarios
                  </th>
                </tr>
              </thead>
              <tbody>
                {geoQuery.data.countries.map((country) => {
                  const isExpanded = expandedCountry === country.countryCode;
                  const flag = countryFlag(country.countryCode);

                  return (
                    <Fragment key={country.countryCode}>
                      <tr
                        className={`cursor-pointer border-b border-border/40 transition-colors hover:bg-accent/50 ${isExpanded ? 'bg-accent/30' : ''}`}
                        onClick={() => setExpandedCountry(isExpanded ? null : country.countryCode)}
                        onKeyDown={(e) => {
                          if (e.key === 'Enter' || e.key === ' ') {
                            e.preventDefault();
                            setExpandedCountry(isExpanded ? null : country.countryCode);
                          }
                        }}
                        tabIndex={0}
                        role="button"
                      >
                        <td className="px-4 py-3">
                          {country.cities.length > 1 ||
                          country.cities[0]?.city !== country.country ? (
                            <button type="button" className="text-muted-foreground">
                              {isExpanded ? (
                                <ChevronDown className="size-4" />
                              ) : (
                                <ChevronRight className="size-4" />
                              )}
                            </button>
                          ) : (
                            <span className="inline-block w-4" />
                          )}
                        </td>
                        <td className="px-4 py-3">
                          <span className="mr-2">{flag}</span>
                          {country.country}
                        </td>
                        <td className="px-4 py-3 text-right font-medium">{country.totalUsers}</td>
                      </tr>
                      {isExpanded && (
                        <tr>
                          <td colSpan={3} className="bg-accent/20 p-0">
                            <table className="w-full text-xs">
                              <tbody>
                                {country.cities.map((city) => (
                                  <tr key={city.city} className="border-b border-border/20">
                                    <td className="w-8 px-4 py-2" />
                                    <td className="px-4 py-2 text-muted-foreground">{city.city}</td>
                                    <td className="px-4 py-2 text-right font-medium">
                                      {city.userCount}
                                    </td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          </td>
                        </tr>
                      )}
                    </Fragment>
                  );
                })}
              </tbody>
            </table>

            <div className="border-t border-border/40 px-4 py-2 text-xs text-muted-foreground">
              {geoQuery.data.totalUniqueCountries}{' '}
              {geoQuery.data.totalUniqueCountries === 1 ? 'país' : 'países'} · solo sesiones activas
              con geolocalización resuelta
            </div>
          </div>
        )}
      </div>
    </AdminLayout>
  );
}
