import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import {
  createHeroSlide,
  fetchHeroSlide,
  updateHeroSlide,
} from '@/lib/api/hero-slides'
import { handleServerError } from '@/lib/handle-server-error'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { HeroSlidesHeader } from './components/hero-slides-header'
import { HeroSlideForm } from './components/hero-slide-form'
import type { HeroSlideFormValues } from './components/hero-slide-form'

function HeroSlideEditorScreen({ slideId }: { slideId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const slideQuery = useQuery({
    queryKey: ['hero-slide', slideId],
    queryFn: () => fetchHeroSlide(slideId as string),
    enabled: Boolean(slideId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: HeroSlideFormValues) => {
      const payload = {
        title: values.title,
        subtitle: values.subtitle || null,
        label: values.label || null,
        description: values.description || null,
        button_text: values.buttonText || null,
        button_url: values.buttonUrl || null,
        media_type: values.mediaType,
        image: values.image || null,
        mobile_image: values.mobileImage || null,
        video_url: values.videoUrl || null,
        mobile_video_url: values.mobileVideoUrl || null,
        order_index: values.orderIndex,
        is_active: values.isActive,
      }

      if (slideId) {
        return updateHeroSlide(slideId, payload)
      }
      return createHeroSlide(payload)
    },
    onSuccess: async () => {
      toast.success(slideId ? 'Slayt güncellendi' : 'Slayt oluşturuldu')
      await queryClient.invalidateQueries({ queryKey: ['hero-slides'] })
      if (slideId) {
        await queryClient.invalidateQueries({
          queryKey: ['hero-slide', slideId],
        })
      }
      navigate({ to: '/hero-slides' })
    },
    onError: handleServerError,
  })

  const slide = slideQuery.data ?? null

  return (
    <>
      <HeroSlidesHeader />
      <Main className='space-y-6'>
        {slideId && slideQuery.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' />
                Slayt bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <HeroSlideForm
            key={slide ? String(slide.id) : 'create-slide'}
            slide={slide}
            isPending={upsertMutation.isPending || slideQuery.isFetching}
            onCancel={() => navigate({ to: '/hero-slides' })}
            onSubmit={async (values) => {
              await upsertMutation.mutateAsync(values)
            }}
          />
        )}
      </Main>
    </>
  )
}

export function HeroSlideCreatePage() {
  return <HeroSlideEditorScreen />
}

export function HeroSlideEditPage({ slideId }: { slideId: string }) {
  return <HeroSlideEditorScreen slideId={slideId} />
}
