import { apiClient } from '@/lib/api-client';
import { setCurrentComplexSlug } from '@/lib/current-complex';
import { type Court, type CreateCourtInput } from '@repo/api-contract';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { CourtFormSection } from './components/court-form-section';
import { CourtListSection } from './components/court-list-section';

type ComplexCourtsPageProps = {
  complexSlug: string;
};

export function ComplexCourtsPage({ complexSlug }: ComplexCourtsPageProps) {
  const [editingCourt, setEditingCourt] = useState<Court | null>(null);
  const [initialDraft, setInitialDraft] = useState<CreateCourtInput | null>(null);

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

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

  const complexId = complexQuery.data?.id ?? null;

  const courtsQuery = useQuery({
    queryKey: ['courts', complexId],
    enabled: Boolean(complexId),
    queryFn: () => apiClient.courts.listByComplex(complexId as string),
  });

  return (
    <main className="mx-auto w-full max-w-6xl space-y-6 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">
          {complexQuery.data?.complexName ?? 'Configurar canchas'}
        </h2>
        <p className="mt-2 text-sm text-muted-foreground">
          Alta y edición de canchas del complejo.
        </p>
      </section>

      <CourtFormSection
        complexId={complexId}
        editingCourt={editingCourt}
        initialDraft={initialDraft}
        onCancelEdit={() => {
          setEditingCourt(null);
        }}
      />

      <CourtListSection
        courts={courtsQuery.data ?? []}
        isLoading={courtsQuery.isLoading}
        isError={courtsQuery.isError}
        onDuplicateCourt={(court) => {
          setEditingCourt(null);
          setInitialDraft({
            name: `${court.name} - Copy`,
            sportId: court.sportId,
            slotDurationMinutes: court.slotDurationMinutes,
            basePrice: court.basePrice,
            availability: court.availability.map((slot) => ({
              dayOfWeek: slot.dayOfWeek,
              startTime: slot.startTime,
              endTime: slot.endTime,
            })),
          });
          window.scrollTo({ top: 0, behavior: 'smooth' });
        }}
        onEditCourt={(court) => {
          setInitialDraft(null);
          setEditingCourt(court);
          window.scrollTo({ top: 0, behavior: 'smooth' });
        }}
      />
    </main>
  );
}
