"use client"

import { useMemo, useState } from "react"
import Link from "next/link"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Settings2, Share2, ShieldCheck, UserCog, UserPlus, Users2, Layers3 } from "lucide-react"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Separator } from "@/components/ui/separator"
import { useAuth, signOut } from "@/lib/auth-client"
import { DEFAULT_TENANT_ID } from "@/lib/constants"

import type { LucideIcon } from "lucide-react"

type RoleRequirement = "admin" | "staff"

type SettingsAction = {
  title: string
  description: string
  href: string
  cta: string
  requiredRole?: RoleRequirement
  icon: LucideIcon
}

const ROLE_LABELS: Record<string, string> = {
  admin: "Administrador",
  manager: "Gestor",
  agent: "Agente",
  collaborator: "Colaborador",
  customer: "Cliente",
}

const SETTINGS_ACTIONS: SettingsAction[] = [
  {
    title: "Times & papéis",
    description: "Controle quem pode atuar nas filas e atribua permissões refinadas por equipe.",
    href: "/admin/teams",
    cta: "Gerenciar times",
    requiredRole: "admin",
    icon: Users2,
  },
  {
    title: "Canais & roteamento",
    description: "Configure canais, horários de atendimento e regras automáticas de distribuição.",
    href: "/admin/channels",
    cta: "Abrir canais",
    requiredRole: "admin",
    icon: Share2,
  },
  {
    title: "Campos e categorias",
    description: "Ajuste categorias, subcategorias e campos personalizados para qualificar tickets.",
    href: "/admin/fields",
    cta: "Editar estrutura",
    requiredRole: "admin",
    icon: Layers3,
  },
  {
    title: "Convites e acessos",
    description: "Convide novos usuários, revise papéis e acompanhe quem tem acesso ao workspace.",
    href: "/admin",
    cta: "Abrir painel",
    requiredRole: "admin",
    icon: UserPlus,
  },
  {
    title: "Preferências da equipe",
    description: "Defina padrões de notificação e comportamento do modo play para toda a equipe.",
    href: "#preferencias",
    cta: "Ajustar preferências",
    requiredRole: "staff",
    icon: Settings2,
  },
  {
    title: "Políticas e segurança",
    description: "Acompanhe SLAs críticos, rastreie integrações e revise auditorias de acesso.",
    href: "/admin/slas",
    cta: "Revisar SLAs",
    requiredRole: "admin",
    icon: ShieldCheck,
  },
]

