import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Sliders, Plus, Pencil, Trash2 } 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 { permissionPresetsApi } from '@/api/permission_presets.api'
import { getErrorMessage } from '@/api/client'
import { cn } from '@/lib/utils'
import type { PermissionPresetResponse } from '@/types/api.types'

// ─── Flag visualizzazione permesso ───────────────────────────────────────────

interface PermissionBadgeProps {
  active: boolean
  label: string
}

function PermissionBadge({ active, label }: PermissionBadgeProps) {
  return (
    <span
      className={cn(
        'inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium',
        active
          ? 'bg-primary/10 text-primary border border-primary/20'
          : 'bg-muted text-muted-foreground border border-border',
      )}
    >
      <span className={cn('h-1.5 w-1.5 rounded-full', active ? 'bg-primary' : 'bg-muted-foreground/40')} />
      {label}
    </span>
  )
}

// ─── Pagina principale ────────────────────────────────────────────────────────

export function PermissionPresetsPage() {
  const queryClient = useQueryClient()
  const [showDialog, setShowDialog] = useState(false)
  const [editingPreset, setEditingPreset] = useState<PermissionPresetResponse | null>(null)

  const { data: presets = [], isLoading } = useQuery({
    queryKey: ['permission-presets'],
    queryFn: () => permissionPresetsApi.list(),
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => permissionPresetsApi.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['permission-presets'] })
      toast.success('Preset eliminato')
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const handleEdit = (preset: PermissionPresetResponse) => {
    setEditingPreset(preset)
    setShowDialog(true)
  }

  const handleNew = () => {
    setEditingPreset(null)
    setShowDialog(true)
  }

  const handleDelete = (preset: PermissionPresetResponse) => {
    if (!confirm(`Eliminare il preset "${preset.name}"? L'operazione non e' reversibile.`)) return
    deleteMutation.mutate(preset.id)
  }

  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">
          <Sliders className="h-5 w-5 text-primary" />
          <div>
            <h1 className="text-xl font-semibold">Preset Permessi</h1>
            <p className="text-sm text-muted-foreground">
              Definisci template di permessi riutilizzabili (sottoruoli) per gli operatori
            </p>
          </div>
        </div>
        <Button onClick={handleNew}>
          <Plus className="h-4 w-4 mr-2" />
          Nuovo preset
        </Button>
      </div>

      {/* Contenuto */}
      <div className="flex-1 overflow-y-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>
        ) : presets.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-64 text-center">
            <Sliders className="h-12 w-12 text-muted-foreground/30 mb-3" />
            <p className="font-medium mb-1">Nessun preset definito</p>
            <p className="text-sm text-muted-foreground mb-4">
              Crea dei preset per applicare rapidamente combinazioni di permessi agli operatori.
            </p>
            <Button onClick={handleNew}>
              <Plus className="h-4 w-4 mr-2" />
              Crea primo preset
            </Button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {presets.map((preset) => (
              <PresetCard
                key={preset.id}
                preset={preset}
                onEdit={() => handleEdit(preset)}
                onDelete={() => handleDelete(preset)}
                isDeleting={deleteMutation.isPending}
              />
            ))}
          </div>
        )}
      </div>

      {/* Dialog crea/modifica */}
      {showDialog && (
        <PresetDialog
          preset={editingPreset}
          onClose={() => setShowDialog(false)}
          onSaved={() => {
            queryClient.invalidateQueries({ queryKey: ['permission-presets'] })
            setShowDialog(false)
          }}
        />
      )}
    </div>
  )
}

// ─── Card preset ──────────────────────────────────────────────────────────────

interface PresetCardProps {
  preset: PermissionPresetResponse
  onEdit: () => void
  onDelete: () => void
  isDeleting: boolean
}

function PresetCard({ preset, onEdit, onDelete, isDeleting }: PresetCardProps) {
  return (
    <div className="rounded-lg border bg-card p-4 flex flex-col gap-3 hover:shadow-sm transition-shadow">
      {/* Titolo e descrizione */}
      <div className="flex items-start justify-between gap-2">
        <div className="min-w-0">
          <h3 className="font-semibold truncate">{preset.name}</h3>
          {preset.description && (
            <p className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
              {preset.description}
            </p>
          )}
        </div>
      </div>

      {/* Permessi */}
      <div className="flex flex-wrap gap-1.5">
        <PermissionBadge active={preset.can_read} label="Lettura" />
        <PermissionBadge active={preset.can_send} label="Invio" />
        <PermissionBadge active={preset.can_manage} label="Gestione" />
        <PermissionBadge active={preset.can_conserve} label="Conservazione" />
      </div>

      {/* Azioni */}
      <div className="flex justify-end gap-2 pt-1 border-t">
        <Button
          variant="ghost"
          size="sm"
          onClick={onEdit}
          className="h-7 text-xs"
        >
          <Pencil className="h-3 w-3 mr-1" />
          Modifica
        </Button>
        <Button
          variant="ghost"
          size="sm"
          onClick={onDelete}
          disabled={isDeleting}
          className="h-7 text-xs text-destructive hover:bg-destructive/10 hover:text-destructive"
        >
          <Trash2 className="h-3 w-3 mr-1" />
          Elimina
        </Button>
      </div>
    </div>
  )
}

