import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Shield, Plus, Trash2, MailCheck, User } from 'lucide-react'
import toast from 'react-hot-toast'
import { Button } from '@/components/ui/Button'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/Dialog'
import { Label } from '@/components/ui/Label'
import { permissionsApi } from '@/api/permissions.api'
import { mailboxesApi } from '@/api/mailboxes.api'
import { usersApi } from '@/api/users.api'
import { getErrorMessage } from '@/api/client'
import { cn, ROLE_LABELS } from '@/lib/utils'
import type { MailboxUserPermissionResponse } from '@/types/api.types'

export function PermissionsPage() {
  const queryClient = useQueryClient()
  const [selectedMailboxId, setSelectedMailboxId] = useState<string>('')
  const [showGrantDialog, setShowGrantDialog] = useState(false)

  const { data: mailboxesData } = useQuery({
    queryKey: ['mailboxes'],
    queryFn: () => mailboxesApi.list(1, 200),
  })

  const { data: mailboxUsers = [], isLoading: loadingUsers } = useQuery({
    queryKey: ['mailbox-permissions', selectedMailboxId],
    queryFn: () => permissionsApi.listMailboxUsers(selectedMailboxId),
    enabled: !!selectedMailboxId,
  })

  const revokeMutation = useMutation({
    mutationFn: ({ userId }: { userId: string }) =>
      permissionsApi.revoke(selectedMailboxId, userId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['mailbox-permissions', selectedMailboxId] })
      toast.success('Permesso revocato')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const mailboxes = mailboxesData?.items || []
  const selectedMailbox = mailboxes.find((m) => m.id === selectedMailboxId)

  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">
          <Shield className="h-5 w-5 text-primary" />
          <h1 className="text-xl font-semibold">Permessi Caselle</h1>
        </div>
        {selectedMailboxId && (
          <Button onClick={() => setShowGrantDialog(true)}>
            <Plus className="h-4 w-4 mr-2" />
            Assegna permesso
          </Button>
        )}
      </div>

      <div className="flex flex-1 overflow-hidden">
        {/* Pannello sinistra: lista caselle */}
        <div className="w-64 border-r flex flex-col">
          <div className="p-3 border-b">
            <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
              Caselle PEC
            </p>
          </div>
          <div className="flex-1 overflow-y-auto py-2">
            {mailboxes.map((mb) => (
              <button
                key={mb.id}
                onClick={() => setSelectedMailboxId(mb.id)}
                className={cn(
                  'w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-muted/50 transition-colors',
                  selectedMailboxId === mb.id && 'bg-primary/10 text-primary font-medium',
                )}
              >
                <MailCheck className="h-4 w-4 flex-shrink-0" />
                <div className="min-w-0">
                  <p className="text-sm truncate">
                    {mb.display_name || mb.email_address}
                  </p>
                  <p className="text-xs text-muted-foreground truncate">{mb.email_address}</p>
                </div>
              </button>
            ))}
          </div>
        </div>

        {/* Pannello destra: utenti con accesso */}
        <div className="flex-1 overflow-y-auto p-6">
          {!selectedMailboxId ? (
            <div className="flex flex-col items-center justify-center h-64 text-center">
              <Shield className="h-12 w-12 text-muted-foreground/30 mb-3" />
              <p className="text-muted-foreground">Seleziona una casella per gestire i permessi</p>
            </div>
          ) : loadingUsers ? (
            <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="space-y-4">
              <div className="flex items-center justify-between">
                <h2 className="font-semibold">
                  Accesso a: {selectedMailbox?.display_name || selectedMailbox?.email_address}
                </h2>
                <p className="text-sm text-muted-foreground">
                  {mailboxUsers.length} utenti con accesso
                </p>
              </div>

              {mailboxUsers.length === 0 ? (
                <div className="rounded-lg border border-dashed p-8 text-center">
                  <User className="h-10 w-10 text-muted-foreground/30 mx-auto mb-3" />
                  <p className="text-muted-foreground text-sm">
                    Nessun utente con accesso esplicito.
                    Gli admin del tenant hanno accesso automatico.
                  </p>
                  <Button
                    variant="outline"
                    size="sm"
                    className="mt-3"
                    onClick={() => setShowGrantDialog(true)}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    Assegna permesso
                  </Button>
                </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-center px-4 py-3 font-medium text-muted-foreground">Lettura</th>
                        <th className="text-center px-4 py-3 font-medium text-muted-foreground">Invio</th>
                        <th className="text-center px-4 py-3 font-medium text-muted-foreground">Gestione</th>
                        <th className="text-right px-4 py-3 font-medium text-muted-foreground">Azioni</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {mailboxUsers.map((perm) => (
                        <PermissionRow
                          key={perm.user_id}
                          perm={perm}
                          mailboxId={selectedMailboxId}
                          onRevoke={() =>
                            revokeMutation.mutate({ userId: perm.user_id })
                          }
                          onUpdate={() =>
                            queryClient.invalidateQueries({
                              queryKey: ['mailbox-permissions', selectedMailboxId],
                            })
                          }
                        />
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Dialog assegna permesso */}
      {showGrantDialog && selectedMailboxId && (
        <GrantPermissionDialog
          mailboxId={selectedMailboxId}
          onClose={() => setShowGrantDialog(false)}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['mailbox-permissions', selectedMailboxId] })
            setShowGrantDialog(false)
          }}
        />
      )}
    </div>
  )
}

// ─── Riga permesso ────────────────────────────────────────────────────────────

interface PermissionRowProps {
  perm: MailboxUserPermissionResponse
  mailboxId: string
  onRevoke: () => void
  onUpdate: () => void
}

function PermissionRow({ perm, mailboxId, onRevoke }: PermissionRowProps) {
  const updateMutation = useMutation({
    mutationFn: (data: { can_read: boolean; can_send: boolean; can_manage: boolean }) =>
      permissionsApi.grant(mailboxId, perm.user_id, data),
    onSuccess: () => toast.success('Permesso aggiornato'),
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const toggle = (field: 'can_read' | 'can_send' | 'can_manage') => {
    updateMutation.mutate({
      can_read: field === 'can_read' ? !perm.can_read : perm.can_read,
      can_send: field === 'can_send' ? !perm.can_send : perm.can_send,
      can_manage: field === 'can_manage' ? !perm.can_manage : perm.can_manage,
    })
  }

  return (
    <tr className="hover:bg-muted/30 transition-colors">
      <td className="px-4 py-3">
        <div>
          <p className="font-medium">{perm.full_name}</p>
          <p className="text-xs text-muted-foreground">{perm.email}</p>
        </div>
      </td>
      <td className="px-4 py-3">
        <span className="text-xs bg-muted px-2 py-0.5 rounded">
          {ROLE_LABELS[perm.role] || perm.role}
        </span>
      </td>
      {(['can_read', 'can_send', 'can_manage'] as const).map((field) => (
        <td key={field} className="px-4 py-3 text-center">
          <button
            onClick={() => toggle(field)}
            className={cn(
              'h-5 w-5 rounded border-2 inline-flex items-center justify-center transition-colors',
              perm[field]
                ? 'bg-primary border-primary text-primary-foreground'
                : 'border-muted-foreground/40 bg-background hover:border-primary',
            )}
          >
            {perm[field] && <span className="text-xs">✓</span>}
          </button>
        </td>
      ))}
      <td className="px-4 py-3 text-right">
        <Button
          variant="ghost"
          size="icon"
          className="h-8 w-8 text-destructive hover:bg-destructive/10"
          onClick={onRevoke}
          title="Revoca accesso"
        >
          <Trash2 className="h-4 w-4" />
        </Button>
      </td>
    </tr>
  )
}

// ─── Dialog assegna permesso ──────────────────────────────────────────────────

interface GrantPermissionDialogProps {
  mailboxId: string
  onClose: () => void
  onSaved: () => void
}

function GrantPermissionDialog({ mailboxId, onClose, onSaved }: GrantPermissionDialogProps) {
  const [selectedUserId, setSelectedUserId] = useState('')
  const [canRead, setCanRead] = useState(true)
  const [canSend, setCanSend] = useState(false)
  const [canManage, setCanManage] = useState(false)

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

  const grantMutation = useMutation({
    mutationFn: () =>
      permissionsApi.grant(mailboxId, selectedUserId, {
        can_read: canRead,
        can_send: canSend,
        can_manage: canManage,
      }),
    onSuccess: () => {
      toast.success('Permesso assegnato')
      onSaved()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const users = usersData?.items?.filter((u) => u.is_active) || []

  return (
    <Dialog open onOpenChange={(o) => !o && onClose()}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Assegna permesso casella</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 mt-4">
          <div className="space-y-2">
            <Label>Utente</Label>
            <select
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              value={selectedUserId}
              onChange={(e) => setSelectedUserId(e.target.value)}
            >
              <option value="">Seleziona utente...</option>
              {users.map((u) => (
                <option key={u.id} value={u.id}>
                  {u.full_name} ({u.email})
                </option>
              ))}
            </select>
          </div>

          <div className="space-y-2">
            <Label>Permessi</Label>
            <div className="space-y-2">
              {[
                { key: 'can_read', label: 'Lettura messaggi', state: canRead, setState: setCanRead },
                { key: 'can_send', label: 'Invio PEC', state: canSend, setState: setCanSend },
                { key: 'can_manage', label: 'Gestione casella', state: canManage, setState: setCanManage },
              ].map(({ key, label, state, setState }) => (
                <label key={key} className="flex items-center gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={state}
                    onChange={(e) => setState(e.target.checked)}
                    className="h-4 w-4 rounded border-input"
                  />
                  <span className="text-sm">{label}</span>
                </label>
              ))}
            </div>
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={onClose}>Annulla</Button>
          <Button
            onClick={() => grantMutation.mutate()}
            disabled={!selectedUserId}
            isLoading={grantMutation.isPending}
          >
            Assegna
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