export function SettingsContent() {
  const { session, isAdmin, isStaff } = useAuth()
  const [isSigningOut, setIsSigningOut] = useState(false)
  const router = useRouter()

  const normalizedRole = session?.user.role?.toLowerCase() ?? "agent"
  const roleLabel = ROLE_LABELS[normalizedRole] ?? "Agente"
  const tenant = session?.user.tenantId ?? DEFAULT_TENANT_ID

  const sessionExpiry = useMemo(() => {
    const expiresAt = session?.session?.expiresAt
    if (!expiresAt) return null
    return new Intl.DateTimeFormat("pt-BR", {
      dateStyle: "long",
      timeStyle: "short",
    }).format(new Date(expiresAt))
  }, [session?.session?.expiresAt])

  async function handleSignOut() {
    if (isSigningOut) return
    setIsSigningOut(true)
    try {
      await signOut()
      toast.success("Sessão encerrada")
      router.replace("/login")
    } catch (error) {
      console.error(error)
      toast.error("Não foi possível encerrar a sessão.")
    } finally {
      setIsSigningOut(false)
    }
  }

  function canAccess(requiredRole?: RoleRequirement) {
    if (!requiredRole) return true
    if (requiredRole === "admin") return isAdmin
    if (requiredRole === "staff") return isStaff
    return false
  }

  return (
    <div className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-4 pb-12 lg:px-6">
      <div className="grid gap-6 lg:grid-cols-[minmax(0,1.7fr)_minmax(0,1fr)] lg:items-start">
        <Card id="preferencias" className="border border-border/70">
          <CardHeader className="flex flex-col gap-1">
            <CardTitle className="text-2xl font-semibold text-neutral-900">Perfil</CardTitle>
            <CardDescription className="text-sm text-neutral-600">
              Dados sincronizados via Better Auth e utilizados para provisionamento no Convex.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <dl className="grid gap-4 text-sm text-neutral-700 sm:grid-cols-2">
              <div className="space-y-1">
                <dt className="text-xs uppercase tracking-wide text-neutral-500">Nome</dt>
                <dd className="font-medium text-neutral-900">{session?.user.name ?? "—"}</dd>
              </div>
              <div className="space-y-1">
                <dt className="text-xs uppercase tracking-wide text-neutral-500">E-mail</dt>
                <dd className="font-medium text-neutral-900">{session?.user.email ?? "—"}</dd>
              </div>
              <div className="space-y-1">
                <dt className="text-xs uppercase tracking-wide text-neutral-500">Tenant</dt>
                <dd>
                  <Badge variant="outline" className="rounded-full border-dashed px-2.5 py-1 text-xs uppercase tracking-wide">
                    {tenant}
                  </Badge>
                </dd>
              </div>
              <div className="space-y-1">
                <dt className="text-xs uppercase tracking-wide text-neutral-500">Papel</dt>
                <dd>
                  <Badge className="rounded-full px-3 py-1 text-xs font-semibold uppercase tracking-wide">
                    {roleLabel}
                  </Badge>
                </dd>
              </div>
            </dl>
            <Separator />
            <div className="space-y-2 text-sm text-neutral-600">
              <div className="flex items-center justify-between">
                <span className="font-medium text-neutral-800">Sessão ativa</span>
                {session?.session?.id ? (
                  <code className="rounded-md bg-slate-100 px-2 py-1 text-xs font-mono text-neutral-700">
                    {session.session.id.slice(0, 8)}…
                  </code>
                ) : null}
              </div>
              <p>{sessionExpiry ? `Expira em ${sessionExpiry}` : "Sessão em background com renovação automática."}</p>
              <p className="text-xs text-neutral-500">
                Alterações no perfil refletem instantaneamente no painel administrativo e nos relatórios.
              </p>
            </div>
          </CardContent>
          <CardFooter className="flex flex-wrap gap-2">
            <Button size="sm" variant="outline" disabled>
              Editar perfil (em breve)
            </Button>
            <Button size="sm" variant="outline" asChild>
              <Link href="mailto:suporte@sistema.dev">Solicitar ajustes</Link>
            </Button>
            <Button size="sm" variant="destructive" onClick={handleSignOut} disabled={isSigningOut}>
              Encerrar sessão
            </Button>
          </CardFooter>
        </Card>
        <Card className="border border-border/70">
          <CardHeader className="flex flex-col gap-1">
            <CardTitle className="flex items-center gap-2 text-lg font-semibold text-neutral-900">
              <UserCog className="size-4 text-neutral-500" /> Preferências rápidas
            </CardTitle>
            <CardDescription className="text-sm text-neutral-600">
              Ajustes pessoais aplicados localmente para acelerar seu fluxo de trabalho.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <PreferenceItem
              title="Abertura de tickets"
              description="Sempre abrir detalhes em nova aba ao clicar na listagem."
            />
            <PreferenceItem
              title="Notificações"
              description="Receber alertas sonoros ao entrar novos tickets urgentes."
            />
            <PreferenceItem
              title="Modo play"
              description="Priorizar tickets da fila 'Chamados' ao iniciar uma nova sessão."
            />
          </CardContent>
        </Card>
      </div>
      <section className="space-y-4">
        <div>
          <h2 className="text-base font-semibold text-neutral-900">Administração do workspace</h2>
          <p className="text-sm text-neutral-600">
            Centralize a gestão de times, canais e políticas. Recursos marcados como restritos dependem de perfil administrador.
          </p>
        </div>
        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {SETTINGS_ACTIONS.map((action) => {
            const allowed = canAccess(action.requiredRole)
            const Icon = action.icon
            return (
              <Card key={action.title} className="border border-border/70">
                <CardHeader className="flex flex-row items-start gap-3">
                  <div className="rounded-full bg-neutral-100 p-2 text-neutral-500">
                    <Icon className="size-4" />
                  </div>
                  <div className="flex flex-1 flex-col gap-1">
                    <CardTitle className="text-sm font-semibold text-neutral-900">{action.title}</CardTitle>
                    <CardDescription className="text-xs text-neutral-600">{action.description}</CardDescription>
                  </div>
                  {!allowed ? <Badge variant="outline" className="rounded-full border-dashed px-2 py-0.5 text-[10px] uppercase">Restrito</Badge> : null}
                </CardHeader>
                <CardFooter className="justify-end">
                  {allowed ? (
                    <Button asChild size="sm">
                      <Link href={action.href}>{action.cta}</Link>
                    </Button>
                  ) : (
                    <Button size="sm" variant="outline" disabled>
                      Acesso restrito
                    </Button>
                  )}
                </CardFooter>
              </Card>
            )
          })}
        </div>
      </section>
    </div>
  )
}

type PreferenceItemProps = {
  title: string
  description: string
}

function PreferenceItem({ title, description }: PreferenceItemProps) {
  const [enabled, setEnabled] = useState(false)

  return (
    <div className="flex items-start justify-between gap-4 rounded-xl border border-dashed border-slate-200/80 bg-white/70 p-4 shadow-[0_1px_2px_rgba(15,23,42,0.04)]">
      <div className="space-y-1">
        <p className="text-sm font-medium text-neutral-800">{title}</p>
        <p className="text-xs text-neutral-500">{description}</p>
      </div>
      <Button
        size="sm"
        variant={enabled ? "default" : "outline"}
        onClick={() => setEnabled((prev) => !prev)}
        className="min-w-[96px]"
      >
        {enabled ? "Ativado" : "Ativar"}
      </Button>
    </div>
  )
}
