import { startTransition, useDeferredValue, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
  ChevronLeft,
  ChevronRight,
  ChevronsUpDown,
  FilterX,
  Loader2,
  PencilLine,
  Plus,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import { TableImagePreview } from '@/components/table-image-preview'
import {
  deleteCategory,
  fetchCategories,
} from '@/lib/api/categories'
import type { AdminCategoryRecord } 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 { CategoriesHeader } from './components/category-header'
import { defaultPerPage } from './helpers'
import type { CategorySort } from './helpers'

export function CategoriesPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [sortBy, setSortBy] = useState<CategorySort>('order-asc')
  const [perPage, setPerPage] = useState(defaultPerPage)
  const [categoryToDelete, setCategoryToDelete] =
    useState<AdminCategoryRecord | null>(null)
  const deferredSearch = useDeferredValue(search)

  const categoriesQuery = useQuery({
    queryKey: ['categories', page, perPage, deferredSearch],
    queryFn: () =>
      fetchCategories({
        page,
        perPage,
        search: deferredSearch || undefined,
      }),
  })

  const hasActiveFilters =
    search.trim().length > 0 ||
    statusFilter !== 'all'

  const visibleCategories = [...(categoriesQuery.data?.items ?? [])]
    .filter((category) => {
      if (statusFilter === 'active') return category.isActive
      if (statusFilter === 'inactive') return !category.isActive
      return true
    })
    .sort((left, right) => {
      switch (sortBy) {
        case 'newest':
          return Number(right.id) - Number(left.id)
        case 'oldest':
          return Number(left.id) - Number(right.id)
        case 'name-asc':
          return left.name.localeCompare(right.name, 'tr')
        case 'name-desc':
          return right.name.localeCompare(left.name, 'tr')
        case 'order-asc':
        default:
          return left.sortOrder - right.sortOrder
      }
    })

  function resetFilters() {
    startTransition(() => {
      setSearch('')
      setStatusFilter('all')
      setSortBy('order-asc')
      setPerPage(defaultPerPage)
      setPage(1)
    })
  }

  const deleteMutation = useMutation({
    mutationFn: async (categoryId: number | string) =>
      deleteCategory(categoryId),
    onSuccess: async () => {
      toast.success('Kategori silindi')
      await queryClient.invalidateQueries({ queryKey: ['categories'] })
      setCategoryToDelete(null)
    },
    onError: handleServerError,
  })

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

  return (
    <>
      <CategoriesHeader />

      <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>Kategori listesi</CardTitle>
                <CardDescription>
                  `/api/admin/categories` kaynağı üzerinden arama ve sayfalama
                  desteklenir.
                </CardDescription>
              </div>
              <div className='flex flex-wrap gap-2'>
                <Button
                  variant='outline'
                  className='rounded-xl'
                  onClick={() => categoriesQuery.refetch()}
                >
                  <RefreshCw
                    className={categoriesQuery.isFetching ? 'animate-spin' : ''}
                  />
                  Yenile
                </Button>
                <Button
                  className='rounded-xl'
                  onClick={() => navigate({ to: '/categories/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='Kategori ara'
                    className='pl-9'
                  />
                </div>
                <Select
                  value={statusFilter}
                  onValueChange={(value) =>
                    startTransition(() => {
                      setStatusFilter(value)
                      setPage(1)
                    })
                  }
                >
                  <SelectTrigger className='w-full'>
                    <SelectValue placeholder='Tüm durumlar' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='all'>Tümü</SelectItem>
                    <SelectItem value='active'>Aktif</SelectItem>
                    <SelectItem value='inactive'>Pasif</SelectItem>
                  </SelectContent>
                </Select>
                <div className='flex items-end justify-end'>
                  <Button
                    variant='outline'
                    className='rounded-xl'
                    onClick={resetFilters}
                    disabled={!hasActiveFilters}
                  >
                    <FilterX />
                    Filtreleri temizle
                  </Button>
                </div>
              </div>

              <div className='mt-3 flex flex-wrap gap-2'>
                {search.trim() ? (
                  <Badge variant='outline' className='rounded-full px-3 py-1'>
                    Arama: {search}
                  </Badge>
                ) : null}
                {statusFilter !== 'all' ? (
                  <Badge variant='outline' className='rounded-full px-3 py-1'>
                    Durum: {statusFilter === 'active' ? 'Aktif' : 'Pasif'}
                  </Badge>
                ) : null}
                {sortBy !== 'order-asc' ? (
                  <Badge variant='outline' className='rounded-full px-3 py-1'>
                    <ChevronsUpDown className='size-3.5' />
                    {sortBy === 'newest'
                      ? 'En yeni önce'
                      : sortBy === 'oldest'
                        ? 'En eski önce'
                        : sortBy === 'name-asc'
                          ? 'Ada göre A-Z'
                          : 'Ada göre Z-A'}
                  </Badge>
                ) : null}
                {perPage !== defaultPerPage ? (
                  <Badge variant='outline' className='rounded-full px-3 py-1'>
                    {perPage} kayıt
                  </Badge>
                ) : null}
              </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>Kategori</TableHead>
                    <TableHead>Durum</TableHead>
                    <TableHead>Sıra</TableHead>
                    <TableHead>SEO</TableHead>
                    <TableHead className='w-[180px] text-right'>
                      İşlemler
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {categoriesQuery.isLoading ? (
                    <TableRow>
                      <TableCell
                        colSpan={6}
                        className='h-28 text-center text-muted-foreground'
                      >
                        <Loader2 className='mx-auto mb-2 size-5 animate-spin' />
                        Kategoriler yükleniyor...
                      </TableCell>
                    </TableRow>
                  ) : visibleCategories.length ? (
                    visibleCategories.map((category) => (
                      <TableRow key={category.id}>
                        <TableCell className='px-4'>
                          <TableImagePreview src={category.image} alt={category.name} />
                        </TableCell>
                        <TableCell className='px-4 py-4'>
                          <div>
                            <p className='font-medium text-foreground'>
                              {category.name}
                            </p>
                            <p className='text-sm text-muted-foreground'>
                              /{category.slug}
                            </p>
                          </div>
                        </TableCell>
                        <TableCell>
                          <Badge
                            className={
                              category.isActive
                                ? 'rounded-full bg-emerald-600 text-white hover:bg-emerald-600'
                                : 'rounded-full bg-slate-500 text-white hover:bg-slate-500'
                            }
                          >
                            {category.isActive ? 'active' : 'inactive'}
                          </Badge>
                        </TableCell>
                        <TableCell className='text-muted-foreground'>
                          {category.sortOrder}
                        </TableCell>
                        <TableCell>
                          <Badge variant='outline' className='rounded-full'>
                            {category.metaTitle && category.metaDescription
                              ? 'Hazır'
                              : 'Eksik'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className='flex justify-end gap-2'>
                            <Button
                              variant='outline'
                              size='sm'
                              className='rounded-xl'
                              onClick={() =>
                                navigate({
                                  to: '/categories/$categoryId',
                                  params: { categoryId: String(category.id) },
                                })
                              }
                            >
                              <PencilLine />
                              Düzenle
                            </Button>
                            <Button
                              variant='destructive'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => setCategoryToDelete(category)}
                            >
                              <Trash2 />
                              Sil
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={6}
                        className='h-28 text-center text-muted-foreground'
                      >
                        Aramaya uygun kategori 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'>
                Görünen {visibleCategories.length} / Toplam{' '}
                {categoriesQuery.data?.meta.total ?? 0} kayıt. Sayfa {page} /{' '}
                {categoriesQuery.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(
                          categoriesQuery.data?.meta.lastPage ?? 1,
                          current + 1
                        )
                      )
                    )
                  }
                  disabled={page === (categoriesQuery.data?.meta.lastPage ?? 1)}
                >
                  <ChevronRight />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </Main>

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