import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { createFaq, fetchFaq, updateFaq } from '@/lib/api/faqs'
import { handleServerError } from '@/lib/handle-server-error'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { FaqsHeader } from './components/faqs-header'
import { FaqForm } from './components/faq-form'
import type { FaqFormValues } from './components/faq-form'

function FaqEditorScreen({ faqId }: { faqId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const faqQuery = useQuery({
    queryKey: ['faq', faqId],
    queryFn: () => fetchFaq(faqId as string),
    enabled: Boolean(faqId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: FaqFormValues) => {
      const payload = {
        question: values.question,
        answer: values.answer,
        category: values.category,
        order_index: values.order,
        is_active: values.isActive,
      }

      if (faqId) {
        return updateFaq(faqId, payload)
      }

      return createFaq(payload)
    },
    onSuccess: async () => {
      toast.success(faqId ? 'SSS güncellendi' : 'SSS oluşturuldu')
      await queryClient.invalidateQueries({ queryKey: ['faqs'] })
      if (faqId) {
        await queryClient.invalidateQueries({ queryKey: ['faq', faqId] })
      }
      navigate({ to: '/faqs' })
    },
    onError: handleServerError,
  })

  const faq = faqQuery.data ?? null

  return (
    <>
      <FaqsHeader />
      <Main className='space-y-6'>
        {faqId && faqQuery.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' />
                SSS bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <FaqForm
            key={faq ? String(faq.id) : 'create-faq'}
            faq={faq}
            isPending={upsertMutation.isPending || faqQuery.isFetching}
            onCancel={() => navigate({ to: '/faqs' })}
            onSubmit={async (values) => {
              await upsertMutation.mutateAsync(values)
            }}
          />
        )}
      </Main>
    </>
  )
}

export function FaqCreatePage() {
  return <FaqEditorScreen />
}

export function FaqEditPage({ faqId }: { faqId: string }) {
  return <FaqEditorScreen faqId={faqId} />
}
