import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { apiClient } from '@/lib/api-client';
import { useQuery } from '@tanstack/react-query';
import { useLocation } from '@tanstack/react-router';
import { Building2, ChevronDown, ChevronUp, MapPin, RefreshCw } from 'lucide-react';
import { useState } from 'react';
import { AdminLayout } from './admin-layout';

function PaymentBadge({ status }: { status: string }) {
  if (status === 'active') {
    return (
      <Badge
        variant="outline"
        className="border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-700 dark:bg-emerald-950 dark:text-emerald-400"
      >
        Activo
      </Badge>
    );
  }

  if (status === 'no_plan') {
    return (
      <Badge variant="outline" className="border-muted-foreground/30 text-muted-foreground">
        Sin plan
      </Badge>
    );
  }

  return (
    <Badge
      variant="outline"
      className="border-red-300 bg-red-50 text-red-700 dark:border-red-700 dark:bg-red-950 dark:text-red-400"
    >
      Expirado
    </Badge>
  );
}

export function ComplexesPage() {
  const location = useLocation();
  const [expandedId, setExpandedId] = useState<string | null>(null);

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

  return (
    <AdminLayout currentPath={location.pathname}>
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Complejos</h1>
          <p className="mt-1 text-sm text-muted-foreground">
            {data?.length ?? 0} complejos registrados en Playzer.
          </p>
        </div>

        <Button variant="outline" size="icon" className="rounded-xl" onClick={() => refetch()}>
          <RefreshCw className="size-4" />
        </Button>
      </div>

      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <p className="text-sm text-muted-foreground">Cargando complejos...</p>
        </div>
      ) : data?.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-20">
          <Building2 className="mb-3 size-10 text-muted-foreground/50" />
          <p className="text-sm text-muted-foreground">No hay complejos registrados.</p>
        </div>
      ) : (
        <div className="space-y-3">
          {data?.map((complex) => {
            const isExpanded = expandedId === complex.id;

            return (
              <div
                key={complex.id}
                className="rounded-2xl border border-border/60 bg-card shadow-sm"
              >
                <button
                  type="button"
                  onClick={() => setExpandedId(isExpanded ? null : complex.id)}
                  className="flex w-full items-center gap-4 px-5 py-4 text-left transition-colors hover:bg-accent/50"
                >
                  <div className="flex min-w-0 flex-1 items-center gap-3">
                    <div className="rounded-xl bg-emerald-100 p-2.5 dark:bg-emerald-900/30">
                      <Building2 className="size-5 text-emerald-600" />
                    </div>

                    <div className="min-w-0">
                      <p className="truncate font-medium">{complex.complexName}</p>
                      <div className="flex items-center gap-2 text-xs text-muted-foreground">
                        <span>{complex.complexSlug}</span>
                        {complex.city && (
                          <>
                            <span>·</span>
                            <MapPin className="size-3" />
                            <span>{complex.city}</span>
                          </>
                        )}
                      </div>
                    </div>
                  </div>

                  <PaymentBadge status={complex.paymentStatus} />

                  <div className="hidden items-center gap-4 text-xs text-muted-foreground sm:flex">
                    <span className="text-center">
                      <span className="block text-sm font-semibold text-foreground">
                        {complex.courtCount}
                      </span>
                      Canchas
                    </span>
                    <span className="text-center">
                      <span className="block text-sm font-semibold text-foreground">
                        {complex.userCount}
                      </span>
                      Usuarios
                    </span>
                    <span className="text-center">
                      <span className="block text-sm font-semibold text-foreground">
                        {complex.avgBookingsPerDay.toFixed(1)}
                      </span>
                      Res/día
                    </span>
                  </div>

                  {isExpanded ? (
                    <ChevronUp className="size-4 shrink-0 text-muted-foreground" />
                  ) : (
                    <ChevronDown className="size-4 shrink-0 text-muted-foreground" />
                  )}
                </button>

                {isExpanded && (
                  <div className="border-t border-border/40 px-5 py-4">
                    <div className="grid grid-cols-2 gap-4 text-sm sm:grid-cols-4">
                      <div>
                        <p className="text-xs text-muted-foreground">Plan</p>
                        <p className="font-medium">{complex.planName ?? 'Sin plan'}</p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">Canchas</p>
                        <p className="font-medium">{complex.courtCount}</p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">Usuarios</p>
                        <p className="font-medium">{complex.userCount}</p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">Prom. reservas/día</p>
                        <p className="font-medium">{complex.avgBookingsPerDay.toFixed(1)}</p>
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </AdminLayout>
  );
}
