import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import {
  createAnnouncement,
  fetchAnnouncement,
  updateAnnouncement,
} from '@/lib/api/announcements'
import { handleServerError } from '@/lib/handle-server-error'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { AnnouncementsHeader } from './components/announcements-header'
import {
  AnnouncementForm,
  type AnnouncementFormValues,
} from './components/announcement-form'

function AnnouncementEditorScreen({ announcementId }: { announcementId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const announcementQuery = useQuery({
    queryKey: ['announcement', announcementId],
    queryFn: () => fetchAnnouncement(announcementId as string),
    enabled: Boolean(announcementId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: AnnouncementFormValues) => {
      const payload = {
        title: values.title,
        slug: values.slug || undefined,
        category: values.category,
        excerpt: values.excerpt,
        content: values.content,
        image: values.image || null,
        is_featured: values.isFeatured,
        meta_title: values.metaTitle || null,
        meta_description: values.metaDescription || null,
        published_at: values.publishedAt || null,
      }

      if (announcementId) {
        return updateAnnouncement(announcementId, payload)
      }

      return createAnnouncement(payload)
    },
    onSuccess: async () => {
      toast.success(announcementId ? 'Duyuru güncellendi' : 'Duyuru oluşturuldu')
      await queryClient.invalidateQueries({ queryKey: ['announcements'] })
      if (announcementId) {
        await queryClient.invalidateQueries({ queryKey: ['announcement', announcementId] })
      }
      navigate({ to: '/announcements' })
    },
    onError: handleServerError,
  })

  const announcement = announcementQuery.data ?? null

  return (
    <>
      <AnnouncementsHeader />
      <Main className='space-y-6'>
        {announcementId && announcementQuery.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' />
                Duyuru bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <AnnouncementForm
            key={announcement ? String(announcement.id) : 'create-announcement'}
            announcement={announcement}
            isPending={upsertMutation.isPending}
            onCancel={() => navigate({ to: '/announcements' })}
            onSubmit={async (values) => {
              await upsertMutation.mutateAsync(values)
            }}
          />
        )}
      </Main>
    </>
  )
}

export function AnnouncementCreatePage() {
  return <AnnouncementEditorScreen />
}

export function AnnouncementEditPage({ announcementId }: { announcementId: string }) {
  return <AnnouncementEditorScreen announcementId={announcementId} />
}
