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

type ComplexSettingsPageProps = {
  complexSlug: string;
};

type TabOption = 'details' | 'courts';

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 complexId = complexQuery.data?.id ?? null;

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

  return (
    <div className="mx-auto w-full max-w-6xl px-4 py-4 sm:px-6">
      <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-6 lg:grid-cols-[200px_1fr]">
        <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} />}
        </div>
      </div>
    </div>
  );
}
