import { apiClient } from '@/lib/api-client';
import { setCurrentComplexSlug } from '@/lib/current-complex';
import { useQuery } from '@tanstack/react-query';
import { Building2, MapPin, Settings, Users } from 'lucide-react';
import { useEffect, useState } from 'react';
import { ComplexCourtsSection } from './components/complex-courts-section';
import { ComplexDetailsSection } from './components/complex-details-section';
import { ComplexUsersSection } from './components/complex-users-section';

type ComplexSettingsPageProps = {
  complexSlug: string;
};

type TabOption = 'details' | 'courts' | 'users';

export function ComplexSettingsPage({ complexSlug }: ComplexSettingsPageProps) {
  const [activeTab, setActiveTab] = useState<TabOption>('details');

  useEffect(() => {
    setCurrentComplexSlug(complexSlug);
  }, [complexSlug]);

  const complexQuery = useQuery({
    queryKey: ['complex-by-slug', complexSlug],
    queryFn: () => apiClient.complexes.getBySlug(complexSlug),
  });

  const myComplexesQuery = useQuery({
    queryKey: ['my-complexes'],
    queryFn: () => apiClient.complexes.listMine(),
  });

  const complexId = complexQuery.data?.id ?? null;
  const currentMembership = myComplexesQuery.data?.find(
    (complex) => complex.complexSlug === complexSlug
  );
  const canManageUsers = currentMembership?.role === 'ADMIN';

  const tabs = [
    { id: 'details' as const, label: 'Datos del complejo', icon: Building2 },
    { id: 'courts' as const, label: 'Canchas', icon: MapPin },
    { id: 'users' as const, label: 'Usuarios', icon: Users },
  ];

  return (
    <div className="mx-auto w-full max-w-7xl px-4 py-4 sm:px-6 lg:px-8 lg:py-6">
      <section className="overflow-hidden rounded-2xl border border-border/70 bg-card p-6 text-card-foreground shadow-sm sm:p-8">
        <div className="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">
          <div className="space-y-3">
            <div className="inline-flex items-center gap-2 rounded-full border border-border/70 bg-background px-3 py-1 text-xs font-medium text-muted-foreground">
              <span className="size-2 rounded-full bg-primary" />
              Administración del complejo
            </div>
            <h2 className="text-3xl font-semibold tracking-tight">
              <Settings className="mb-1 mr-2 inline size-6" />
              Configuración del complejo
            </h2>
            <p className="max-w-2xl text-sm text-muted-foreground">
              {complexQuery.data?.complexName ??
                'Configurá los datos del complejo, las canchas y los usuarios.'}
            </p>
          </div>


        </div>
      </section>

      <div className="mt-6 grid gap-6 lg:grid-cols-[220px_1fr]">
        <nav className="flex flex-row gap-2 overflow-x-auto rounded-2xl border border-border/70 bg-card p-2 shadow-sm lg:flex-col lg:overflow-visible">
          {tabs.map((tab) => {
            const Icon = tab.icon;
            const isActive = activeTab === tab.id;
            return (
              <button
                key={tab.id}
                type="button"
                onClick={() => setActiveTab(tab.id)}
                className={`inline-flex items-center gap-2 rounded-2xl px-3 py-3 text-sm font-medium transition-all lg:w-full lg:justify-start ${isActive
                    ? 'bg-primary text-primary-foreground shadow-sm'
                    : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                  }`}
              >
                <Icon className="size-4" />
                {tab.label}
              </button>
            );
          })}
        </nav>

        <div className="min-w-0 rounded-2xl border border-border/70 bg-card p-4 shadow-sm sm:p-6">
          {activeTab === 'details' && (
            <ComplexDetailsSection
              complex={complexQuery.data ?? null}
              isLoading={complexQuery.isLoading}
              isError={complexQuery.isError}
            />
          )}

          {activeTab === 'courts' && <ComplexCourtsSection complexId={complexId} />}

          {activeTab === 'users' && (
            <ComplexUsersSection complexId={complexId} canManageUsers={canManageUsers} />
          )}
        </div>
      </div>
    </div>
  );
}
