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 { listAdminApps, deleteApp } from '@/features/admin/apps/api'
import { AppFormDialog } from '@/features/admin/apps/AppFormDialog'
import type { AdminAppDto, OsPlatform } from '@/shared/api/types'

export const Route = createFileRoute('/admin/apps')({ component: AdminAppsPage })

const OS_ORDER: OsPlatform[] = ['IOS', 'Android', 'Windows', 'MacOS', 'Linux']

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

  const { data, isLoading, isError, refetch } = useQuery({ queryKey: ['admin-apps'], queryFn: listAdminApps })

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

  return (
    <div className="flex flex-col gap-4">
      <div className="flex justify-end">
        <AppFormDialog />
      </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.apps.empty')}</p>}

      {data && (
        <div className="flex flex-col gap-6">
          {OS_ORDER.filter((os) => data.some((a) => a.operatingSystem === os)).map((os) => (
            <div key={os} className="flex flex-col gap-2">
              <h3 className="text-sm font-semibold text-muted-foreground">{t(`instructions.os.${os}`)}</h3>
              {data
                .filter((a) => a.operatingSystem === os)
                .map((app) => (
                  <div key={app.id} className="flex items-center justify-between rounded-md border border-border px-3 py-2 text-sm">
                    <div className="flex items-center gap-2">
                      <span>{app.name}</span>
                      {!app.isEnabled && <Badge variant="outline">{t('admin.apps.disabled')}</Badge>}
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" onClick={() => setEditing(app)}>
                        {t('admin.roles.edit')}
                      </Button>
                      <Button
                        size="sm"
                        variant="ghost"
                        disabled={deleteMutation.isPending}
                        onClick={() => {
                          if (confirm(t('admin.apps.confirmDelete'))) deleteMutation.mutate(app.id)
                        }}
                      >
                        {t('admin.roles.delete')}
                      </Button>
                    </div>
                  </div>
                ))}
            </div>
          ))}
        </div>
      )}

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