import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import {
  createCategory,
  fetchCategory,
  updateCategory,
} from '@/lib/api/categories'
import { handleServerError } from '@/lib/handle-server-error'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { CategoriesHeader } from './components/category-header'
import { CategoryEditorPage } from './components/category-form'
import type { CategoryFormValues } from './helpers'

function CategoryEditorScreen({ categoryId }: { categoryId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const categoryQuery = useQuery({
    queryKey: ['category', categoryId],
    queryFn: () => fetchCategory(categoryId as string),
    enabled: Boolean(categoryId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: CategoryFormValues) => {
      const payload = {
        name: values.name,
        slug: values.slug,
        description: values.description || undefined,
        image: values.image || undefined,
        is_active: values.isActive,
        meta_title: values.metaTitle || undefined,
        meta_description: values.metaDescription || undefined,
      }

      if (categoryId) {
        return updateCategory(categoryId, payload)
      }

      return createCategory(payload)
    },
    onSuccess: async () => {
      toast.success(categoryId ? 'Kategori güncellendi' : 'Kategori oluşturuldu')
      await queryClient.invalidateQueries({ queryKey: ['categories'] })
      if (categoryId) {
        await queryClient.invalidateQueries({
          queryKey: ['category', categoryId],
        })
      }
      navigate({ to: '/categories' })
    },
    onError: handleServerError,
  })

  const category = categoryQuery.data ?? null

  return (
    <>
      <CategoriesHeader />
      <Main className='space-y-6'>
        {categoryId && categoryQuery.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' />
                Kategori bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <CategoryEditorPage
            key={category ? String(category.id) : 'create-category'}
            category={category}
            isPending={upsertMutation.isPending || categoryQuery.isFetching}
            onCancel={() => navigate({ to: '/categories' })}
            onSubmit={async (values) => {
              await upsertMutation.mutateAsync(values)
            }}
          />
        )}
      </Main>
    </>
  )
}

export function CategoryCreatePage() {
  return <CategoryEditorScreen />
}

export function CategoryEditPage({ categoryId }: { categoryId: string }) {
  return <CategoryEditorScreen categoryId={categoryId} />
}
