import { startTransition, useDeferredValue, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import {
  ChevronLeft,
  ChevronRight,
  FilterX,
  Loader2,
  PencilLine,
  Plus,
  RefreshCw,
  Search,
  Trash2,
} from 'lucide-react'
import { toast } from 'sonner'
import { deleteFaq, fetchFaqs } from '@/lib/api/faqs'
import type { AdminFaqRecord } 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 { FaqsHeader } from './components/faqs-header'

const perPage = 20

const categoryLabels: Record<string, string> = {
  egitimler: 'Eğitimler',
  kayit: 'Kayıt',
  iletisim: 'İletişim',
}

export function FaqsPage() {
  const navigate = useNavigate()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [categoryFilter, setCategoryFilter] = useState('all')
  const [statusFilter, setStatusFilter] = useState<'all' | 'active' | 'inactive'>('all')
  const [searchText, setSearchText] = useState('')
  const deferredSearch = useDeferredValue(searchText)
  const [faqToDelete, setFaqToDelete] = useState<AdminFaqRecord | null>(null)

  const faqsQuery = useQuery({
    queryKey: ['faqs', page, categoryFilter, statusFilter, deferredSearch],
    queryFn: () =>
      fetchFaqs({
        page,
        perPage,
        category: categoryFilter === 'all' ? undefined : categoryFilter,
        search: deferredSearch || undefined,
        is_active: statusFilter === 'all' ? undefined : statusFilter === 'active',
      }),
  })

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

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

  return (
    <>
      <FaqsHeader />

      <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>Sık Sorulan Sorular</CardTitle>
                  <CardDescription>
                    Kategorilere göre SSS yönetimi.
                  </CardDescription>
                </div>
                <div className='flex flex-wrap gap-2'>
                  <Button
                    variant='outline'
                    className='rounded-xl'
                    onClick={() => faqsQuery.refetch()}
                  >
                    <RefreshCw
                      className={faqsQuery.isFetching ? 'animate-spin' : ''}
                    />
                    Yenile
                  </Button>
                  <Button
                    className='rounded-xl'
                    onClick={() => navigate({ to: '/faqs/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_180px_180px_auto]'>
                  <div className='relative'>
                    <Search className='absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground' />
                    <Input
                      placeholder='Soru veya cevap ara...'
                      value={searchText}
                      onChange={(e) => {
                        setSearchText(e.target.value)
                        setPage(1)
                      }}
                      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>
                      {Object.entries(categoryLabels).map(([value, label]) => (
                        <SelectItem key={value} value={value}>
                          {label}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <Select
                    value={statusFilter}
                    onValueChange={(value: 'all' | 'active' | 'inactive') =>
                      startTransition(() => {
                        setStatusFilter(value)
                        setPage(1)
                      })
                    }
                  >
                    <SelectTrigger className='w-full'>
                      <SelectValue placeholder='Tümü' />
                    </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={() => {
                        setCategoryFilter('all')
                        setStatusFilter('all')
                        setSearchText('')
                        setPage(1)
                      }}
                      disabled={categoryFilter === 'all' && statusFilter === 'all' && searchText === ''}
                    >
                      <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='px-4'>Soru</TableHead>
                      <TableHead>Kategori</TableHead>
                      <TableHead>Sıra</TableHead>
                      <TableHead>Durum</TableHead>
                      <TableHead className='w-[180px] text-right'>
                        İşlemler
                      </TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {faqsQuery.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>
                    ) : faqsQuery.data?.items.length ? (
                      faqsQuery.data.items.map((item) => (
                        <TableRow key={item.id}>
                          <TableCell className='px-4 py-4 font-medium'>
                            {item.question}
                          </TableCell>
                          <TableCell>
                            <Badge variant='outline' className='rounded-full'>
                              {categoryLabels[item.category] ?? item.category}
                            </Badge>
                          </TableCell>
                          <TableCell>{item.orderIndex}</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='outline'
                                size='sm'
                                className='rounded-xl'
                                onClick={() => navigate({ to: '/faqs/$faqId', params: { faqId: String(item.id) } })}
                              >
                                <PencilLine />
                                Düzenle
                              </Button>
                              <Button
                                variant='destructive'
                                size='sm'
                                className='rounded-xl'
                                onClick={() => setFaqToDelete(item)}
                              >
                                <Trash2 />
                                Sil
                              </Button>
                            </div>
                          </TableCell>
                        </TableRow>
                      ))
                    ) : (
                      <TableRow>
                        <TableCell
                          colSpan={5}
                          className='h-28 text-center text-muted-foreground'
                        >
                          SSS 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 {faqsQuery.data?.meta.total ?? 0} kayıt. Sayfa {page} /{' '}
                  {faqsQuery.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(faqsQuery.data?.meta.lastPage ?? 1, c + 1)
                        )
                      )
                    }
                    disabled={page === (faqsQuery.data?.meta.lastPage ?? 1)}
                  >
                    <ChevronRight />
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
      </Main>

      <ConfirmDialog
        open={!!faqToDelete}
        onOpenChange={(open) => {
          if (!open) setFaqToDelete(null)
        }}
        title='SSS silmek istediğinize emin misiniz?'
        desc={`"${faqToDelete?.question ?? ''}" kalıcı olarak silinecek.`}
        confirmText='Evet, sil'
        cancelBtnText='İptal'
        destructive
        isLoading={deleteMutation.isPending}
        handleConfirm={() => {
          if (faqToDelete) {
            deleteMutation.mutate(faqToDelete.id)
          }
        }}
      />
    </>
  )
}
