import { startTransition, useDeferredValue, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
  ChevronLeft,
  ChevronRight,
  FilterX,
  Loader2,
  PencilLine,
  Plus,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { useNavigate } from '@tanstack/react-router'
import { toast } from 'sonner'
import { TableImagePreview } from '@/components/table-image-preview'
import { fetchCategoryOptions } from '@/lib/api/categories'
import { deleteCourse, fetchCourses } from '@/lib/api/courses'
import type { AdminCourseRecord } from '@/lib/api/types'
import { handleServerError } from '@/lib/handle-server-error'
import { getPageNumbers } from '@/lib/utils'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { Main } from '@/components/layout/main'
import { PreviewModal } from '@/features/pages/components/preview-modal'
import { CoursesHeader } from './components/courses-header'
import { perPage } from './helpers'

export function CoursesPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [categoryFilter, setCategoryFilter] = useState('all')
  const [courseToDelete, setCourseToDelete] =
    useState<AdminCourseRecord | null>(null)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)
  const [previewTitle, setPreviewTitle] = useState('')
  const deferredSearch = useDeferredValue(search)

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

  const coursesQuery = useQuery({
    queryKey: ['courses', page, deferredSearch, categoryFilter],
    queryFn: () =>
      fetchCourses({
        page,
        perPage,
        search: deferredSearch || undefined,
        category: categoryFilter === 'all' ? undefined : categoryFilter,
      }),
  })

  const deleteMutation = useMutation({
    mutationFn: async (courseId: number | string) => deleteCourse(courseId),
    onSuccess: async () => {
      toast.success('Eğitim silindi')
      await queryClient.invalidateQueries({ queryKey: ['courses'] })
      setCourseToDelete(null)
    },
    onError: handleServerError,
  })

  const pageNumbers = getPageNumbers(
    page,
    coursesQuery.data?.meta.lastPage ?? 1
  )

  return (
    <>
      <CoursesHeader />
      <Main className='space-y-6'>
        <Card>
          <CardHeader className='gap-4'>
            <div className='flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between'>
              <div>
                <CardTitle>Eğitim listesi</CardTitle>
                <CardDescription>
                  `/api/admin/courses` kaynağı kategori ve arama filtreleriyle
                  kullanılır.
                </CardDescription>
              </div>
              <div className='flex flex-wrap gap-2'>
                <Button
                  variant='outline'
                  className='rounded-xl'
                  onClick={() => coursesQuery.refetch()}
                >
                  <RefreshCw
                    className={coursesQuery.isFetching ? 'animate-spin' : ''}
                  />
                  Yenile
                </Button>
                <Button
                  className='rounded-xl'
                  onClick={() => navigate({ to: '/courses/create' })}
                >
                  <Plus />
                  Ekle
                </Button>
              </div>
            </div>

            <div className='rounded-2xl border border-dashed border-border/70 bg-muted/20 p-4'>
              <div className='grid gap-3 md:grid-cols-[1fr_220px_auto]'>
                <div className='relative min-w-[260px]'>
                  <Search className='pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground' />
                  <Input
                    value={search}
                    onChange={(event) => {
                      const nextValue = event.target.value

                      startTransition(() => {
                        setSearch(nextValue)
                        setPage(1)
                      })
                    }}
                    placeholder='Başlık veya slug ile ara'
                    className='pl-9'
                  />
                </div>
                <Select
                  value={categoryFilter}
                  onValueChange={(value) =>
                    startTransition(() => {
                      setCategoryFilter(value)
                      setPage(1)
                    })
                  }
                >
                  <SelectTrigger className='w-full'>
                    <SelectValue placeholder='Tüm kategoriler' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='all'>Tüm kategoriler</SelectItem>
                    {(categoriesQuery.data ?? []).map((category) => (
                      <SelectItem key={category.id} value={category.slug}>
                        {category.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <div className='flex items-end justify-end'>
                  <Button
                    variant='outline'
                    className='rounded-xl'
                    onClick={() => {
                      setSearch('')
                      setCategoryFilter('all')
                      setPage(1)
                    }}
                    disabled={!search && categoryFilter === 'all'}
                  >
                    <FilterX />
                    Temizle
                  </Button>
                </div>
              </div>
            </div>
          </CardHeader>
          <CardContent className='space-y-4'>
            <div className='rounded-2xl border border-border/70'>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className='w-16 px-4'>Görsel</TableHead>
                    <TableHead>Eğitim</TableHead>
                    <TableHead>Kategori</TableHead>
                    <TableHead>Süre / Lokasyon</TableHead>
                    <TableHead>Fiyat / Rating</TableHead>
                    <TableHead className='w-[180px] text-right'>
                      İşlemler
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {coursesQuery.isLoading ? (
                    <TableRow>
                      <TableCell
                        colSpan={6}
                        className='h-28 text-center text-muted-foreground'
                      >
                        <Loader2 className='mx-auto mb-2 size-5 animate-spin' />
                        Eğitimler yükleniyor...
                      </TableCell>
                    </TableRow>
                  ) : coursesQuery.data?.items.length ? (
                    coursesQuery.data.items.map((course) => (
                      <TableRow key={course.id}>
                        <TableCell className='px-4'>
                          <TableImagePreview src={course.image} alt={course.title} />
                        </TableCell>
                        <TableCell className='px-4 py-4'>
                          <div>
                            <p className='font-medium text-foreground'>
                              {course.title}
                            </p>
                            <p className='text-sm text-muted-foreground'>
                              /{course.slug}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge variant='outline' className='rounded-full'>
                            {course.categoryName}
                          </Badge>
                        </TableCell>
                        <TableCell className='text-sm text-muted-foreground'>
                          <div>{course.duration}</div>
                          <div>{course.location || '-'}</div>
                        </TableCell>
                        <TableCell className='text-sm text-muted-foreground'>
                          <div>{course.price || '-'}</div>
                          <div>{course.rating.toFixed(1)} / 5.0</div>
                        </TableCell>
                        <TableCell>
                          <div className='flex justify-end gap-2'>
                            {/* TODO: Preview — backend hazır olunca aktif edilecek */}
                            {/* <Button
                              variant='ghost'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => {
                                setPreviewTitle(course.title)
                                setPreviewUrl(
                                  `${FRONTEND_URL}/egitimler/${course.categorySlug}/${course.slug}`
                                )
                              }}
                            >
                              <Eye />
                            </Button> */}
                            <Button
                              variant='outline'
                              size='sm'
                              className='rounded-xl'
                              onClick={() =>
                                navigate({
                                  to: '/courses/$courseId',
                                  params: { courseId: String(course.id) },
                                })
                              }
                            >
                              <PencilLine />
                              Düzenle
                            </Button>
                            <Button
                              variant='destructive'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => setCourseToDelete(course)}
                            >
                              <Trash2 />
                              Sil
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={6}
                        className='h-28 text-center text-muted-foreground'
                      >
                        Filtreye uygun eğitim bulunamadı.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>

            <div className='flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between'>
              <p className='text-sm text-muted-foreground'>
                Toplam {coursesQuery.data?.meta.total ?? 0} kayıt. Sayfa{' '}
                {page} / {coursesQuery.data?.meta.lastPage ?? 1}
              </p>
              <div className='flex flex-wrap items-center gap-2'>
                <Button
                  variant='outline'
                  size='sm'
                  onClick={() =>
                    startTransition(() =>
                      setPage((current) => Math.max(1, current - 1))
                    )
                  }
                  disabled={page === 1}
                >
                  <ChevronLeft />
                </Button>
                {pageNumbers.map((item, index) =>
                  item === '...' ? (
                    <span
                      key={`${item}-${index}`}
                      className='px-2 text-sm text-muted-foreground'
                    >
                      ...
                    </span>
                  ) : (
                    <Button
                      key={item}
                      size='sm'
                      variant={item === page ? 'default' : 'outline'}
                      onClick={() =>
                        startTransition(() => setPage(Number(item)))
                      }
                    >
                      {item}
                    </Button>
                  )
                )}
                <Button
                  variant='outline'
                  size='sm'
                  onClick={() =>
                    startTransition(() =>
                      setPage((current) =>
                        Math.min(
                          coursesQuery.data?.meta.lastPage ?? 1,
                          current + 1
                        )
                      )
                    )
                  }
                  disabled={page === (coursesQuery.data?.meta.lastPage ?? 1)}
                >
                  <ChevronRight />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </Main>

      <ConfirmDialog
        open={!!courseToDelete}
        onOpenChange={(open) => {
          if (!open) setCourseToDelete(null)
        }}
        title='Eğitimi silmek istediğinize emin misiniz?'
        desc={`${courseToDelete?.title ?? 'Bu eğitim'} kalıcı olarak silinecek. Bu işlem geri alınamaz.`}
        confirmText='Evet, sil'
        cancelBtnText='İptal'
        destructive
        isLoading={deleteMutation.isPending}
        handleConfirm={() => {
          if (courseToDelete) {
            deleteMutation.mutate(courseToDelete.id)
          }
        }}
      />

      {previewUrl && (
        <PreviewModal
          url={previewUrl}
          title={previewTitle}
          onClose={() => setPreviewUrl(null)}
        />
      )}
    </>
  )
}
