import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { fetchCourseOptions } from '@/lib/api/courses'
import {
  createSchedule,
  fetchSchedule,
  updateSchedule,
} from '@/lib/api/schedules'
import { handleServerError } from '@/lib/handle-server-error'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { SchedulesHeader } from './components/schedules-header'
import { ScheduleForm } from './components/schedule-form'
import type { ScheduleFormValues } from './components/schedule-form'

function ScheduleEditorScreen({ scheduleId }: { scheduleId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const coursesQuery = useQuery({
    queryKey: ['courses', 'options'],
    queryFn: fetchCourseOptions,
  })

  const scheduleQuery = useQuery({
    queryKey: ['schedule', scheduleId],
    queryFn: () => fetchSchedule(scheduleId as string),
    enabled: Boolean(scheduleId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: ScheduleFormValues) => {
      const payload = {
        course_id: values.courseId,
        start_date: values.startDate,
        end_date: values.endDate || null,
        location: values.location,
        instructor: values.instructor || null,
        quota: values.quota,
        enrolled_count: values.enrolledCount,
        price_override: values.priceOverride ? Number(values.priceOverride) : null,
        status: values.status,
        notes: values.notes || null,
      }

      if (scheduleId) {
        return updateSchedule(scheduleId, payload)
      }

      return createSchedule(payload)
    },
    onSuccess: async () => {
      toast.success(scheduleId ? 'Takvim kaydı güncellendi' : 'Takvim kaydı oluşturuldu')
      await queryClient.invalidateQueries({ queryKey: ['schedules'] })
      if (scheduleId) {
        await queryClient.invalidateQueries({ queryKey: ['schedule', scheduleId] })
      }
      navigate({ to: '/schedules' })
    },
    onError: handleServerError,
  })

  const schedule = scheduleQuery.data ?? null

  return (
    <>
      <SchedulesHeader />
      <Main className='space-y-6'>
        {scheduleId && scheduleQuery.isLoading ? (
          <Card className='border-border/70 shadow-sm'>
            <CardContent className='flex min-h-64 items-center justify-center text-muted-foreground'>
              <div className='text-center'>
                <Loader2 className='mx-auto mb-3 size-6 animate-spin' />
                Takvim bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <ScheduleForm
            key={schedule ? String(schedule.id) : 'create-schedule'}
            schedule={schedule}
            courses={coursesQuery.data ?? []}
            isPending={upsertMutation.isPending || scheduleQuery.isFetching}
            onCancel={() => navigate({ to: '/schedules' })}
            onSubmit={async (values) => {
              await upsertMutation.mutateAsync(values)
            }}
          />
        )}
      </Main>
    </>
  )
}

export function ScheduleCreatePage() {
  return <ScheduleEditorScreen />
}

export function ScheduleEditPage({ scheduleId }: { scheduleId: string }) {
  return <ScheduleEditorScreen scheduleId={scheduleId} />
}
