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-6xl py-4">
      <section className="rounded-xl border bg-card p-4 text-card-foreground shadow-sm sm:p-5">
        <h2 className="text-2xl font-semibold">
          <Settings className="mb-1 mr-2 inline size-6" />
          Configuración del complejo
        </h2>
        <p className="mt-2 text-sm text-muted-foreground">
          {complexQuery.data?.complexName ?? 'Configura los datos de tu complejo'}
        </p>
      </section>

      <div className="mt-6 grid gap-5 lg:grid-cols-[200px_1fr] lg:gap-6">
        <nav className="flex flex-row gap-1 overflow-x-auto 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-lg px-3 py-2 text-sm font-medium transition-colors lg:w-full lg:justify-start ${
                  isActive
                    ? 'bg-muted text-foreground'
                    : 'text-muted-foreground hover:bg-muted hover:text-foreground'
                }`}
              >
                <Icon className="size-4" />
                {tab.label}
              </button>
            );
          })}
        </nav>

        <div className="min-w-0">
          {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>
  );
}
