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 { Badge } from '@/shared/ui/badge'
import { listRoles, deleteRole } from '@/features/admin/roles/api'
import { RoleFormDialog } from '@/features/admin/roles/RoleFormDialog'
import { getPricingSettings } from '@/features/admin/pricing/api'
import type { RoleDto } from '@/shared/api/types'

export const Route = createFileRoute('/admin/roles')({ component: AdminRolesPage })

function AdminRolesPage() {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [editing, setEditing] = useState<RoleDto | null>(null)

  const { data, isLoading, isError, refetch } = useQuery({ queryKey: ['admin-roles'], queryFn: listRoles })
  const { data: pricing } = useQuery({ queryKey: ['admin-pricing'], queryFn: getPricingSettings })

  // Ставки — цена за конфиг В МЕСЯЦ при данном тарифе; итог за период = ставка × месяцев × квота.
  const totalPrice = (monthlyRate: number | null | undefined, maxConfigs: number, months: number) =>
    monthlyRate == null || maxConfigs < 0 ? t('admin.roles.noPrice') : `${monthlyRate * months * maxConfigs} ₽`

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

  return (
    <div className="flex flex-col gap-4">
      <div className="flex justify-end">
        <RoleFormDialog />
      </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 && (
        <div className="overflow-x-auto">
        <table className="w-full text-left text-sm">
          <thead>
            <tr className="border-b border-border text-muted-foreground">
              <th className="py-2 font-medium">{t('admin.roles.name')}</th>
              <th className="py-2 font-medium">{t('admin.roles.maxConfigs')}</th>
              <th className="py-2 font-medium">{t('admin.roles.maxIpLimit')}</th>
              <th className="py-2 font-medium">{t('admin.roles.totalPerQuarter')}</th>
              <th className="py-2 font-medium">{t('admin.roles.totalHalfYear')}</th>
              <th className="py-2 font-medium">{t('admin.roles.totalPerYear')}</th>
              <th className="py-2" />
              <th className="py-2" />
            </tr>
          </thead>
          <tbody>
            {data.map((role) => (
              <tr key={role.id} className="border-b border-border">
                <td className="py-2">
                  {role.name} {role.isSystem && <Badge variant="outline">{t('admin.roles.system')}</Badge>}
                </td>
                <td className="py-2">{role.maxConfigs < 0 ? t('unlimited') : role.maxConfigs}</td>
                <td className="py-2">{role.maxIpLimit < 0 ? t('unlimited') : role.maxIpLimit}</td>
                <td className="py-2">{totalPrice(pricing?.pricePerConfigPerQuarter, role.maxConfigs, 3)}</td>
                <td className="py-2">{totalPrice(pricing?.pricePerConfigPerQuarter, role.maxConfigs, 6)}</td>
                <td className="py-2">{totalPrice(pricing?.pricePerConfigPerYear, role.maxConfigs, 12)}</td>
                <td className="py-2 text-right">
                  <Button size="sm" variant="outline" onClick={() => setEditing(role)}>
                    {t('admin.roles.edit')}
                  </Button>
                </td>
                <td className="py-2 text-right">
                  {!role.isSystem && (
                    <Button
                      size="sm"
                      variant="ghost"
                      disabled={deleteMutation.isPending}
                      onClick={() => {
                        if (confirm(t('admin.roles.confirmDelete'))) deleteMutation.mutate(role.id)
                      }}
                    >
                      {t('admin.roles.delete')}
                    </Button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        </div>
      )}

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