'use client'

import { useState } from 'react'
import { Shield, ShieldAlert, Plus, Trash2, Save } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Label } from '@/components/ui/label'
import useSWR from 'swr'
import { useAuth } from '@/lib/auth-context'
import { apiFetch } from '@/lib/fetcher'

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { cn } from '@/lib/utils'

const fetcher = (url: string) =>
  fetch(url).then((r) => r.json()).then((d) => (Array.isArray(d) ? d : d?.data ?? d))

const OPERATIONS = [
  { id: 'user.create', label: 'Criar usuário' },
  { id: 'user.update', label: 'Editar usuário' },
  { id: 'user.disable', label: 'Inativar usuário' },
  { id: 'user.reset_password', label: 'Redefinir senha' },
  { id: 'user.assign_group', label: 'Adicionar a grupos' },
  { id: 'user.remove_group', label: 'Remover de grupos' },
  { id: 'user.clone', label: 'Clonar usuário' },
  { id: 'group.create', label: 'Criar grupos' },
  { id: 'group.add_member', label: 'Adicionar membros a grupos' },
  { id: 'group.remove_member', label: 'Remover membros de grupos' },
  { id: 'sync.manual', label: 'Sincronização manual' },
]

export default function PermissionsPage() {
  const { user } = useAuth()
  const [selectedTenant, setSelectedTenant] = useState(user?.tenantId ?? '')
  const [protectedGroups, setProtectedGroups] = useState<string[]>([])
  const [protectedUsers, setProtectedUsers] = useState<string[]>([])
  const [allowedOUs, setAllowedOUs] = useState<string[]>([])
  const [blockedNames, setBlockedNames] = useState<string[]>([])
  const [newProtectedGroup, setNewProtectedGroup] = useState('')
  const [newProtectedUser, setNewProtectedUser] = useState('')
  const [newAllowedOU, setNewAllowedOU] = useState('')
  const [newBlockedName, setNewBlockedName] = useState('')
  const [allowedOps, setAllowedOps] = useState<string[]>(OPERATIONS.map((o) => o.id))
  const [saved, setSaved] = useState(false)
  const [saving, setSaving] = useState(false)

  const { data: tenantsRaw } = useSWR('/api/tenants', fetcher)
  const tenants: any[] = Array.isArray(tenantsRaw) ? tenantsRaw : []
  const { data: policy } = useSWR(
    selectedTenant ? `/api/tenant-config?tenant_id=${selectedTenant}` : null,
    fetcher,
  )

  function addItem(list: string[], setList: (v: string[]) => void, value: string, setValue: (v: string) => void) {
    if (value.trim() && !list.includes(value.trim())) {
      setList([...list, value.trim()])
      setValue('')
    }
  }

  function removeItem(list: string[], setList: (v: string[]) => void, value: string) {
    setList(list.filter((i) => i !== value))
  }

  function toggleOp(id: string) {
    setAllowedOps((prev) =>
      prev.includes(id) ? prev.filter((o) => o !== id) : [...prev, id],
    )
  }

  async function handleSave() {
    setSaving(true)
    await apiFetch('/api/permissions', {
      method: 'POST',
      body: JSON.stringify({
        tenant_id: selectedTenant,
        allowed_operations: allowedOps,
        protected_groups: protectedGroups,
        protected_users: protectedUsers,
        allowed_ous: allowedOUs,
        blocked_name_patterns: blockedNames,
      }),
    })
    setSaving(false)
    setSaved(true)
    setTimeout(() => setSaved(false), 2000)
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-bold text-foreground">Permissões e Objetos Protegidos</h2>
          <p className="text-sm text-muted-foreground">Configure proteções, OUs permitidas e operações liberadas por tenant.</p>
        </div>
        <Button onClick={handleSave} disabled={saving}>
          <Save className="w-4 h-4 mr-2" />
          {saving ? 'Salvando...' : saved ? 'Salvo!' : 'Salvar Configurações'}
        </Button>
      </div>

      {/* Seletor de tenant */}
      <div className="flex items-center gap-3">
        <Label>Empresa:</Label>
        <Select value={selectedTenant} onValueChange={setSelectedTenant}>
          <SelectTrigger className="w-64">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            {tenants.filter((t: any) => t.status === 'active').map((t: any) => (
              <SelectItem key={t.id} value={String(t.id)}>{t.name}</SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>

      <div className="grid lg:grid-cols-2 gap-6">
        {/* Operações permitidas */}
        <div className="bg-card border border-border rounded-xl p-5 space-y-4">
          <h3 className="font-semibold text-foreground flex items-center gap-2">
            <Shield className="w-4 h-4 text-primary" />
            Operações Permitidas
          </h3>
          <p className="text-xs text-muted-foreground">Defina quais ações os operadores deste tenant podem realizar.</p>
          <div className="space-y-2">
            {OPERATIONS.map((op) => (
              <div key={op.id} className="flex items-center gap-3 py-1">
                <Switch
                  id={`op-${op.id}`}
                  checked={allowedOps.includes(op.id)}
                  onCheckedChange={() => toggleOp(op.id)}
                />
                <Label htmlFor={`op-${op.id}`} className="text-sm cursor-pointer">
                  {op.label}
                </Label>
              </div>
            ))}
          </div>
        </div>

        {/* Políticas */}
        {policy && (
          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <h3 className="font-semibold text-foreground flex items-center gap-2">
              <ShieldAlert className="w-4 h-4 text-yellow-500" />
              Políticas de Criação de Usuário
            </h3>
            <p className="text-xs text-muted-foreground">Defina políticas padrão e o que o operador pode personalizar.</p>
            <div className="space-y-3">
              {[
                { label: 'Trocar senha no 1º login', fixed: !policy.operatorCanChooseMustChange, value: policy.mustChangePasswordOnFirstLogin },
                { label: 'Não pode alterar senha', fixed: !policy.operatorCanChooseCannotChange, value: policy.cannotChangePassword },
                { label: 'Senha nunca expira', fixed: !policy.operatorCanChooseNeverExpires, value: policy.passwordNeverExpires },
                { label: 'Conta inicia habilitada', fixed: !policy.operatorCanChooseEnabled, value: policy.accountStartsEnabled },
              ].map((p) => (
                <div key={p.label} className="flex items-center justify-between py-1">
                  <div>
                    <p className="text-sm text-foreground">{p.label}</p>
                    <p className="text-xs text-muted-foreground">
                      {p.fixed ? 'Travado — operador não pode alterar' : 'Operador pode personalizar'}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <Switch checked={p.value} disabled={false} />
                    <span className={cn('text-xs', p.fixed ? 'text-muted-foreground' : 'text-primary')}>
                      {p.fixed ? 'Fixo' : 'Livre'}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Grupos protegidos */}
        <div className="bg-card border border-border rounded-xl p-5 space-y-4">
          <h3 className="font-semibold text-foreground flex items-center gap-2">
            <ShieldAlert className="w-4 h-4 text-red-500" />
            Grupos Protegidos
          </h3>
          <p className="text-xs text-muted-foreground">Grupos que não podem ser modificados pelo operador.</p>
          <div className="flex gap-2">
            <Input
              value={newProtectedGroup}
              onChange={(e) => setNewProtectedGroup(e.target.value)}
              placeholder="Nome do grupo"
              onKeyDown={(e) => e.key === 'Enter' && addItem(protectedGroups, setProtectedGroups, newProtectedGroup, setNewProtectedGroup)}
            />
            <Button size="sm" variant="outline" onClick={() => addItem(protectedGroups, setProtectedGroups, newProtectedGroup, setNewProtectedGroup)}>
              <Plus className="w-4 h-4" />
            </Button>
          </div>
          <div className="space-y-2">
            {protectedGroups.map((g) => (
              <div key={g} className="flex items-center justify-between bg-red-50 dark:bg-red-900/20 rounded-md px-3 py-1.5">
                <span className="text-sm font-mono text-foreground">{g}</span>
                <button onClick={() => removeItem(protectedGroups, setProtectedGroups, g)} className="text-destructive hover:opacity-70">
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Usuários protegidos */}
        <div className="bg-card border border-border rounded-xl p-5 space-y-4">
          <h3 className="font-semibold text-foreground flex items-center gap-2">
            <ShieldAlert className="w-4 h-4 text-orange-500" />
            Usuários Protegidos
          </h3>
          <p className="text-xs text-muted-foreground">Contas que não podem ser modificadas pelo operador.</p>
          <div className="flex gap-2">
            <Input
              value={newProtectedUser}
              onChange={(e) => setNewProtectedUser(e.target.value)}
              placeholder="sAMAccountName"
              onKeyDown={(e) => e.key === 'Enter' && addItem(protectedUsers, setProtectedUsers, newProtectedUser, setNewProtectedUser)}
            />
            <Button size="sm" variant="outline" onClick={() => addItem(protectedUsers, setProtectedUsers, newProtectedUser, setNewProtectedUser)}>
              <Plus className="w-4 h-4" />
            </Button>
          </div>
          <div className="space-y-2">
            {protectedUsers.map((u) => (
              <div key={u} className="flex items-center justify-between bg-orange-50 dark:bg-orange-900/20 rounded-md px-3 py-1.5">
                <span className="text-sm font-mono text-foreground">{u}</span>
                <button onClick={() => removeItem(protectedUsers, setProtectedUsers, u)} className="text-destructive hover:opacity-70">
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* OUs permitidas */}
        <div className="bg-card border border-border rounded-xl p-5 space-y-4">
          <h3 className="font-semibold text-foreground flex items-center gap-2">
            <Shield className="w-4 h-4 text-green-600" />
            OUs Permitidas (Whitelist)
          </h3>
          <p className="text-xs text-muted-foreground">Operadores só poderão gerenciar objetos dentro destas OUs.</p>
          <div className="flex gap-2">
            <Input
              value={newAllowedOU}
              onChange={(e) => setNewAllowedOU(e.target.value)}
              placeholder="OU=Usuarios,DC=empresa,DC=local"
              className="font-mono text-xs"
              onKeyDown={(e) => e.key === 'Enter' && addItem(allowedOUs, setAllowedOUs, newAllowedOU, setNewAllowedOU)}
            />
            <Button size="sm" variant="outline" onClick={() => addItem(allowedOUs, setAllowedOUs, newAllowedOU, setNewAllowedOU)}>
              <Plus className="w-4 h-4" />
            </Button>
          </div>
          <div className="space-y-2">
            {allowedOUs.map((ou) => (
              <div key={ou} className="flex items-center justify-between bg-green-50 dark:bg-green-900/20 rounded-md px-3 py-1.5">
                <span className="text-xs font-mono text-foreground break-all">{ou}</span>
                <button onClick={() => removeItem(allowedOUs, setAllowedOUs, ou)} className="text-destructive hover:opacity-70 ml-2 shrink-0">
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        </div>

        {/* Blacklist */}
        <div className="bg-card border border-border rounded-xl p-5 space-y-4">
          <h3 className="font-semibold text-foreground flex items-center gap-2">
            <ShieldAlert className="w-4 h-4 text-gray-500" />
            Blacklist de Nomes / DNs
          </h3>
          <p className="text-xs text-muted-foreground">Padrões de nome ou DN que devem ser bloqueados.</p>
          <div className="flex gap-2">
            <Input
              value={newBlockedName}
              onChange={(e) => setNewBlockedName(e.target.value)}
              placeholder="ex: admin, CN=teste"
              onKeyDown={(e) => e.key === 'Enter' && addItem(blockedNames, setBlockedNames, newBlockedName, setNewBlockedName)}
            />
            <Button size="sm" variant="outline" onClick={() => addItem(blockedNames, setBlockedNames, newBlockedName, setNewBlockedName)}>
              <Plus className="w-4 h-4" />
            </Button>
          </div>
          <div className="space-y-2">
            {blockedNames.length === 0 && (
              <p className="text-sm text-muted-foreground">Nenhum padrão bloqueado.</p>
            )}
            {blockedNames.map((n) => (
              <div key={n} className="flex items-center justify-between bg-gray-50 dark:bg-gray-800 rounded-md px-3 py-1.5">
                <span className="text-sm font-mono text-foreground">{n}</span>
                <button onClick={() => removeItem(blockedNames, setBlockedNames, n)} className="text-destructive hover:opacity-70">
                  <Trash2 className="w-3.5 h-3.5" />
                </button>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
