'use client'

import { use, useState } from 'react'
import Link from 'next/link'
import {
  ArrowLeft, Edit, KeyRound, UserX, UserCheck,
  Copy, UsersRound, Mail, Phone, Building2,
  Briefcase, FolderOpen, Shield, Clock, RefreshCw,
} from 'lucide-react'
import { Button } from '@/components/ui/button'
import { formatDate, formatRelativeTime, generatePassword } from '@/lib/utils-ad'
import { ConfirmActionModal } from '@/components/ui/confirm-action-modal'
import { ADUserFormModal } from '../_components/ad-user-form-modal'
import { cn } from '@/lib/utils'
import {
  Dialog, DialogContent, DialogHeader,
  DialogTitle, DialogDescription, DialogFooter,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import useSWR from 'swr'
import { arrayFetcher } from '@/lib/fetcher'

function fetcher(url: string) {
  const token = typeof window !== 'undefined' ? sessionStorage.getItem('adm_token') : null
  return fetch(url, {
    credentials: 'include',
    headers: token ? { Authorization: `Bearer ${token}` } : {},
  }).then((r) => r.ok ? r.json() : null)
}

export default function ADUserDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)

  const { data: user, mutate } = useSWR(`/api/ad/users/${id}`, fetcher)
  const { data: groups = [] } = useSWR('/api/ad/groups', arrayFetcher)
  const { data: auditLogs = [] } = useSWR(`/api/audit?limit=6&object_id=${id}`, (url: string) =>
    fetcher(url).then((d) => d?.data ?? [])
  )

  const [showEdit, setShowEdit] = useState(false)
  const [showConfirmToggle, setShowConfirmToggle] = useState(false)
  const [showReset, setShowReset] = useState(false)
  const [newPassword, setNewPassword] = useState('')
  const [enabled, setEnabled] = useState<boolean | null>(null)

  const isEnabled = enabled ?? user?.enabled ?? true
  const userGroups = groups.filter((g: any) => user?.groups?.includes(g.samAccountName))

  if (!user) {
    return (
      <div className="flex items-center justify-center h-64">
        <p className="text-muted-foreground">Carregando...</p>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/ad/users">
          <Button variant="outline" size="sm">
            <ArrowLeft className="w-4 h-4 mr-2" />
            Voltar
          </Button>
        </Link>
        <div className="flex items-center gap-4 flex-1">
          <div className={cn(
            'w-12 h-12 rounded-full flex items-center justify-center text-base font-bold',
            isEnabled ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground',
          )}>
            {user.displayName?.slice(0, 2).toUpperCase()}
          </div>
          <div>
            <h2 className="text-xl font-bold text-foreground">{user.displayName}</h2>
            <p className="text-sm text-muted-foreground font-mono">{user.upn}</p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <span className={cn(
            'inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium',
            isEnabled ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-600',
          )}>
            {isEnabled ? 'Habilitado' : 'Desabilitado'}
          </span>
          <Button variant="outline" size="sm" onClick={() => setShowEdit(true)}>
            <Edit className="w-4 h-4 mr-2" />Editar
          </Button>
          <Button variant="outline" size="sm" onClick={() => { setNewPassword(generatePassword()); setShowReset(true) }}>
            <KeyRound className="w-4 h-4 mr-2" />Redefinir senha
          </Button>
          <Button variant={isEnabled ? 'destructive' : 'outline'} size="sm" onClick={() => setShowConfirmToggle(true)}>
            {isEnabled ? <UserX className="w-4 h-4 mr-2" /> : <UserCheck className="w-4 h-4 mr-2" />}
            {isEnabled ? 'Desabilitar' : 'Habilitar'}
          </Button>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 space-y-4">
          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <h3 className="font-semibold text-foreground">Dados Pessoais</h3>
            <div className="grid grid-cols-2 gap-4">
              {[
                { icon: Mail, label: 'E-mail', value: user.email },
                { icon: Phone, label: 'Telefone', value: user.phone ?? '—' },
                { icon: Building2, label: 'Departamento', value: user.department ?? '—' },
                { icon: Briefcase, label: 'Cargo', value: user.title ?? '—' },
              ].map((f) => (
                <div key={f.label} className="flex items-start gap-3">
                  <f.icon className="w-4 h-4 text-muted-foreground mt-0.5 shrink-0" />
                  <div>
                    <p className="text-xs text-muted-foreground">{f.label}</p>
                    <p className="text-sm text-foreground">{f.value}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <h3 className="font-semibold text-foreground">Conta Active Directory</h3>
            <div className="grid grid-cols-2 gap-3 text-sm">
              {[
                { label: 'sAMAccountName', value: user.samAccountName },
                { label: 'UPN', value: user.upn },
                { label: 'OU', value: user.ou },
                { label: 'Criado em', value: formatDate(user.createdAt) },
                { label: 'Última sincronização', value: formatDate(user.lastSync) },
              ].map((f) => (
                <div key={f.label}>
                  <p className="text-xs text-muted-foreground">{f.label}</p>
                  <p className="font-mono text-xs text-foreground mt-0.5 break-all">{f.value}</p>
                </div>
              ))}
            </div>
            <div className="pt-2 border-t border-border">
              <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-2">Opções da conta</p>
              <div className="flex flex-wrap gap-2">
                {[
                  { label: 'Habilitado', active: user.enabled },
                  { label: 'Trocar senha próx. login', active: user.mustChangePassword },
                  { label: 'Não pode alterar senha', active: user.cannotChangePassword },
                  { label: 'Senha nunca expira', active: user.passwordNeverExpires },
                ].map((flag) => (
                  <span key={flag.label} className={cn(
                    'inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium',
                    flag.active ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground',
                  )}>
                    <span className={cn('w-1.5 h-1.5 rounded-full', flag.active ? 'bg-primary' : 'bg-muted-foreground')} />
                    {flag.label}
                  </span>
                ))}
              </div>
            </div>
          </div>

          <div className="bg-card border border-border rounded-xl overflow-hidden">
            <div className="flex items-center justify-between px-5 py-4 border-b border-border">
              <h3 className="font-semibold text-foreground flex items-center gap-2">
                <Clock className="w-4 h-4 text-muted-foreground" />
                Histórico de Ações
              </h3>
              <Link href="/audit" className="text-xs text-primary hover:underline">Ver auditoria</Link>
            </div>
            <div className="divide-y divide-border">
              {auditLogs.length === 0 ? (
                <p className="px-5 py-6 text-center text-sm text-muted-foreground">Nenhuma ação registrada.</p>
              ) : auditLogs.map((log: any) => (
                <div key={log.id} className="px-5 py-3 flex items-start gap-3">
                  <span className={cn('mt-1 w-2 h-2 rounded-full shrink-0', log.status === 'success' ? 'bg-green-500' : 'bg-red-500')} />
                  <div className="flex-1">
                    <p className="text-sm text-foreground">{log.details}</p>
                    <p className="text-xs text-muted-foreground mt-0.5">
                      {log.user_name ?? log.userName} &middot; {formatRelativeTime(log.created_at ?? log.createdAt)}
                    </p>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="space-y-4">
          <div className="bg-card border border-border rounded-xl p-5 space-y-4">
            <div className="flex items-center justify-between">
              <h3 className="font-semibold text-foreground flex items-center gap-2">
                <UsersRound className="w-4 h-4 text-muted-foreground" />
                Grupos ({user.groups?.length ?? 0})
              </h3>
            </div>
            <div className="space-y-2">
              {!user.groups?.length ? (
                <p className="text-sm text-muted-foreground">Sem grupos.</p>
              ) : user.groups.map((g: string) => {
                const group = userGroups.find((grp: any) => grp.samAccountName === g)
                return (
                  <div key={g} className="flex items-center justify-between px-3 py-2 rounded-md bg-muted/30">
                    <div>
                      <p className="text-sm font-medium text-foreground">{g}</p>
                      {group?.description && <p className="text-xs text-muted-foreground">{group.description}</p>}
                    </div>
                    {group?.protected && <Shield className="w-3.5 h-3.5 text-muted-foreground shrink-0" />}
                  </div>
                )
              })}
            </div>
            <Button variant="outline" size="sm" className="w-full">
              <UsersRound className="w-4 h-4 mr-2" />Gerenciar grupos
            </Button>
          </div>

          <div className="bg-card border border-border rounded-xl p-5 space-y-3">
            <h3 className="font-semibold text-foreground flex items-center gap-2">
              <FolderOpen className="w-4 h-4 text-muted-foreground" />
              Empresa
            </h3>
            <div>
              <p className="text-sm font-medium text-foreground">{user.tenantName ?? '—'}</p>
              <p className="text-xs text-muted-foreground">{user.domain ?? '—'}</p>
            </div>
          </div>
        </div>
      </div>

      <ADUserFormModal
        open={showEdit}
        onClose={() => setShowEdit(false)}
        user={user}
        tenantId={user.tenantId}
        upnSuffix={user.upnSuffix ?? ''}
        defaultOU={user.ou ?? ''}
      />

      <Dialog open={showReset} onOpenChange={setShowReset}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>Redefinir Senha</DialogTitle>
            <DialogDescription>Define uma nova senha para este usuário no Active Directory.</DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Nova senha para <span className="font-medium text-foreground">{user.displayName}</span>.
            </p>
            <div className="space-y-2">
              <Label>Nova senha</Label>
              <div className="flex gap-2">
                <Input value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className="font-mono" />
                <Button variant="outline" size="sm" onClick={() => setNewPassword(generatePassword())}><RefreshCw className="w-4 h-4" /></Button>
                <Button variant="outline" size="sm" onClick={() => navigator.clipboard.writeText(newPassword)}><Copy className="w-4 h-4" /></Button>
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowReset(false)}>Cancelar</Button>
            <Button onClick={() => setShowReset(false)}>Redefinir</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <ConfirmActionModal
        open={showConfirmToggle}
        onClose={() => setShowConfirmToggle(false)}
        onConfirm={() => { setEnabled(!isEnabled); setShowConfirmToggle(false) }}
        title={isEnabled ? 'Desabilitar conta' : 'Habilitar conta'}
        description={isEnabled ? 'A conta será desabilitada no Active Directory.' : 'A conta será habilitada no Active Directory.'}
        objectName={user.displayName}
        changeSummary={`${isEnabled ? 'Desabilitar' : 'Habilitar'} conta: ${user.samAccountName}`}
        confirmLabel={isEnabled ? 'Desabilitar' : 'Habilitar'}
        variant={isEnabled ? 'destructive' : 'default'}
      />
    </div>
  )
}
