import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { toast } from '@/shared/ui/toast-store'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/shared/ui/dialog'
import { Button } from '@/shared/ui/button'
import { Input } from '@/shared/ui/input'
import { Label } from '@/shared/ui/label'
import { Badge } from '@/shared/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { listRoles } from '@/features/admin/roles/api'
import type { UserSummaryDto } from '@/shared/api/types'
import {
  blockUser,
  changeUserRole,
  forceRevokeConfig,
  getUserConfigs,
  resetUserPassword,
  unblockUser,
} from './api'

export function UserManageDialog({ user, open, onOpenChange }: { user: UserSummaryDto; open: boolean; onOpenChange: (open: boolean) => void }) {
  const { t } = useTranslation()
  const queryClient = useQueryClient()
  const [newPassword, setNewPassword] = useState('')

  const rolesQuery = useQuery({ queryKey: ['admin-roles'], queryFn: listRoles, enabled: open })
  const configsQuery = useQuery({ queryKey: ['admin-user-configs', user.id], queryFn: () => getUserConfigs(user.id), enabled: open })

  const invalidateUsers = () => queryClient.invalidateQueries({ queryKey: ['admin-users'] })

  const blockMutation = useMutation({
    mutationFn: () => (user.isBlocked ? unblockUser(user.id) : blockUser(user.id)),
    onSuccess: async () => {
      toast.success(user.isBlocked ? t('admin.users.unblocked') : t('admin.users.blocked'))
      await invalidateUsers()
    },
    onError: () => toast.error(t('auth.genericError')),
  })

  const roleMutation = useMutation({
    mutationFn: (roleId: string) => changeUserRole(user.id, roleId),
    onSuccess: async () => {
      toast.success(t('admin.users.roleChanged'))
      await invalidateUsers()
    },
    onError: () => toast.error(t('auth.genericError')),
  })

  const resetPasswordMutation = useMutation({
    mutationFn: () => resetUserPassword(user.id, newPassword),
    onSuccess: () => {
      toast.success(t('admin.users.passwordReset'))
      setNewPassword('')
    },
    onError: () => toast.error(t('auth.genericError')),
  })

  const revokeMutation = useMutation({
    mutationFn: (configId: string) => forceRevokeConfig(configId),
    onSuccess: async () => {
      toast.success(t('configs.revoked'))
      await queryClient.invalidateQueries({ queryKey: ['admin-user-configs', user.id] })
    },
    onError: () => toast.error(t('auth.genericError')),
  })

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-lg">
        <DialogHeader>
          <DialogTitle>{user.userName}</DialogTitle>
        </DialogHeader>

        <div className="flex flex-col gap-6">
          <div className="flex items-center gap-2">
            <Badge variant={user.isBlocked ? 'destructive' : user.isActivated ? 'success' : 'warning'}>
              {user.isBlocked ? t('admin.users.status.blocked') : user.isActivated ? t('admin.users.status.active') : t('admin.users.status.pending')}
            </Badge>
            <Button
              size="sm"
              variant="outline"
              disabled={blockMutation.isPending}
              onClick={() => {
                if (!user.isBlocked && !confirm(t('admin.users.confirmBlock'))) return
                blockMutation.mutate()
              }}
            >
              {user.isBlocked ? t('admin.users.unblock') : t('admin.users.block')}
            </Button>
          </div>

          <div className="flex flex-col gap-1.5">
            <Label>{t('admin.users.role')}</Label>
            <Select defaultValue="" onValueChange={(roleId) => roleMutation.mutate(roleId)}>
              <SelectTrigger>
                <SelectValue placeholder={user.role} />
              </SelectTrigger>
              <SelectContent>
                {rolesQuery.data?.map((role) => (
                  <SelectItem key={role.id} value={role.id}>
                    {role.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div className="flex flex-col gap-1.5">
            <Label htmlFor="newPassword">{t('admin.users.resetPassword')}</Label>
            <div className="flex gap-2">
              <Input
                id="newPassword"
                type="password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder={t('auth.passwordHint')}
              />
              <Button
                variant="outline"
                disabled={newPassword.length < 8 || resetPasswordMutation.isPending}
                onClick={() => resetPasswordMutation.mutate()}
              >
                {t('admin.users.reset')}
              </Button>
            </div>
          </div>

          <div className="flex flex-col gap-2">
            <Label>{t('admin.users.configs')}</Label>
            {configsQuery.data?.length === 0 && <p className="text-sm text-muted-foreground">{t('configs.empty')}</p>}
            {configsQuery.data?.map((config) => (
              <div key={config.id} className="flex items-center justify-between rounded-md border border-border px-3 py-2 text-sm">
                <span>
                  {config.label ?? config.location} · {config.protocol} · {t(`configs.status.${config.status}`)}
                </span>
                <Button
                  size="sm"
                  variant="ghost"
                  disabled={config.status === 'Revoked' || revokeMutation.isPending}
                  onClick={() => {
                    if (confirm(t('configs.confirmRevoke'))) revokeMutation.mutate(config.id)
                  }}
                >
                  {t('configs.revoke')}
                </Button>
              </div>
            ))}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}
