import { Separator } from '@/components/ui/separator';
import { apiClient } from '@/lib/api-client';
import { type Court, type CreateCourtInput } from '@repo/api-contract';
import { useQuery } from '@tanstack/react-query';
import { MapPin } from 'lucide-react';
import { useState } from 'react';
import { CourtFormSection } from './court-form-section';
import { CourtListSection } from './court-list-section';

type ComplexCourtsSectionProps = {
  complexId: string | null;
};

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

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

  return (
    <section className="mt-6 rounded-xl border bg-card p-3 sm:p-5">
      <div className="flex items-center gap-2">
        <MapPin className="size-5 text-muted-foreground" />
        <h3 className="text-lg font-medium">Canchas</h3>
      </div>
      <Separator className="my-4" />
      <p className="mb-4 text-sm text-muted-foreground">Alta y edición de canchas del complejo.</p>

      <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' });
        }}
      />
    </section>
  );
}
