import { startTransition, useDeferredValue, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
  ChevronLeft,
  ChevronRight,
  Eye,
  Loader2,
  PencilLine,
  Plus,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import { deletePage, fetchPages } from '@/lib/api/pages'
import type { AdminPageRecord } 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 { PagesHeader } from './components/pages-header'
import { PreviewModal } from './components/preview-modal'
import { perPage } from './helpers'

const FRONTEND_URL =
  (import.meta.env.VITE_FRONTEND_URL as string | undefined)?.replace(
    /\/$/,
    ''
  ) || 'http://localhost:3000'

export function PagesListPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const deferredSearch = useDeferredValue(search)
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [pageToDelete, setPageToDelete] = useState<AdminPageRecord | null>(null)
  const [previewUrl, setPreviewUrl] = useState<string | null>(null)
  const [previewTitle, setPreviewTitle] = useState('')

  const pagesQuery = useQuery({
    queryKey: ['pages', page, deferredSearch, statusFilter],
    queryFn: () =>
      fetchPages({
        page,
        perPage,
        search: deferredSearch || undefined,
        is_active:
          statusFilter === 'active'
            ? true
            : statusFilter === 'inactive'
              ? false
              : undefined,
      }),
  })

  const deleteMutation = useMutation({
    mutationFn: async (id: number | string) => deletePage(id),
    onSuccess: async () => {
      toast.success('Sayfa silindi')
      await queryClient.invalidateQueries({ queryKey: ['pages'] })
      setPageToDelete(null)
    },
    onError: handleServerError,
  })

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

  return (
    <>
      <PagesHeader />

      <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>Sayfalar</CardTitle>
                <CardDescription>
                  Statik sayfa ve blok yönetimi.
                </CardDescription>
              </div>
              <div className='flex flex-wrap gap-2'>
                <div className='relative'>
                  <Search className='pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground' />
                  <Input
                    value={search}
                    onChange={(e) => {
                      setSearch(e.target.value)
                      startTransition(() => setPage(1))
                    }}
                    placeholder='Sayfa ara...'
                    className='w-56 rounded-xl pl-9'
                  />
                </div>
                <Select
                  value={statusFilter}
                  onValueChange={(value) => {
                    setStatusFilter(value)
                    startTransition(() => setPage(1))
                  }}
                >
                  <SelectTrigger className='w-32 rounded-xl'>
                    <SelectValue placeholder='Durum' />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value='all'>Tümü</SelectItem>
                    <SelectItem value='active'>Aktif</SelectItem>
                    <SelectItem value='inactive'>Pasif</SelectItem>
                  </SelectContent>
                </Select>
                <Button
                  variant='outline'
                  className='rounded-xl'
                  onClick={() => pagesQuery.refetch()}
                >
                  <RefreshCw
                    className={pagesQuery.isFetching ? 'animate-spin' : ''}
                  />
                  Yenile
                </Button>
                <Button
                  className='rounded-xl'
                  onClick={() => navigate({ to: '/pages/create' })}
                >
                  <Plus />
                  Ekle
                </Button>
              </div>
            </div>
          </CardHeader>
          <CardContent className='space-y-4'>
            <div className='rounded-2xl border border-border/70'>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className='px-4'>Başlık</TableHead>
                    <TableHead>Slug</TableHead>
                    <TableHead>Bloklar</TableHead>
                    <TableHead>Durum</TableHead>
                    <TableHead className='w-45 text-right'>
                      İşlemler
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {pagesQuery.isLoading ? (
                    <TableRow>
                      <TableCell
                        colSpan={5}
                        className='h-28 text-center text-muted-foreground'
                      >
                        <Loader2 className='mx-auto mb-2 size-5 animate-spin' />
                        Yükleniyor...
                      </TableCell>
                    </TableRow>
                  ) : pagesQuery.data?.items.length ? (
                    pagesQuery.data.items.map((item) => (
                      <TableRow key={item.id}>
                        <TableCell className='px-4 py-4 font-medium'>
                          {item.title}
                        </TableCell>
                        <TableCell className='text-sm text-muted-foreground'>
                          /{item.slug}
                        </TableCell>
                        <TableCell>
                          <Badge variant='outline' className='rounded-full'>
                            {item.blocks.length} blok
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <Badge
                            variant={item.isActive ? 'default' : 'secondary'}
                            className='rounded-full'
                          >
                            {item.isActive ? 'Aktif' : 'Pasif'}
                          </Badge>
                        </TableCell>
                        <TableCell>
                          <div className='flex justify-end gap-2'>
                            <Button
                              variant='ghost'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => {
                                setPreviewTitle(item.title)
                                setPreviewUrl(
                                  `${FRONTEND_URL}/kurumsal/${item.slug}`
                                )
                              }}
                            >
                              <Eye />
                            </Button>
                            <Button
                              variant='outline'
                              size='sm'
                              className='rounded-xl'
                              onClick={() =>
                                navigate({
                                  to: '/pages/$pageId',
                                  params: { pageId: String(item.id) },
                                })
                              }
                            >
                              <PencilLine />
                              Düzenle
                            </Button>
                            <Button
                              variant='destructive'
                              size='sm'
                              className='rounded-xl'
                              onClick={() => setPageToDelete(item)}
                            >
                              <Trash2 />
                              Sil
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={5}
                        className='h-28 text-center text-muted-foreground'
                      >
                        Sayfa 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 {pagesQuery.data?.meta.total ?? 0} kayıt. Sayfa {page}{' '}
                / {pagesQuery.data?.meta.lastPage ?? 1}
              </p>
              <div className='flex flex-wrap items-center gap-2'>
                <Button
                  variant='outline'
                  size='sm'
                  onClick={() =>
                    startTransition(() => setPage((c) => Math.max(1, c - 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((c) =>
                        Math.min(pagesQuery.data?.meta.lastPage ?? 1, c + 1)
                      )
                    )
                  }
                  disabled={page === (pagesQuery.data?.meta.lastPage ?? 1)}
                >
                  <ChevronRight />
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </Main>

      <ConfirmDialog
        open={!!pageToDelete}
        onOpenChange={(open) => {
          if (!open) setPageToDelete(null)
        }}
        title='Sayfayı silmek istediğinize emin misiniz?'
        desc={`"${pageToDelete?.title ?? ''}" ve tüm blokları kalıcı olarak silinecek.`}
        confirmText='Evet, sil'
        cancelBtnText='İptal'
        destructive
        isLoading={deleteMutation.isPending}
        handleConfirm={() => {
          if (pageToDelete) {
            deleteMutation.mutate(pageToDelete.id)
          }
        }}
      />

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