'use client'

import { useState, useEffect } from 'react'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Table, TableBody, TableCell,
  TableHead, TableHeader, TableRow,
} from '@/components/ui/table'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Search, RefreshCw, Trash2, Users,
  Shield, UserCheck, Building2, User,
  Mail, Phone, ArrowLeft, ArrowRight, X,
} from 'lucide-react'
import { toast } from 'sonner'
import { cn } from '@/lib/utils'
import { useUsers } from '@/contexts/UsersContext'
import { ConfirmDialog } from '@/components/ui/confirm-dialog'
import { UserDialog } from '@/components/users/user-dialog'

// ─── Config ───────────────────────────────────────────────────────────────────

const ROLE_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
  validation_agent: { label: 'Agent validation', color: 'bg-blue-50 text-blue-700',    icon: <Shield    className="h-3 w-3" /> },
  kalale_agent:     { label: 'Agent Kalalé',     color: 'bg-emerald-50 text-emerald-700', icon: <UserCheck className="h-3 w-3" /> },
  company_admin:    { label: 'Admin compagnie',  color: 'bg-rose-50 text-rose-700',    icon: <Building2 className="h-3 w-3" /> },
  company_agent:    { label: 'Agent compagnie',  color: 'bg-amber-50 text-amber-700',  icon: <Building2 className="h-3 w-3" /> },
  ticketing_agent:  { label: 'Guichetier',       color: 'bg-orange-50 text-orange-700',icon: <UserCheck className="h-3 w-3" /> },
  customer:         { label: 'Client',           color: 'bg-gray-50 text-gray-600',    icon: <User      className="h-3 w-3" /> },
}

const PER_PAGE_OPTIONS = [10, 25, 50]

const HAS_COMPANY_ROLE = new Set(['company_agent', 'ticketing_agent', 'company_admin'])

// ─── Sub-components ───────────────────────────────────────────────────────────

function RoleBadge({ role }: { role: string }) {
  const cfg = ROLE_MAP[role]
  return (
    <span className={cn(
      'inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-medium border border-transparent',
      cfg?.color ?? 'bg-gray-50 text-gray-600'
    )}>
      {cfg?.icon ?? <User className="h-3 w-3" />}
      {cfg?.label ?? role}
    </span>
  )
}

