import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import { useNavigate } from '@tanstack/react-router'
import { toast } from 'sonner'
import { fetchCategoryOptions } from '@/lib/api/categories'
import {
  createCourse,
  fetchCourse,
  updateCourse,
} from '@/lib/api/courses'
import { handleServerError } from '@/lib/handle-server-error'
import { Card, CardContent } from '@/components/ui/card'
import { Main } from '@/components/layout/main'
import { PreviewModal } from '@/features/pages/components/preview-modal'
import { CoursesHeader } from './components/courses-header'
import { CourseForm } from './components/course-form'
import type { CourseFormValues } from './helpers'

function CourseEditorScreen({ courseId }: { courseId?: string }) {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)

  const categoriesQuery = useQuery({
    queryKey: ['categories', 'options'],
    queryFn: fetchCategoryOptions,
  })

  const courseQuery = useQuery({
    queryKey: ['course', courseId],
    queryFn: () => fetchCourse(courseId as string),
    enabled: Boolean(courseId),
  })

  const upsertMutation = useMutation({
    mutationFn: async (values: CourseFormValues) => {
      const payload = {
        category_id: values.categoryId,
        slug: values.slug,
        title: values.title,
        sub: values.sub || null,
        desc: values.description,
        long_desc: values.longDescription || null,
        duration: values.duration,
        badge: values.badge || null,
        image: values.image || null,
        price: values.price || null,
        includes: values.includes,
        requirements: values.requirements,
        meta_title: values.metaTitle || null,
        meta_description: values.metaDescription || null,
        scope: values.scope,
        standard: values.standard || null,
        location: 'Kadıköy / Tuzla',
      }

      if (courseId) {
        return updateCourse(courseId, payload)
      }

      return createCourse(payload)
    },
    onSuccess: async () => {
      toast.success(courseId ? 'Eğitim güncellendi' : 'Eğitim oluşturuldu')
      await queryClient.invalidateQueries({ queryKey: ['courses'] })
      if (courseId) {
        await queryClient.invalidateQueries({ queryKey: ['course', courseId] })
      }
      navigate({ to: '/courses' })
    },
    onError: handleServerError,
  })

  const course = courseQuery.data ?? null

  return (
    <>
      <CoursesHeader />
      <Main className='space-y-6'>
        {courseId && courseQuery.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' />
                Eğitim bilgileri yükleniyor...
              </div>
            </CardContent>
          </Card>
        ) : (
          <>
            <CourseForm
              key={course ? String(course.id) : 'create-course'}
              course={course}
              categories={categoriesQuery.data ?? []}
              isPending={upsertMutation.isPending || courseQuery.isFetching}
              onCancel={() => navigate({ to: '/courses' })}
              onSubmit={async (values) => {
                await upsertMutation.mutateAsync(values)
              }}
            />

            {/* TODO: Eğitim blokları ve önizleme — backend hazır olunca aktif edilecek */}
            {/* {course && (
              <>
                <div className='flex items-center justify-between rounded-2xl border border-border/70 bg-card px-4 py-3 shadow-sm'>
                  <div>
                    <p className='text-sm font-medium'>Eğitim Önizleme</p>
                    <p className='text-xs text-muted-foreground'>
                      Eğitimin frontend'deki görünümünü kontrol edin
                    </p>
                  </div>
                  <div className='flex gap-2'>
                    <Button
                      type='button'
                      variant='outline'
                      className='gap-2 rounded-xl'
                      onClick={() =>
                        setPreviewUrl(
                          `${FRONTEND_URL}/egitimler/${course.categorySlug}/${course.slug}`
                        )
                      }
                    >
                      <Eye className='size-4' />
                      Önizle
                    </Button>
                    <Button
                      type='button'
                      variant='ghost'
                      size='icon'
                      className='rounded-xl'
                      onClick={() =>
                        window.open(
                          `${FRONTEND_URL}/egitimler/${course.categorySlug}/${course.slug}`,
                          '_blank'
                        )
                      }
                    >
                      <ExternalLink className='size-4' />
                    </Button>
                  </div>
                </div>

                <BlockManager api={courseBlockApi(course.id)} />
              </>
            )} */}
          </>
        )}
      </Main>

      {previewUrl && (
        <PreviewModal
          url={previewUrl}
          title={course?.title ?? 'Eğitim'}
          onClose={() => setPreviewUrl(null)}
        />
      )}
    </>
  )
}

export function CourseCreatePage() {
  return <CourseEditorScreen />
}

export function CourseEditPage({ courseId }: { courseId: string }) {
  return <CourseEditorScreen courseId={courseId} />
}
