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 { listAdminPlans, deletePlan } from '@/features/admin/plans/api'
import { PlanFormDialog } from '@/features/admin/plans/PlanFormDialog'
import { getPricingSettings } from '@/features/admin/pricing/api'
import { applyDiscount, resolveDiscountPercent } from '@/shared/lib/pricing'
import type { AdminPlanDto } from '@/shared/api/types'

export const Route = createFileRoute('/admin/plans')({ component: AdminPlansPage })

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

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

  const priceCell = (monthlyRate: number | null | undefined, configCount: number, months: number) => {
    if (monthlyRate == null) return <span>{t('admin.plans.noPrice')}</span>

    const original = monthlyRate * months * configCount
    const percent = resolveDiscountPercent(pricing?.discountTiers ?? [], configCount)
    if (percent <= 0) return <span>{original} ₽</span>

    const discounted = applyDiscount(original, percent)
    return (
      <span className="flex flex-col">
        <span className="text-xs text-muted-foreground line-through">{original} ₽</span>
        <span className="flex items-center gap-1">
          {discounted} ₽
          <Badge variant="success">-{percent}%</Badge>
        </span>
      </span>
    )
  }

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

  return (
    <div className="flex flex-col gap-4">
      <p className="text-xs text-muted-foreground">{t('admin.plans.pageHint')}</p>
      <div className="flex justify-end">
        <PlanFormDialog />
      </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?.length === 0 && <p className="text-sm text-muted-foreground">{t('admin.plans.empty')}</p>}

      {data && data.length > 0 && (
        <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.plans.name')}</th>
                <th className="py-2 font-medium">{t('admin.plans.configCount')}</th>
                <th className="py-2 font-medium">{t('admin.plans.totalPerQuarter')}</th>
                <th className="py-2 font-medium">{t('admin.plans.totalHalfYear')}</th>
                <th className="py-2 font-medium">{t('admin.plans.totalPerYear')}</th>
                <th className="py-2" />
                <th className="py-2" />
              </tr>
            </thead>
            <tbody>
              {data.map((plan) => (
                <tr key={plan.id} className="border-b border-border">
                  <td className="py-2">
                    {plan.name} {!plan.isEnabled && <Badge variant="outline">{t('admin.plans.disabled')}</Badge>}
                  </td>
                  <td className="py-2">{plan.configCount}</td>
                  <td className="py-2">{priceCell(pricing?.pricePerConfigPerQuarter, plan.configCount, 3)}</td>
                  <td className="py-2">{priceCell(pricing?.pricePerConfigPerHalfYear, plan.configCount, 6)}</td>
                  <td className="py-2">{priceCell(pricing?.pricePerConfigPerYear, plan.configCount, 12)}</td>
                  <td className="py-2 text-right">
                    <Button size="sm" variant="outline" onClick={() => setEditing(plan)}>
                      {t('admin.plans.edit')}
                    </Button>
                  </td>
                  <td className="py-2 text-right">
                    <Button
                      size="sm"
                      variant="ghost"
                      disabled={deleteMutation.isPending}
                      onClick={() => {
                        if (confirm(t('admin.plans.confirmDelete'))) deleteMutation.mutate(plan.id)
                      }}
                    >
                      {t('admin.plans.delete')}
                    </Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

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