// ─── Dialog crea/modifica preset ─────────────────────────────────────────────

interface PresetDialogProps {
  preset: PermissionPresetResponse | null
  onClose: () => void
  onSaved: () => void
}

function PresetDialog({ preset, onClose, onSaved }: PresetDialogProps) {
  const isEdit = preset !== null

  const [name, setName] = useState(preset?.name ?? '')
  const [description, setDescription] = useState(preset?.description ?? '')
  const [canRead, setCanRead] = useState(preset?.can_read ?? true)
  const [canSend, setCanSend] = useState(preset?.can_send ?? false)
  const [canManage, setCanManage] = useState(preset?.can_manage ?? false)
  const [canConserve, setCanConserve] = useState(preset?.can_conserve ?? false)

  const createMutation = useMutation({
    mutationFn: () =>
      permissionPresetsApi.create({
        name: name.trim(),
        description: description.trim() || null,
        can_read: canRead,
        can_send: canSend,
        can_manage: canManage,
        can_conserve: canConserve,
      }),
    onSuccess: () => {
      toast.success('Preset creato')
      onSaved()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const updateMutation = useMutation({
    mutationFn: () =>
      permissionPresetsApi.update(preset!.id, {
        name: name.trim(),
        description: description.trim() || null,
        can_read: canRead,
        can_send: canSend,
        can_manage: canManage,
        can_conserve: canConserve,
      }),
    onSuccess: () => {
      toast.success('Preset aggiornato')
      onSaved()
    },
    onError: (e) => toast.error(getErrorMessage(e)),
  })

  const isPending = createMutation.isPending || updateMutation.isPending

  const handleSave = () => {
    if (!name.trim()) {
      toast.error('Il nome e\' obbligatorio')
      return
    }
    if (isEdit) {
      updateMutation.mutate()
    } else {
      createMutation.mutate()
    }
  }

  const permFlags = [
    { key: 'can_read', label: 'Lettura messaggi', desc: 'Accesso in lettura alle PEC della casella', state: canRead, setState: setCanRead },
    { key: 'can_send', label: 'Invio PEC', desc: 'Possibilita\' di inviare messaggi dalla casella', state: canSend, setState: setCanSend },
    { key: 'can_manage', label: 'Gestione casella', desc: 'Modifica configurazione IMAP/SMTP della casella', state: canManage, setState: setCanManage },
    { key: 'can_conserve', label: 'Conservazione documenti', desc: 'Spostamento messaggi nella cartella di conservazione', state: canConserve, setState: setCanConserve },
  ]

  return (
    <Dialog open onOpenChange={(o) => !o && onClose()}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>{isEdit ? 'Modifica preset' : 'Nuovo preset permessi'}</DialogTitle>
        </DialogHeader>

        <div className="space-y-4 mt-2">
          {/* Nome */}
          <div className="space-y-1.5">
            <Label htmlFor="preset-name">Nome <span className="text-destructive">*</span></Label>
            <input
              id="preset-name"
              type="text"
              className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
              placeholder="Es. Operatore Archivio, Operatore Invio..."
              value={name}
              onChange={(e) => setName(e.target.value)}
              maxLength={100}
            />
          </div>

          {/* Descrizione */}
          <div className="space-y-1.5">
            <Label htmlFor="preset-desc">Descrizione</Label>
            <textarea
              id="preset-desc"
              className="flex w-full rounded-md border border-input bg-background px-3 py-2 text-sm resize-none"
              rows={2}
              placeholder="Descrizione opzionale del preset..."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
            />
          </div>

          {/* Permessi */}
          <div className="space-y-2">
            <Label>Permessi inclusi nel preset</Label>
            <div className="space-y-3 rounded-md border p-3 bg-muted/30">
              {permFlags.map(({ key, label, desc, state, setState }) => (
                <label key={key} className="flex items-start gap-3 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={state}
                    onChange={(e) => setState(e.target.checked)}
                    className="h-4 w-4 mt-0.5 rounded border-input flex-shrink-0"
                  />
                  <div>
                    <p className="text-sm font-medium leading-tight">{label}</p>
                    <p className="text-xs text-muted-foreground">{desc}</p>
                  </div>
                </label>
              ))}
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={onClose} disabled={isPending}>
            Annulla
          </Button>
          <Button onClick={handleSave} isLoading={isPending} disabled={!name.trim()}>
            {isEdit ? 'Salva modifiche' : 'Crea preset'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