function Avatar({ firstName, lastName }: { firstName?: string; lastName?: string }) {
  const initials = ((firstName?.[0] ?? '') + (lastName?.[0] ?? '')).toUpperCase() || '?'
  return (
    <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-[11px] font-semibold text-gray-600 flex-shrink-0">
      {initials}
    </div>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function UsersPage() {
  const { users, meta, loading, error, fetchUsers, removeUser } = useUsers()

  const [q,           setQ]           = useState('')
  const [role,        setRole]        = useState('')
  const [page,        setPage]        = useState(1)
  const [perPage,     setPerPage]     = useState(25)
  const [deleteId,    setDeleteId]    = useState<number | null>(null)

  useEffect(() => {
    fetchUsers({ page, perPage, q, role })
  }, [fetchUsers, page, perPage, q, role])

  const refresh = () => fetchUsers({ page, perPage, q, role })

  const handleDelete = async () => {
    if (!deleteId) return
    try {
      await removeUser(deleteId)
      toast.success('Utilisateur supprimé')
      if (users.length === 1 && page > 1) setPage(p => p - 1)
    } catch {
      toast.error('Erreur lors de la suppression')
    } finally {
      setDeleteId(null)
    }
  }

  const from = (page - 1) * perPage + 1
  const to   = Math.min(page * perPage, meta.total)

  return (
    <div className="space-y-5">

      {/* ── Header ── */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-gray-900">Utilisateurs</h1>
          <p className="text-sm text-gray-400 mt-0.5">Tous les comptes du système</p>
        </div>
        <UserDialog onSuccess={refresh} />
      </div>

      {/* ── Main card ── */}
      <Card className="border border-gray-200 shadow-none bg-white overflow-hidden">

        {/* Toolbar */}
        <CardHeader className="px-6 py-4 border-b border-gray-100">
          <div className="flex flex-col gap-3">
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
              <CardTitle className="text-sm font-semibold text-gray-800 flex items-center gap-2">
                <Users className="w-4 h-4 text-rose-500" />
                {meta.total > 0 ? `${meta.total} utilisateur${meta.total > 1 ? 's' : ''}` : 'Utilisateurs'}
                {role && (
                  <span className="text-[11px] font-normal text-gray-400">
                    · {ROLE_MAP[role]?.label}
                  </span>
                )}
              </CardTitle>

              <div className="flex items-center gap-2">
                <div className="relative">
                  <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400 pointer-events-none" />
                  <Input
                    placeholder="Rechercher…"
                    value={q}
                    onChange={e => { setQ(e.target.value); setPage(1) }}
                    className="pl-8 h-8 text-xs border-gray-200 w-44"
                  />
                  {q && (
                    <button
                      onClick={() => { setQ(''); setPage(1) }}
                      className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600"
                    >
                      <X className="w-3 h-3" />
                    </button>
                  )}
                </div>

                <select
                  value={perPage}
                  onChange={e => { setPerPage(Number(e.target.value)); setPage(1) }}
                  className="h-8 border border-gray-200 rounded-md px-2 text-xs text-gray-600 bg-white focus:outline-none focus:border-gray-300"
                >
                  {PER_PAGE_OPTIONS.map(n => (
                    <option key={n} value={n}>{n} / page</option>
                  ))}
                </select>

                <button
                  onClick={refresh}
                  disabled={loading}
                  className="p-1.5 rounded-md hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors"
                  title="Actualiser"
                >
                  <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
                </button>
              </div>
            </div>

            {/* Role filter pills */}
            <div className="flex flex-wrap items-center gap-1.5">
              <button
                onClick={() => { setRole(''); setPage(1) }}
                className={cn(
                  'px-2.5 py-1 rounded-md text-[11px] font-medium border transition-all',
                  !role
                    ? 'bg-gray-900 text-white border-gray-900'
                    : 'bg-white text-gray-500 border-gray-200 hover:border-gray-300 hover:text-gray-700'
                )}
              >
                Tous
              </button>
              {Object.entries(ROLE_MAP).map(([r, cfg]) => (
                <button
                  key={r}
                  onClick={() => { setRole(role === r ? '' : r); setPage(1) }}
                  className={cn(
                    'inline-flex items-center gap-1 px-2.5 py-1 rounded-md text-[11px] font-medium border transition-all',
                    role === r
                      ? `${cfg.color} border-current`
                      : 'bg-white text-gray-500 border-gray-200 hover:border-gray-300 hover:text-gray-700'
                  )}
                >
                  {cfg.icon}
                  {cfg.label}
                </button>
              ))}
            </div>
          </div>
        </CardHeader>

        <CardContent className="p-0">
          {error ? (
            <div className="flex items-center gap-2 m-6 text-sm text-rose-600 bg-rose-50 border border-rose-200 rounded-lg px-4 py-3">
              <X className="w-4 h-4 flex-shrink-0" />
              {error}
            </div>
          ) : (
            <>
              {/* Table — desktop */}
              <div className="hidden sm:block overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gray-50 hover:bg-gray-50 border-b border-gray-100">
                      <TableHead className="pl-6 text-[11px] font-semibold uppercase tracking-wider text-gray-400">Utilisateur</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Contact</TableHead>
                      <TableHead className="text-[11px] font-semibold uppercase tracking-wider text-gray-400">Rôle</TableHead>
                      <TableHead className="pr-6 text-right text-[11px] font-semibold uppercase tracking-wider text-gray-400">Actions</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {loading && users.length === 0 ? (
                      Array.from({ length: 6 }).map((_, i) => (
                        <TableRow key={i} className="border-b border-gray-100">
                          <TableCell className="pl-6">
                            <div className="flex items-center gap-3">
                              <Skeleton className="w-8 h-8 rounded-full flex-shrink-0" />
                              <div className="space-y-1.5">
                                <Skeleton className="h-3.5 w-28" />
                                <Skeleton className="h-3 w-10" />
                              </div>
                            </div>
                          </TableCell>
                          <TableCell>
                            <div className="space-y-1.5">
                              <Skeleton className="h-3 w-36" />
                              <Skeleton className="h-3 w-24" />
                            </div>
                          </TableCell>
                          <TableCell><Skeleton className="h-5 w-28 rounded-md" /></TableCell>
                          <TableCell className="pr-6 text-right"><Skeleton className="h-7 w-16 ml-auto" /></TableCell>
                        </TableRow>
                      ))
                    ) : users.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={4} className="py-14 text-center text-gray-400">
                          <Users className="w-7 h-7 mx-auto mb-2 opacity-30" />
                          <p className="text-sm">
                            {q ? `Aucun résultat pour "${q}"` : 'Aucun utilisateur trouvé'}
                          </p>
                        </TableCell>
                      </TableRow>
                    ) : users.map(user => (
                      <TableRow key={user.id} className="border-b border-gray-100 hover:bg-gray-50 transition-colors">
                        <TableCell className="pl-6">
                          <div className="flex items-center gap-3">
                            <Avatar firstName={user.firstName} lastName={user.lastName} />
                            <div className="min-w-0">
                              <p className="text-sm font-medium text-gray-900 truncate">
                                {`${user.firstName ?? ''} ${user.lastName ?? ''}`.trim() || '—'}
                              </p>
                              <p className="text-[11px] text-gray-400">#{user.id}</p>
                            </div>
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="space-y-0.5">
                            <p className="text-xs text-gray-600 flex items-center gap-1.5">
                              <Mail className="w-3 h-3 text-gray-400 flex-shrink-0" />
                              <span className="truncate max-w-[200px]">{user.email}</span>
                            </p>
                            {user.phone && (
                              <p className="text-xs text-gray-400 flex items-center gap-1.5">
                                <Phone className="w-3 h-3 flex-shrink-0" />
                                {user.phone}
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell>
                          <div className="space-y-1">
                            <RoleBadge role={user.role} />
                            {HAS_COMPANY_ROLE.has(user.role) && user.companyName && (
                              <p className="text-[11px] text-gray-400 flex items-center gap-1">
                                <Building2 className="w-3 h-3" />
                                {user.companyName}
                              </p>
                            )}
                          </div>
                        </TableCell>
                        <TableCell className="pr-6">
                          <div className="flex justify-end gap-1">
                            <UserDialog user={user} onSuccess={refresh} />
                            <button
                              onClick={() => setDeleteId(user.id)}
                              className="p-1.5 rounded-md hover:bg-rose-50 text-gray-400 hover:text-rose-600 transition-colors"
                              title="Supprimer"
                            >
                              <Trash2 className="w-3.5 h-3.5" />
                            </button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>

              {/* List — mobile */}
              <div className="sm:hidden divide-y divide-gray-100">
                {loading && users.length === 0 ? (
                  Array.from({ length: 4 }).map((_, i) => (
                    <div key={i} className="flex items-center gap-3 px-5 py-3.5">
                      <Skeleton className="w-9 h-9 rounded-full flex-shrink-0" />
                      <div className="flex-1 space-y-1.5">
                        <Skeleton className="h-3.5 w-28" />
                        <Skeleton className="h-3 w-36" />
                      </div>
                    </div>
                  ))
                ) : users.length === 0 ? (
                  <div className="py-12 text-center text-gray-400">
                    <Users className="w-7 h-7 mx-auto mb-2 opacity-30" />
                    <p className="text-sm">{q ? `Aucun résultat pour "${q}"` : 'Aucun utilisateur'}</p>
                  </div>
                ) : users.map(user => (
                  <div key={user.id} className="px-5 py-3.5">
                    <div className="flex items-center justify-between gap-3">
                      <div className="flex items-center gap-3 min-w-0">
                        <Avatar firstName={user.firstName} lastName={user.lastName} />
                        <div className="min-w-0">
                          <p className="text-sm font-medium text-gray-900 truncate">
                            {`${user.firstName ?? ''} ${user.lastName ?? ''}`.trim() || '—'}
                          </p>
                          <p className="text-[11px] text-gray-400 truncate">{user.email}</p>
                        </div>
                      </div>
                      <div className="flex items-center gap-1 flex-shrink-0">
                        <RoleBadge role={user.role} />
                      </div>
                    </div>
                    <div className="flex justify-end gap-1 mt-1.5">
                      <UserDialog user={user} onSuccess={refresh} />
                      <button
                        onClick={() => setDeleteId(user.id)}
                        className="p-2 rounded-md hover:bg-rose-50 text-gray-400 hover:text-rose-600 transition-colors"
                      >
                        <Trash2 className="w-4 h-4" />
                      </button>
                    </div>
                  </div>
                ))}
              </div>

              {/* Pagination */}
              {meta.total > 0 && (
                <div className="flex items-center justify-between px-6 py-3 border-t border-gray-100">
                  <p className="text-xs text-gray-400">{from}–{to} sur {meta.total}</p>
                  <div className="flex items-center gap-1.5">
                    <Button
                      variant="outline" size="sm"
                      disabled={page === 1 || loading}
                      onClick={() => setPage(p => p - 1)}
                      className="h-7 px-2.5 text-xs border-gray-200 gap-1"
                    >
                      <ArrowLeft className="w-3 h-3" />
                      Précédent
                    </Button>
                    <Button
                      variant="outline" size="sm"
                      disabled={page === meta.lastPage || loading}
                      onClick={() => setPage(p => p + 1)}
                      className="h-7 px-2.5 text-xs border-gray-200 gap-1"
                    >
                      Suivant
                      <ArrowRight className="w-3 h-3" />
                    </Button>
                  </div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      <ConfirmDialog
        title="Supprimer l'utilisateur ?"
        description="Cette action est irréversible. L'utilisateur sera définitivement supprimé du système."
        open={!!deleteId}
        onOpenChange={open => { if (!open) setDeleteId(null) }}
        onConfirm={handleDelete}
      />
    </div>
  )
}
