import { useState } from 'react'
import { createFileRoute } from '@tanstack/react-router'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/shared/ui/toast-store'
import { Button } from '@/shared/ui/button'
import { listAdminNews, deletePost } from '@/features/admin/news/api'
import { NewsFormDialog } from '@/features/admin/news/NewsFormDialog'
import type { NewsPostDto } from '@/shared/api/types'

export const Route = createFileRoute('/admin/news')({ component: AdminNewsPage })

const PAGE_SIZE = 20

function AdminNewsPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [page, setPage] = useState(1)
  const [editing, setEditing] = useState<NewsPostDto | null>(null)

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['admin-news', page],
    queryFn: () => listAdminNews(page, PAGE_SIZE),
  })

  const deleteMutation = useMutation({
    mutationFn: deletePost,
    onSuccess: async () => {
      toast.success(t('admin.news.deleted'))
      await queryClient.invalidateQueries({ queryKey: ['admin-news'] })
    },
    onError: () => toast.error(t('auth.genericError')),
  })

  return (
    <div className="flex flex-col gap-4">
      <div className="flex justify-end">
        <NewsFormDialog />
      </div>

      {isLoading && <p className="text-sm text-muted-foreground">…</p>}

      {isError && (
        <div className="flex items-center gap-2">
          <p className="text-sm text-muted-foreground">{t('auth.genericError')}</p>
          <Button variant="outline" size="sm" onClick={() => void refetch()}>
            {t('activation.retry')}
          </Button>
        </div>
      )}

      {data?.items.length === 0 && <p className="text-sm text-muted-foreground">{t('admin.news.empty')}</p>}

      {data && data.items.length > 0 && (
        <>
          <div className="flex flex-col gap-2">
            {data.items.map((post) => (
              <div key={post.id} className="flex items-center justify-between rounded-md border border-border px-3 py-2 text-sm">
                <div className="flex flex-col">
                  <span>{post.title}</span>
                  <span className="text-xs text-muted-foreground">{new Date(post.createdAt).toLocaleString()}</span>
                </div>
                <div className="flex gap-2">
                  <Button size="sm" variant="outline" onClick={() => setEditing(post)}>
                    {t('admin.roles.edit')}
                  </Button>
                  <Button
                    size="sm"
                    variant="ghost"
                    disabled={deleteMutation.isPending}
                    onClick={() => {
                      if (confirm(t('admin.news.confirmDelete'))) deleteMutation.mutate(post.id)
                    }}
                  >
                    {t('admin.roles.delete')}
                  </Button>
                </div>
              </div>
            ))}
          </div>

          <div className="flex items-center justify-between text-sm">
            <span className="text-muted-foreground">{t('admin.users.total', { count: data.total })}</span>
            <div className="flex gap-2">
              <Button variant="outline" size="sm" disabled={page <= 1} onClick={() => setPage((p) => p - 1)}>
                {t('admin.prev')}
              </Button>
              <Button variant="outline" size="sm" disabled={page * PAGE_SIZE >= data.total} onClick={() => setPage((p) => p + 1)}>
                {t('admin.next')}
              </Button>
            </div>
          </div>
        </>
      )}

      {editing && <NewsFormDialog post={editing} open={!!editing} onOpenChange={(open) => !open && setEditing(null)} />}
    </div>
  )
}
