import { useState } from 'react'
import { getRouteApi } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { Button } from '@/shared/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/shared/ui/card'
import { CreateBugReportDialog } from './CreateBugReportDialog'
import { CreateRoleRequestDialog } from './CreateRoleRequestDialog'
import { TicketDetailDialog } from './TicketDetailDialog'
import { TicketStatusBadge } from './TicketStatusBadge'
import { listMyTickets } from './api'

const PAGE_SIZE = 20
const routeApi = getRouteApi('/support')

export function SupportTicketList() {
  const { t } = useTranslation()
  const navigate = routeApi.useNavigate()
  const { ticket: selectedTicketId } = routeApi.useSearch()
  const [page, setPage] = useState(1)

  const { data, isLoading, isError, refetch } = useQuery({
    queryKey: ['my-tickets', page],
    queryFn: () => listMyTickets(undefined, undefined, page, PAGE_SIZE),
  })

  return (
    <div className="flex flex-col gap-6">
      <div className="flex flex-wrap gap-2">
        <CreateBugReportDialog />
        <CreateRoleRequestDialog />
      </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('support.empty')}</p>}

      {data && data.items.length > 0 && (
        <div className="flex flex-col gap-3">
          {data.items.map((ticket) => (
            <Card key={ticket.id} className="cursor-pointer" onClick={() => navigate({ search: { ticket: ticket.id } })}>
              <CardHeader className="flex-row items-center justify-between gap-2">
                <CardTitle className="text-base">{t(`support.type.${ticket.type}`)}</CardTitle>
                <TicketStatusBadge status={ticket.status} />
              </CardHeader>
              <CardContent>
                <p className="text-xs text-muted-foreground">
                  {t('support.lastActivity', { date: new Date(ticket.lastActivityAt).toLocaleString() })}
                </p>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {data && data.total > PAGE_SIZE && (
        <div className="flex justify-end gap-2 text-sm">
          <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>
      )}

      {selectedTicketId && (
        <TicketDetailDialog ticketId={selectedTicketId} onOpenChange={(open) => !open && navigate({ search: {} })} />
      )}
    </div>
  )
}
