import { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { ArrowLeft, Shield, Crown, UserCheck, UserX, Clock, Ticket, KeyRound, Copy, Check, Archive, ArchiveRestore, Trash2 } from 'lucide-react'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { StatusBadge } from '@/components/admin'
import { Modal } from '@/components/common/Modal'
import { Spinner } from '@/components/common/Spinner'
import { EmptyState } from '@/components/common/EmptyState'
import { adminApi } from '@/api/admin'
import { toast } from '@/lib/toast'
import { cn } from '@/lib/utils'
import type { UserDetailResponse } from '@/types/admin'

const PLAN_OPTIONS = ['free', 'pro', 'team'] as const

export function UserDetailPage() {
  const { userId } = useParams<{ userId: string }>()
  const navigate = useNavigate()
  const [user, setUser] = useState<UserDetailResponse | null>(null)
  const [loading, setLoading] = useState(true)

  // Modal state
  const [planModalOpen, setPlanModalOpen] = useState(false)
  const [selectedPlan, setSelectedPlan] = useState('')
  const [trialModalOpen, setTrialModalOpen] = useState(false)
  const [trialDays, setTrialDays] = useState('14')
  const [activeTab, setActiveTab] = useState<'sessions' | 'audit'>('sessions')

  // Password reset modal
  const [resetModalOpen, setResetModalOpen] = useState(false)
  const [resetMode, setResetMode] = useState<'email_link' | 'temp_password'>('email_link')
  const [resetLoading, setResetLoading] = useState(false)
  const [resetTempPassword, setResetTempPassword] = useState<string | null>(null)
  const [resetCopied, setResetCopied] = useState(false)

  // Super admin
  const [superAdminModalOpen, setSuperAdminModalOpen] = useState(false)

  // Hard delete
  const [hardDeleteModalOpen, setHardDeleteModalOpen] = useState(false)
  const [hardDeleteChecking, setHardDeleteChecking] = useState(false)
  const [hardDeleteBlockers, setHardDeleteBlockers] = useState<Record<string, number> | null>(null)

  const fetchUser = useCallback(async () => {
    if (!userId) return
    setLoading(true)
    try {
      const data = await adminApi.getUserDetail(userId)
      setUser(data)
    } catch {
      toast.error('Failed to load user details')
    } finally {
      setLoading(false)
    }
  }, [userId])

  useEffect(() => { fetchUser() }, [fetchUser])

  const handleChangePlan = async () => {
    if (!userId || !selectedPlan) return
    try {
      await adminApi.updateUserSubscriptionPlan(userId, selectedPlan)
      toast.success(`Plan changed to ${selectedPlan}`)
      setPlanModalOpen(false)
      fetchUser()
    } catch {
      toast.error('Failed to change plan')
    }
  }

  const handleExtendTrial = async () => {
    if (!userId || !trialDays) return
    try {
      await adminApi.extendUserTrial(userId, parseInt(trialDays))
      toast.success(`Trial extended by ${trialDays} days`)
      setTrialModalOpen(false)
      fetchUser()
    } catch {
      toast.error('Failed to extend trial')
    }
  }

  const handleToggleActive = async () => {
    if (!userId || !user) return
    try {
      if (user.is_active) {
        await adminApi.deactivateUser(userId)
        toast.success('User deactivated')
      } else {
        await adminApi.activateUser(userId)
        toast.success('User activated')
      }
      fetchUser()
    } catch {
      toast.error('Failed to update user status')
    }
  }

  const handleResetPassword = async () => {
    if (!userId) return
    setResetLoading(true)
    try {
      const result = await adminApi.adminResetPassword(userId, resetMode)
      if (resetMode === 'temp_password' && result.temporary_password) {
        setResetTempPassword(result.temporary_password)
        setResetCopied(false)
      } else {
        toast.success(result.email_sent ? 'Password reset email sent' : result.message)
        setResetModalOpen(false)
      }
      fetchUser()
    } catch {
      toast.error('Failed to reset password')
    } finally {
      setResetLoading(false)
    }
  }

  const handleCopyResetPassword = async () => {
    if (!resetTempPassword) return
    await navigator.clipboard.writeText(resetTempPassword)
    setResetCopied(true)
    setTimeout(() => setResetCopied(false), 2000)
  }

  const handleToggleSuperAdmin = async () => {
    if (!userId || !user) return
    try {
      await adminApi.updateSuperAdminStatus(userId, !user.is_super_admin)
      toast.success(user.is_super_admin ? 'Super admin access removed' : 'Promoted to super admin')
      setSuperAdminModalOpen(false)
      fetchUser()
    } catch {
      toast.error('Failed to update super admin status')
    }
  }

  const handleArchive = async () => {
    if (!userId) return
    try {
      await adminApi.archiveUser(userId)
      toast.success('User archived')
      fetchUser()
    } catch {
      toast.error('Failed to archive user')
    }
  }

  const handleRestore = async () => {
    if (!userId) return
    try {
      await adminApi.restoreUser(userId)
      toast.success('User restored')
      fetchUser()
    } catch {
      toast.error('Failed to restore user')
    }
  }

  const handleHardDeleteCheck = async () => {
    if (!userId) return
    setHardDeleteChecking(true)
    try {
      const result = await adminApi.hardDeleteCheck(userId)
      setHardDeleteBlockers(result.blockers)
      setHardDeleteModalOpen(true)
    } catch {
      toast.error('Failed to check delete eligibility')
    } finally {
      setHardDeleteChecking(false)
    }
  }

  const handleHardDelete = async () => {
    if (!userId) return
    try {
      await adminApi.hardDeleteUser(userId)
      toast.success('User permanently deleted')
      navigate('/admin/accounts')
    } catch (err: unknown) {
      if (err && typeof err === 'object' && 'response' in err) {
        const axiosErr = err as { response?: { data?: { detail?: string } } }
        toast.error(axiosErr.response?.data?.detail || 'Failed to delete user')
      } else {
        toast.error('Failed to delete user')
      }
    }
  }

  const selectClass = cn(
    'w-full rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground',
    'placeholder:text-muted-foreground focus:outline-hidden focus:border-primary focus:ring-2 focus:ring-primary/20'
  )

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Spinner className="border-t-foreground" />
      </div>
    )
  }

  if (!user) {
    return (
      <EmptyState
        title="User not found"
        description="This user may have been removed or is unavailable."
        action={(
          <Button variant="secondary" onClick={() => navigate('/admin/accounts')}>
            Back to Accounts
          </Button>
        )}
      />
    )
  }

  const fmt = (d: string | null) => d ? new Date(d).toLocaleDateString() : '—'
  const fmtFull = (d: string | null) => d ? new Date(d).toLocaleString() : '—'

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <button
          onClick={() => navigate('/admin/accounts')}
          className="rounded-md border border-border p-2 text-muted-foreground hover:bg-accent hover:text-foreground"
        >
          <ArrowLeft className="h-4 w-4" />
        </button>
        <div className="flex-1">
          <h1 className="text-xl font-heading font-semibold text-foreground">
            {user.full_name || user.email}
          </h1>
          <p className="text-sm text-muted-foreground">{user.email}</p>
        </div>
        <div className="flex items-center gap-2">
          {user.is_super_admin && (
            <StatusBadge variant="warning">
              <Crown className="mr-1 h-3 w-3" /> Super Admin
            </StatusBadge>
          )}
          <StatusBadge variant={user.is_active ? 'success' : 'destructive'}>
            {user.is_active ? 'Active' : 'Inactive'}
          </StatusBadge>
          <StatusBadge variant="default">{user.role}</StatusBadge>
          {user.deleted_at && (
            <StatusBadge variant="warning">Archived</StatusBadge>
          )}
        </div>
      </div>

      {/* Account & Subscription */}
      <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
        <div className="bg-card border border-border rounded-xl p-6">
          <h2 className="mb-4 text-sm font-semibold uppercase tracking-wider text-muted-foreground">
            Account & Subscription
          </h2>
          <dl className="space-y-3">
            {user.account && (
              <>
                <div className="flex justify-between">
                  <dt className="text-sm text-muted-foreground">Account</dt>
                  <dd className="text-sm text-foreground">{user.account.name}</dd>
                </div>
                {user.account.display_code && (
                  <div className="flex justify-between">
                    <dt className="text-sm text-muted-foreground">Display Code</dt>
                    <dd className="text-sm font-mono text-muted-foreground">{user.account.display_code}</dd>
                  </div>
                )}
              </>
            )}
            {user.subscription ? (
              <>
                <div className="flex justify-between">
                  <dt className="text-sm text-muted-foreground">Plan</dt>
                  <dd className="text-sm font-semibold text-foreground">
                    {user.subscription.plan.charAt(0).toUpperCase() + user.subscription.plan.slice(1)}
                  </dd>
                </div>
                <div className="flex justify-between">
                  <dt className="text-sm text-muted-foreground">Status</dt>
                  <dd>
                    <StatusBadge variant={user.subscription.status === 'trialing' ? 'warning' : 'success'}>
                      {user.subscription.status}
                    </StatusBadge>
                  </dd>
                </div>
                {user.subscription.current_period_end && (
                  <div className="flex justify-between">
                    <dt className="text-sm text-muted-foreground">Period End</dt>
                    <dd className="text-sm text-muted-foreground">{fmt(user.subscription.current_period_end)}</dd>
                  </div>
                )}
              </>
            ) : (
              <div className="text-sm text-muted-foreground">No subscription</div>
            )}
            <div className="flex justify-between">
              <dt className="text-sm text-muted-foreground">Joined</dt>
              <dd className="text-sm text-muted-foreground">{fmt(user.created_at)}</dd>
            </div>
          </dl>
        </div>

        {/* Admin Actions */}
        <div className="bg-card border border-border rounded-xl p-6">
          <h2 className="mb-4 text-sm font-semibold uppercase tracking-wider text-muted-foreground">
            Admin Actions
          </h2>
          <div className="space-y-3">
            {user.account && (
              <>
                <button
                  onClick={() => {
                    setSelectedPlan(user.subscription?.plan || 'free')
                    setPlanModalOpen(true)
                  }}
                  className="flex w-full items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
                >
                  <Shield className="h-4 w-4 text-muted-foreground" />
                  Change Plan
                </button>
                <button
                  onClick={() => setTrialModalOpen(true)}
                  className="flex w-full items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
                >
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  {user.subscription?.status === 'trialing' ? 'Extend Trial' : 'Start Trial'}
                </button>
              </>
            )}
            <button
              onClick={() => setSuperAdminModalOpen(true)}
              className={cn(
                'flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left text-sm',
                user.is_super_admin
                  ? 'border-yellow-500/20 text-yellow-400 hover:bg-yellow-500/5'
                  : 'border-purple-500/20 text-purple-400 hover:bg-purple-500/5'
              )}
            >
              <Crown className="h-4 w-4" />
              {user.is_super_admin ? 'Remove Super Admin' : 'Promote to Super Admin'}
            </button>
            <button
              onClick={() => {
                setResetMode('email_link')
                setResetTempPassword(null)
                setResetModalOpen(true)
              }}
              className="flex w-full items-center gap-3 rounded-lg border border-border px-4 py-3 text-left text-sm text-muted-foreground hover:bg-accent hover:text-foreground"
            >
              <KeyRound className="h-4 w-4 text-muted-foreground" />
              Reset Password
            </button>
            <button
              onClick={handleToggleActive}
              className={cn(
                'flex w-full items-center gap-3 rounded-lg border px-4 py-3 text-left text-sm',
                user.is_active
                  ? 'border-red-500/20 text-red-400 hover:bg-red-500/5'
                  : 'border-emerald-500/20 text-emerald-400 hover:bg-emerald-500/5'
              )}
            >
              {user.is_active ? (
                <><UserX className="h-4 w-4" /> Deactivate User</>
              ) : (
                <><UserCheck className="h-4 w-4" /> Activate User</>
              )}
            </button>
            {/* Archive / Restore */}
            {user.deleted_at ? (
              <button
                onClick={handleRestore}
                className="flex w-full items-center gap-3 rounded-lg border border-emerald-500/20 px-4 py-3 text-left text-sm text-emerald-400 hover:bg-emerald-500/5"
              >
                <ArchiveRestore className="h-4 w-4" /> Restore User
              </button>
            ) : (
              <button
                onClick={handleArchive}
                className="flex w-full items-center gap-3 rounded-lg border border-yellow-500/20 px-4 py-3 text-left text-sm text-yellow-400 hover:bg-yellow-500/5"
              >
                <Archive className="h-4 w-4" /> Archive User
              </button>
            )}
            {/* Hard Delete (only if archived) */}
            {user.deleted_at && (
              <button
                onClick={handleHardDeleteCheck}
                disabled={hardDeleteChecking}
                className="flex w-full items-center gap-3 rounded-lg border border-red-500/20 px-4 py-3 text-left text-sm text-red-400 hover:bg-red-500/5 disabled:opacity-50"
              >
                <Trash2 className="h-4 w-4" />
                {hardDeleteChecking ? 'Checking...' : 'Permanently Delete'}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Invite Code Used */}
      {user.invite_code_used && (
        <div className="bg-card border border-border rounded-xl p-6">
          <h2 className="mb-4 text-sm font-semibold uppercase tracking-wider text-muted-foreground">
            <Ticket className="mr-2 inline h-4 w-4" />
            Invite Code Used
          </h2>
          <dl className="grid grid-cols-2 gap-4 md:grid-cols-4">
            <div>
              <dt className="text-xs text-muted-foreground">Code</dt>
              <dd className="mt-1 font-mono text-sm text-muted-foreground">{user.invite_code_used.code}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted-foreground">Plan Assigned</dt>
              <dd className="mt-1 text-sm text-muted-foreground">
                {user.invite_code_used.assigned_plan.charAt(0).toUpperCase() + user.invite_code_used.assigned_plan.slice(1)}
              </dd>
            </div>
            <div>
              <dt className="text-xs text-muted-foreground">Trial Days</dt>
              <dd className="mt-1 text-sm text-muted-foreground">{user.invite_code_used.trial_duration_days ?? '—'}</dd>
            </div>
            <div>
              <dt className="text-xs text-muted-foreground">Created By</dt>
              <dd className="mt-1 text-sm text-muted-foreground">{user.invite_code_used.created_by_email ?? '—'}</dd>
            </div>
          </dl>
        </div>
      )}

      {/* Tabs: Sessions / Audit Logs */}
      <div className="bg-card border border-border rounded-xl">
        <div className="flex border-b border-border">
          <button
            onClick={() => setActiveTab('sessions')}
            className={cn(
              'px-6 py-3 text-sm font-medium',
              activeTab === 'sessions' ? 'border-b-2 border-foreground text-foreground' : 'text-muted-foreground hover:text-foreground'
            )}
          >
            Sessions ({user.total_sessions})
          </button>
          <button
            onClick={() => setActiveTab('audit')}
            className={cn(
              'px-6 py-3 text-sm font-medium',
              activeTab === 'audit' ? 'border-b-2 border-foreground text-foreground' : 'text-muted-foreground hover:text-foreground'
            )}
          >
            Audit Logs ({user.total_audit_logs})
          </button>
        </div>

        <div className="p-6">
          {activeTab === 'sessions' && (
            user.recent_sessions.length > 0 ? (
              <table className="w-full">
                <thead>
                  <tr className="border-b border-border text-left text-xs text-muted-foreground">
                    <th className="pb-2 font-medium">Tree</th>
                    <th className="pb-2 font-medium">Started</th>
                    <th className="pb-2 font-medium">Completed</th>
                    <th className="pb-2 font-medium">Outcome</th>
                  </tr>
                </thead>
                <tbody>
                  {user.recent_sessions.map(s => (
                    <tr key={s.id} className="border-b border-border">
                      <td className="py-3 text-sm text-muted-foreground">{s.tree_name ?? '—'}</td>
                      <td className="py-3 text-sm text-muted-foreground">{fmtFull(s.started_at)}</td>
                      <td className="py-3 text-sm text-muted-foreground">{fmtFull(s.completed_at)}</td>
                      <td className="py-3">
                        {s.outcome ? (
                          <StatusBadge variant={s.outcome === 'resolved' ? 'success' : 'default'}>
                            {s.outcome}
                          </StatusBadge>
                        ) : (
                          <span className="text-sm text-muted-foreground">—</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="py-8 text-center text-sm text-muted-foreground">No sessions yet</div>
            )
          )}

          {activeTab === 'audit' && (
            user.recent_audit_logs.length > 0 ? (
              <table className="w-full">
                <thead>
                  <tr className="border-b border-border text-left text-xs text-muted-foreground">
                    <th className="pb-2 font-medium">Action</th>
                    <th className="pb-2 font-medium">Resource</th>
                    <th className="pb-2 font-medium">Time</th>
                  </tr>
                </thead>
                <tbody>
                  {user.recent_audit_logs.map(a => (
                    <tr key={a.id} className="border-b border-border">
                      <td className="py-3 text-sm text-muted-foreground">{a.action}</td>
                      <td className="py-3 text-sm text-muted-foreground">{a.resource_type ?? '—'}</td>
                      <td className="py-3 text-sm text-muted-foreground">{fmtFull(a.created_at)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            ) : (
              <div className="py-8 text-center text-sm text-muted-foreground">No audit logs yet</div>
            )
          )}
        </div>
      </div>

      {/* Change Plan Modal */}
      <Modal
        isOpen={planModalOpen}
        onClose={() => setPlanModalOpen(false)}
        title="Change Subscription Plan"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setPlanModalOpen(false)}>Cancel</Button>
            <Button onClick={handleChangePlan}>Update Plan</Button>
          </div>
        }
      >
        <div>
          <label className="mb-1 block text-sm font-medium text-foreground">Plan</label>
          <select
            aria-label="Subscription plan"
            value={selectedPlan}
            onChange={(e) => setSelectedPlan(e.target.value)}
            className={selectClass}
          >
            {PLAN_OPTIONS.map(p => (
              <option key={p} value={p}>{p.charAt(0).toUpperCase() + p.slice(1)}</option>
            ))}
          </select>
        </div>
      </Modal>

      {/* Reset Password Modal */}
      <Modal
        isOpen={resetModalOpen && !resetTempPassword}
        onClose={() => setResetModalOpen(false)}
        title="Reset User Password"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setResetModalOpen(false)}>Cancel</Button>
            <Button onClick={handleResetPassword} loading={resetLoading}>
              {resetLoading ? 'Resetting...' : 'Reset Password'}
            </Button>
          </div>
        }
      >
        <div className="space-y-4">
          <p className="text-sm text-muted-foreground">
            Choose how to reset the password for <span className="font-medium text-foreground">{user.full_name || user.email}</span>.
          </p>
          <div className="space-y-2">
            <label className="flex items-start gap-3 rounded-lg border border-border p-3 cursor-pointer hover:bg-accent">
              <input
                type="radio"
                name="reset-mode"
                value="email_link"
                checked={resetMode === 'email_link'}
                onChange={() => setResetMode('email_link')}
                className="mt-0.5"
              />
              <div>
                <div className="text-sm font-medium text-foreground">Send Reset Email</div>
                <div className="text-xs text-muted-foreground">User receives an email with a reset link (30 min expiry)</div>
              </div>
            </label>
            <label className="flex items-start gap-3 rounded-lg border border-border p-3 cursor-pointer hover:bg-accent">
              <input
                type="radio"
                name="reset-mode"
                value="temp_password"
                checked={resetMode === 'temp_password'}
                onChange={() => setResetMode('temp_password')}
                className="mt-0.5"
              />
              <div>
                <div className="text-sm font-medium text-foreground">Generate Temp Password</div>
                <div className="text-xs text-muted-foreground">A temporary password is generated. You share it manually.</div>
              </div>
            </label>
          </div>
        </div>
      </Modal>

      {/* Temp Password Result Modal */}
      <Modal
        isOpen={!!resetTempPassword}
        onClose={() => { setResetTempPassword(null); setResetModalOpen(false) }}
        title="Temporary Password"
        size="sm"
        footer={
          <div className="flex justify-end">
            <Button onClick={() => { setResetTempPassword(null); setResetModalOpen(false) }}>Done</Button>
          </div>
        }
      >
        <div className="space-y-4">
          <div className="rounded-xl border border-yellow-400/20 bg-yellow-400/10 p-3 text-sm text-yellow-400">
            This password will not be shown again. Copy it now.
          </div>
          <div className="flex items-center gap-2">
            <code className="flex-1 rounded-md border border-border bg-card px-3 py-2 text-sm text-foreground font-mono">
              {resetTempPassword}
            </code>
            <button
              onClick={handleCopyResetPassword}
              className="rounded-md border border-border p-2 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
              title="Copy password"
            >
              {resetCopied ? <Check className="h-4 w-4 text-green-400" /> : <Copy className="h-4 w-4" />}
            </button>
          </div>
          <p className="text-xs text-muted-foreground">
            The user will be required to change this password on next login.
          </p>
        </div>
      </Modal>

      {/* Extend Trial Modal */}
      <Modal
        isOpen={trialModalOpen}
        onClose={() => setTrialModalOpen(false)}
        title={user.subscription?.status === 'trialing' ? 'Extend Trial' : 'Start Trial'}
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setTrialModalOpen(false)}>Cancel</Button>
            <Button onClick={handleExtendTrial}>
              {user.subscription?.status === 'trialing' ? 'Extend' : 'Start Trial'}
            </Button>
          </div>
        }
      >
        <div>
          <label className="mb-1 block text-sm font-medium text-foreground">Days to add</label>
          <Input
            type="number"
            value={trialDays}
            onChange={(e) => setTrialDays(e.target.value)}
            min={1}
            max={90}
          />
          <p className="mt-1 text-xs text-muted-foreground">1-90 days. Will convert to trialing status if not already.</p>
        </div>
      </Modal>

      {/* Super Admin Modal */}
      <Modal
        isOpen={superAdminModalOpen}
        onClose={() => setSuperAdminModalOpen(false)}
        title={user.is_super_admin ? 'Remove Super Admin Access' : 'Promote to Super Admin'}
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setSuperAdminModalOpen(false)}>Cancel</Button>
            <Button
              onClick={handleToggleSuperAdmin}
              className={user.is_super_admin ? 'bg-yellow-600 hover:bg-yellow-700 shadow-none' : ''}
            >
              {user.is_super_admin ? 'Remove Access' : 'Promote'}
            </Button>
          </div>
        }
      >
        <div className="space-y-3">
          {user.is_super_admin ? (
            <div className="rounded-xl border border-yellow-400/20 bg-yellow-400/10 p-3 text-sm text-yellow-400">
              This will remove system-wide admin access from <strong>{user.full_name || user.email}</strong>. They will revert to their account role permissions.
            </div>
          ) : (
            <div className="rounded-xl border border-purple-400/20 bg-purple-400/10 p-3 text-sm text-purple-400">
              This will grant <strong>{user.full_name || user.email}</strong> full system-wide admin access, including access to the admin panel and all accounts.
            </div>
          )}
        </div>
      </Modal>

      {/* Hard Delete Modal */}
      <Modal
        isOpen={hardDeleteModalOpen}
        onClose={() => setHardDeleteModalOpen(false)}
        title="Permanently Delete User"
        size="sm"
        footer={
          <div className="flex justify-end gap-3">
            <Button variant="secondary" onClick={() => setHardDeleteModalOpen(false)}>Cancel</Button>
            {hardDeleteBlockers && Object.keys(hardDeleteBlockers).length === 0 && (
              <Button variant="destructive" onClick={handleHardDelete}>
                Delete Permanently
              </Button>
            )}
          </div>
        }
      >
        <div className="space-y-4">
          {hardDeleteBlockers && Object.keys(hardDeleteBlockers).length > 0 ? (
            <>
              <div className="rounded-xl border border-red-400/20 bg-red-400/10 p-3 text-sm text-red-400">
                This user cannot be deleted because they have dependencies:
              </div>
              <ul className="space-y-1 text-sm text-muted-foreground">
                {Object.entries(hardDeleteBlockers).map(([key, count]) => (
                  <li key={key} className="flex justify-between">
                    <span>{key.replace(/_/g, ' ')}</span>
                    <span className="font-mono text-muted-foreground">{count}</span>
                  </li>
                ))}
              </ul>
            </>
          ) : (
            <div className="rounded-xl border border-red-400/20 bg-red-400/10 p-4 text-sm text-red-400">
              <p className="font-medium">This action is irreversible.</p>
              <p className="mt-1">The user <strong>{user?.full_name || user?.email}</strong> and all their technical data (tokens, reset tokens) will be permanently removed.</p>
            </div>
          )}
        </div>
      </Modal>
    </div>
  )
}

export default UserDetailPage
