import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Users, Plus, Edit, UserX, UserCheck, Key, Shield } from 'lucide-react'
import { useForm } from 'react-hook-form'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Label } from '@/components/ui/Label'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/Dialog'
import { usersApi } from '@/api/users.api'
import { getErrorMessage } from '@/api/client'
import { formatDate, ROLE_LABELS } from '@/lib/utils'
import { cn } from '@/lib/utils'
import type { UserCreateRequest, UserResponse, UserRole } from '@/types/api.types'

const ROLE_COLORS: Record<UserRole, string> = {
  super_admin: 'bg-purple-100 text-purple-800',
  admin: 'bg-blue-100 text-blue-800',
  supervisor: 'bg-cyan-100 text-cyan-800',
  operator: 'bg-green-100 text-green-800',
  readonly: 'bg-gray-100 text-gray-800',
}

export function UsersPage() {
  const queryClient = useQueryClient()
  const [showCreateDialog, setShowCreateDialog] = useState(false)
  const [editingUser, setEditingUser] = useState<UserResponse | null>(null)
  const [resetPasswordUser, setResetPasswordUser] = useState<UserResponse | null>(null)

  const { data: usersData, isLoading } = useQuery({
    queryKey: ['users'],
    queryFn: () => usersApi.list(1, 100),
  })

  const toggleActiveMutation = useMutation({
    mutationFn: ({ id, active }: { id: string; active: boolean }) =>
      usersApi.update(id, { is_active: active }),
    onSuccess: (_, vars) => {
      queryClient.invalidateQueries({ queryKey: ['users'] })
      toast.success(vars.active ? 'Utente riattivato' : 'Utente disabilitato')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const users = usersData?.items || []

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b bg-background px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Users className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">Utenti</h1>
          <span className="text-sm text-muted-foreground">
            ({users.filter((u) => u.is_active).length} attivi su {users.length})
          </span>
        </div>
        <Button onClick={() => setShowCreateDialog(true)}>
          <Plus className="h-4 w-4 mr-2" />
          Nuovo utente
        </Button>
      </div>

      {/* Tabella */}
      <div className="flex-1 overflow-auto p-6">
        {isLoading ? (
          <div className="flex justify-center py-12">
            <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent" />
          </div>
        ) : (
          <div className="rounded-lg border overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="bg-muted/50 border-b">
                  <th className="text-left px-4 py-3 font-medium text-muted-foreground">Utente</th>
                  <th className="text-left px-4 py-3 font-medium text-muted-foreground">Ruolo</th>
                  <th className="text-left px-4 py-3 font-medium text-muted-foreground">2FA</th>
                  <th className="text-left px-4 py-3 font-medium text-muted-foreground">Ultimo accesso</th>
                  <th className="text-left px-4 py-3 font-medium text-muted-foreground">Stato</th>
                  <th className="text-right px-4 py-3 font-medium text-muted-foreground">Azioni</th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {users.map((user) => (
                  <tr
                    key={user.id}
                    className={cn('hover:bg-muted/30 transition-colors', !user.is_active && 'opacity-60')}
                  >
                    <td className="px-4 py-3">
                      <div>
                        <p className="font-medium">{user.full_name}</p>
                        <p className="text-muted-foreground text-xs">{user.email}</p>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={cn(
                          'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                          ROLE_COLORS[user.role],
                        )}
                      >
                        {ROLE_LABELS[user.role] || user.role}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      {user.totp_enabled ? (
                        <span className="text-green-600 text-xs font-medium flex items-center gap-1">
                          <Shield className="h-3 w-3" /> Attivo
                        </span>
                      ) : (
                        <span className="text-muted-foreground text-xs">—</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-xs text-muted-foreground">
                      {formatDate(user.last_login_at) || '—'}
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className={cn(
                          'inline-flex rounded-full px-2 py-0.5 text-xs font-medium',
                          user.is_active
                            ? 'bg-green-100 text-green-800'
                            : 'bg-gray-100 text-gray-600',
                        )}
                      >
                        {user.is_active ? 'Attivo' : 'Disabilitato'}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-end gap-1">
                        {/* Modifica */}
                        <Button
                          variant="ghost"
                          size="icon"
                          title="Modifica"
                          onClick={() => setEditingUser(user)}
                          className="h-8 w-8"
                        >
                          <Edit className="h-4 w-4" />
                        </Button>

                        {/* Reset password */}
                        <Button
                          variant="ghost"
                          size="icon"
                          title="Reset password"
                          onClick={() => setResetPasswordUser(user)}
                          className="h-8 w-8"
                        >
                          <Key className="h-4 w-4" />
                        </Button>

                        {/* Attiva/disabilita */}
                        <Button
                          variant="ghost"
                          size="icon"
                          title={user.is_active ? 'Disabilita' : 'Riattiva'}
                          onClick={() =>
                            toggleActiveMutation.mutate({ id: user.id, active: !user.is_active })
                          }
                          className="h-8 w-8"
                        >
                          {user.is_active ? (
                            <UserX className="h-4 w-4 text-red-500" />
                          ) : (
                            <UserCheck className="h-4 w-4 text-green-500" />
                          )}
                        </Button>
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Dialog crea/modifica utente */}
      {(showCreateDialog || editingUser) && (
        <UserFormDialog
          open
          onClose={() => {
            setShowCreateDialog(false)
            setEditingUser(null)
          }}
          editingUser={editingUser}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['users'] })
            setShowCreateDialog(false)
            setEditingUser(null)
          }}
        />
      )}

      {/* Dialog reset password */}
      {resetPasswordUser && (
        <ResetPasswordDialog
          user={resetPasswordUser}
          onClose={() => setResetPasswordUser(null)}
        />
      )}
    </div>
  )
}

// ─── Dialog crea/modifica utente ─────────────────────────────────────────────

interface UserFormDialogProps {
  open: boolean
  onClose: () => void
  editingUser: UserResponse | null
  onSaved: () => void
}

function UserFormDialog({ open, onClose, editingUser, onSaved }: UserFormDialogProps) {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<UserCreateRequest>({
    defaultValues: editingUser
      ? { full_name: editingUser.full_name, role: editingUser.role, email: editingUser.email }
      : { role: 'operator' },
  })

  const createMutation = useMutation({
    mutationFn: usersApi.create,
    onSuccess: () => {
      toast.success('Utente creato')
      onSaved()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<UserCreateRequest> }) =>
      usersApi.update(id, data),
    onSuccess: () => {
      toast.success('Utente aggiornato')
      onSaved()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const onSubmit = (data: UserCreateRequest) => {
    if (editingUser) {
      updateMutation.mutate({ id: editingUser.id, data: { full_name: data.full_name, role: data.role } })
    } else {
      createMutation.mutate(data)
    }
  }

  return (
    <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{editingUser ? 'Modifica utente' : 'Nuovo utente'}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 mt-4">
          <div className="space-y-2">
            <Label>Nome completo *</Label>
            <Input {...register('full_name', { required: 'Obbligatorio' })} />
            {errors.full_name && <p className="text-xs text-destructive">{errors.full_name.message}</p>}
          </div>

          {!editingUser && (
            <>
              <div className="space-y-2">
                <Label>Email *</Label>
                <Input type="email" {...register('email', { required: 'Obbligatoria' })} />
              </div>
              <div className="space-y-2">
                <Label>Password *</Label>
                <Input
                  type="password"
                  placeholder="Min. 8 caratteri, 1 maiuscola, 1 numero"
                  {...register('password', { required: 'Obbligatoria', minLength: 8 })}
                />
              </div>
            </>
          )}

          <div className="space-y-2">
            <Label>Ruolo *</Label>
            <select
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              {...register('role', { required: true })}
            >
              {Object.entries(ROLE_LABELS)
                .filter(([role]) => role !== 'super_admin')
                .map(([role, label]) => (
                  <option key={role} value={role}>{label}</option>
                ))}
            </select>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>Annulla</Button>
            <Button type="submit" isLoading={createMutation.isPending || updateMutation.isPending}>
              {editingUser ? 'Salva' : 'Crea utente'}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}

// ─── Dialog reset password ────────────────────────────────────────────────────

function ResetPasswordDialog({ user, onClose }: { user: UserResponse; onClose: () => void }) {
  const { register, handleSubmit } = useForm<{ new_password: string; confirm: string }>()

  const mutation = useMutation({
    mutationFn: (pwd: string) => usersApi.resetPassword(user.id, pwd),
    onSuccess: () => {
      toast.success('Password aggiornata')
      onClose()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const onSubmit = (data: { new_password: string }) => {
    mutation.mutate(data.new_password)
  }

  return (
    <Dialog open onOpenChange={(o) => !o && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Reset password – {user.full_name}</DialogTitle>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 mt-4">
          <div className="space-y-2">
            <Label>Nuova password</Label>
            <Input
              type="password"
              placeholder="Min. 8 caratteri, 1 maiuscola, 1 numero"
              {...register('new_password', { required: true, minLength: 8 })}
            />
          </div>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>Annulla</Button>
            <Button type="submit" isLoading={mutation.isPending}>Aggiorna password</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  )
}
