<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUsersStore } from '@/stores/users'
import { getAllCellsWithCounts, getMembers, saveCell, deleteCell, addMember, removeMember, createCellId, type CellRecord, type CellMemberRecord } from '@/services/cells-db'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  IconExclamationCircle,
  IconUsers,
  IconPlus,
  IconTrash,
  IconUserPlus,
  IconUserMinus,
  IconBuildingFactory,
  IconArrowUp,
  IconArrowDown,
  IconGripVertical,
} from '@tabler/icons-vue'

const { t } = useI18n()
const store = useUsersStore()

// ─── Role hierarchy ──────────────────────────────────────
const ROLE_HIERARCHY = ['pm', 'ba', 'tl', 'dev', 'qa', 'asistente'] as const
type CellRole = (typeof ROLE_HIERARCHY)[number]

const ROLE_LABELS: Record<CellRole, string> = {
  pm: 'PM',
  ba: 'BA',
  tl: 'TL',
  dev: 'Dev',
  qa: 'QA',
  asistente: 'Asistente',
}

const ROLE_COLORS: Record<CellRole, string> = {
  pm: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
  ba: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
  tl: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
  dev: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
  qa: 'bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400',
  asistente: 'bg-sky-100 text-sky-700 dark:bg-sky-900/30 dark:text-sky-400',
}

function roleOrder(role: string): number {
  const idx = ROLE_HIERARCHY.indexOf(role.toLowerCase() as CellRole)
  return idx >= 0 ? idx : 99
}

function roleLabel(role: string): string {
  return ROLE_LABELS[role.toLowerCase() as CellRole] || role
}

function roleColor(role: string): string {
  return ROLE_COLORS[role.toLowerCase() as CellRole] || 'bg-muted text-muted-foreground'
}

// ─── Cells ───────────────────────────────────────────────
const cells = ref<(CellRecord & { memberCount: number })[]>([])
const expandedCell = ref<string | null>(null)
const cellMembers = ref<Record<string, CellMemberRecord[]>>({})
const showNewCell = ref(false)
const newCellName = ref('')
const newCellDesc = ref('')
const newCellType = ref<'normal' | 'transversal'>('normal')

// Add member
const addingToCell = ref<string | null>(null)
const selectedUserId = ref<number | null>(null)
const selectedRole = ref<CellRole>('dev')

async function loadCells() {
  cells.value = await getAllCellsWithCounts()
  for (const c of cells.value) {
    loadMembers(c.id)
  }
}

async function loadMembers(cellId: string) {
  const members = await getMembers(cellId)
  members.sort((a, b) => roleOrder(a.roleInCell) - roleOrder(b.roleInCell))
  cellMembers.value[cellId] = members
}

function toggleCell(cellId: string) {
  if (expandedCell.value === cellId) {
    expandedCell.value = null
  } else {
    expandedCell.value = cellId
    loadMembers(cellId)
  }
}

async function createCell() {
  if (!newCellName.value.trim()) return
  await saveCell({
    id: createCellId(),
    name: newCellName.value.trim(),
    description: newCellDesc.value.trim(),
    type: newCellType.value,
    createdAt: new Date().toISOString(),
  })
  newCellName.value = ''
  newCellDesc.value = ''
  newCellType.value = 'normal'
  showNewCell.value = false
  await loadCells()
}

async function removeCell(id: string) {
  await deleteCell(id)
  if (expandedCell.value === id) expandedCell.value = null
  await loadCells()
}

async function addUserToCell(cellId: string) {
  if (!selectedUserId.value) return
  await addMember({ cellId, userId: selectedUserId.value, roleInCell: selectedRole.value, addedAt: new Date().toISOString() })
  selectedUserId.value = null
  selectedRole.value = 'dev'
  addingToCell.value = null
  await loadMembers(cellId)
  await loadCells()
}

function startAddMember(cellId: string) {
  selectedUserId.value = null
  selectedRole.value = 'dev'
  addingToCell.value = cellId
}

async function removeUserFromCell(cellId: string, userId: number) {
  await removeMember(cellId, userId)
  await loadMembers(cellId)
  await loadCells()
}

function userCells(userId: number) {
  return cells.value.filter(c => (cellMembers.value[c.id] || []).some((m: any) => m.userId === userId))
}

function userName(id: number): string {
  return store.users.find(u => u.id === id)?.full_name || `Usuario ${id}`
}

function sortedMembers(members: CellMemberRecord[]) {
  return [...members].sort((a, b) => roleOrder(a.roleInCell) - roleOrder(b.roleInCell))
}

// ─── Table ───────────────────────────────────────────────
const searchQuery = ref('')
const currentPage = ref(1)
const filterRole = ref('__all')
const filterProject = ref('__all')
const PAGE_SIZE = 15

const uniqueRoles = computed(() => {
  const roles = new Set(store.users.map(u => u.role).filter(Boolean))
  return Array.from(roles).sort() as string[]
})

const uniqueProjects = computed(() => {
  const projs = new Set<string>()
  store.users.forEach(u => u.projects.forEach(p => projs.add(p)))
  return Array.from(projs).sort()
})

const filteredUsers = computed(() => {
  let list = store.users
  const q = searchQuery.value.toLowerCase().trim()
  if (q) {
    list = list.filter(u =>
      u.full_name?.toLowerCase().includes(q) ||
      u.email?.toLowerCase().includes(q) ||
      u.role?.toLowerCase().includes(q) ||
      u.cell?.toLowerCase().includes(q)
    )
  }
  if (filterRole.value && filterRole.value !== '__all') {
    list = list.filter(u => u.role === filterRole.value)
  }
  if (filterProject.value && filterProject.value !== '__all') {
    list = list.filter(u => u.projects.includes(filterProject.value))
  }
  return list
})

const totalPages = computed(() => Math.ceil(filteredUsers.value.length / PAGE_SIZE))

const paginatedUsers = computed(() => {
  const start = (currentPage.value - 1) * PAGE_SIZE
  return filteredUsers.value.slice(start, start + PAGE_SIZE)
})

function goToPage(p: number) {
  currentPage.value = Math.max(1, Math.min(p, totalPages.value))
}

const pageNumbers = computed(() => {
  const total = totalPages.value
  const curr = currentPage.value
  if (total <= 5) return Array.from({ length: total }, (_, i) => i + 1)
  if (curr <= 3) return [1, 2, 3, 4, "...", total]
  if (curr >= total - 2) return [1, "...", total - 3, total - 2, total - 1, total]
  return [1, "...", curr - 1, curr, curr + 1, "...", total]
})

function initials(u: { first_name?: string; last_name?: string }) {
  return `${(u.first_name || '')[0] || ''}${(u.last_name || '')[0] || ''}`
}

onMounted(() => {
  store.fetchAll()
  loadCells()
})
</script>

<template>
  <div class="flex flex-col gap-6 px-4 lg:px-6">
    <!-- Header -->
    <div class="flex items-center justify-between">
      <div>
        <h2 class="text-2xl font-bold tracking-tight">{{ t('users.teamTitle') }}</h2>
        <p class="text-sm text-muted-foreground">{{ store.users.length }} usuarios · {{ store.employees.length }} asignaciones · {{ cells.length }} células</p>
      </div>
      <Button size="sm" @click="showNewCell = !showNewCell">
        <IconPlus class="size-4 mr-1" />
        Nueva célula
      </Button>
    </div>

    <!-- New cell form -->
    <Card v-if="showNewCell" class="border-dashed">
      <CardContent class="p-4 space-y-3">
        <Input v-model="newCellName" placeholder="Nombre de la célula" />
        <Input v-model="newCellDesc" placeholder="Descripción (opcional)" />
        <div class="flex items-center gap-3">
          <Select v-model="newCellType">
            <SelectTrigger class="w-40"><SelectValue /></SelectTrigger>
            <SelectContent>
              <SelectItem value="normal">Normal</SelectItem>
              <SelectItem value="transversal">Transversal</SelectItem>
            </SelectContent>
          </Select>
          <Button size="sm" @click="createCell" :disabled="!newCellName.trim()">Crear</Button>
          <Button size="sm" variant="outline" @click="showNewCell = false">Cancelar</Button>
        </div>
      </CardContent>
    </Card>

    <!-- Loading -->
    <template v-if="store.loading && cells.length === 0">
      <div class="grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3">
        <Skeleton v-for="i in 3" :key="i" class="h-28 rounded-xl" />
      </div>
    </template>

    <!-- Error -->
    <template v-else-if="store.error && cells.length === 0">
      <div class="flex flex-col items-center gap-3 py-12">
        <IconExclamationCircle class="size-10 text-destructive" />
        <p class="text-sm text-muted-foreground">{{ store.error }}</p>
        <Button variant="outline" @click="store.fetchAll()">{{ t('common.retry') }}</Button>
      </div>
    </template>

    <!-- Cell cards -->
    <div v-if="cells.length > 0" class="grid grid-cols-1 gap-3 @xl:grid-cols-2 @3xl:grid-cols-3">
      <Card
        v-for="c in cells"
        :key="c.id"
        class="cursor-pointer transition-colors hover:border-primary/40"
        :class="expandedCell === c.id ? 'border-primary' : ''"
        @click="toggleCell(c.id)"
      >
        <CardHeader class="p-4 pb-2 flex flex-row items-start justify-between">
          <div class="space-y-1">
            <CardTitle class="text-sm font-medium flex items-center gap-2">
              <IconBuildingFactory v-if="c.type === 'transversal'" class="size-4 text-amber-500" />
              <IconUsers v-else class="size-4 text-muted-foreground" />
              {{ c.name }}
            </CardTitle>
            <p v-if="c.description" class="text-xs text-muted-foreground">{{ c.description }}</p>
          </div>
          <div class="flex items-center gap-2 shrink-0">
            <Badge variant="outline" class="text-[10px]" :class="c.type === 'transversal' ? 'border-amber-300 text-amber-600' : ''">
              {{ c.type === 'transversal' ? 'Transversal' : 'Normal' }}
            </Badge>
            <span class="text-xs text-muted-foreground">{{ c.memberCount }}</span>
          </div>
        </CardHeader>
        <!-- Expanded members -->
        <CardContent v-if="expandedCell === c.id" class="p-4 pt-2 space-y-2" @click.stop>
          <div v-if="cellMembers[c.id]?.length" class="space-y-1">
            <div v-for="m in sortedMembers(cellMembers[c.id])" :key="m.userId" class="group flex items-center justify-between rounded-md px-2 py-1.5 text-sm hover:bg-muted/50 transition-colors">
              <div class="flex items-center gap-2 min-w-0">
                <span class="truncate">{{ userName(m.userId) }}</span>
                <span class="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium shrink-0" :class="roleColor(m.roleInCell)">
                  {{ roleLabel(m.roleInCell) }}
                </span>
              </div>
              <Button variant="ghost" size="sm" class="size-6 opacity-0 group-hover:opacity-100 transition-opacity shrink-0" @click="removeUserFromCell(c.id, m.userId)">
                <IconUserMinus class="size-3" />
              </Button>
            </div>
          </div>
          <p v-else class="text-xs text-muted-foreground italic">Sin miembros</p>
          <div v-if="addingToCell === c.id" class="space-y-2 pt-1">
            <div class="flex gap-2">
              <Select v-model="selectedUserId">
                <SelectTrigger class="flex-1 h-8 text-xs"><SelectValue placeholder="Seleccionar usuario..." /></SelectTrigger>
                <SelectContent>
                  <SelectItem v-for="u in store.users" :key="u.id" :value="u.id" class="text-xs">{{ u.full_name }}</SelectItem>
                </SelectContent>
              </Select>
              <Select v-model="selectedRole">
                <SelectTrigger class="w-28 h-8 text-xs"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem v-for="role in ROLE_HIERARCHY" :key="role" :value="role" class="text-xs">
                    {{ ROLE_LABELS[role] }}
                  </SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div class="flex gap-2">
              <Button size="sm" class="h-8 text-xs flex-1" :disabled="!selectedUserId" @click="addUserToCell(c.id)">
                <IconUserPlus class="size-3 mr-1" /> Añadir
              </Button>
              <Button size="sm" variant="outline" class="h-8 text-xs" @click="addingToCell = null">Cancelar</Button>
            </div>
          </div>
          <div class="flex gap-1 pt-1">
            <Button v-if="addingToCell !== c.id" size="sm" variant="outline" class="h-7 text-xs" @click="startAddMember(c.id)">
              <IconUserPlus class="size-3 mr-1" /> Añadir miembro
            </Button>
            <Button size="sm" variant="ghost" class="h-7 text-xs text-destructive" @click="removeCell(c.id)">
              <IconTrash class="size-3 mr-1" /> Eliminar
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>

    <!-- Empty cells -->
    <div v-if="!store.loading && cells.length === 0" class="text-center py-8 text-sm text-muted-foreground">
      <IconUsers class="size-10 mx-auto mb-2 text-muted-foreground/50" />
      <p>Sin células creadas. Creá una para organizar tu equipo.</p>
    </div>

    <!-- Users table -->
    <Card>
      <CardHeader class="pb-3 flex flex-col @md:flex-row items-start @md:items-center justify-between gap-3">
        <CardTitle class="text-sm font-medium">{{ t('users.allUsers') }} ({{ store.users.length }})</CardTitle>
        <div class="flex items-center gap-2 flex-wrap">
          <Select v-model="filterRole">
            <SelectTrigger class="h-8 w-[140px] text-xs"><SelectValue :placeholder="t('users.role')" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="__all" class="text-xs">{{ t('users.allRoles') }}</SelectItem>
              <SelectItem v-for="r in uniqueRoles" :key="r" :value="r" class="text-xs">{{ r }}</SelectItem>
            </SelectContent>
          </Select>
          <Select v-model="filterProject">
            <SelectTrigger class="h-8 w-[180px] text-xs"><SelectValue :placeholder="t('users.assignments')" /></SelectTrigger>
            <SelectContent>
              <SelectItem value="__all" class="text-xs">{{ t('users.allProjects') }}</SelectItem>
              <SelectItem v-for="p in uniqueProjects" :key="p" :value="p" class="text-xs">{{ p }}</SelectItem>
            </SelectContent>
          </Select>
          <div class="relative w-48">
            <Input v-model="searchQuery" placeholder="Buscar..." class="pl-8 h-8 text-sm" @input="currentPage = 1" />
          </div>
        </div>
      </CardHeader>
      <CardContent class="p-0">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead class="w-[60px]">ID</TableHead>
              <TableHead>{{ t('users.name') }}</TableHead>
              <TableHead>{{ t('users.email') }}</TableHead>
              <TableHead class="w-[80px]">{{ t('users.role') }}</TableHead>
              <TableHead class="w-[100px]">Célula</TableHead>
              <TableHead class="w-[70px] text-right">{{ t('users.projects') }}</TableHead>
              <TableHead>{{ t('users.assignments') }}</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            <TableRow v-for="user in paginatedUsers" :key="user.id">
              <TableCell class="text-xs font-mono text-muted-foreground">{{ user.id }}</TableCell>
              <TableCell>
                <div class="flex items-center gap-2">
                  <div class="flex items-center justify-center size-7 rounded-full bg-primary/10 text-primary text-xs font-semibold shrink-0">{{ initials(user) }}</div>
                  <span class="font-medium text-sm">{{ user.full_name }}</span>
                </div>
              </TableCell>
              <TableCell class="text-sm text-muted-foreground">{{ user.email }}</TableCell>
              <TableCell>
                <span v-if="user.role" class="inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium bg-muted">{{ user.role }}</span>
                <span v-else class="text-muted-foreground text-sm">—</span>
              </TableCell>
              <TableCell class="text-sm text-muted-foreground">
                <template v-if="userCells(user.id).length > 0">
                  <span v-for="c in userCells(user.id)" :key="c.id" class="inline-flex rounded-full bg-muted px-2 py-0.5 text-[10px] mr-1">{{ c.name }}</span>
                </template>
                <span v-else>—</span>
              </TableCell>
              <TableCell class="text-sm text-right font-semibold">{{ user.projects_count || '—' }}</TableCell>
              <TableCell>
                <div class="flex flex-wrap gap-1">
                  <span v-for="p in user.projects.slice(0, 2)" :key="p" class="inline-flex rounded-full bg-muted px-2 py-0.5 text-[10px]">{{ p }}</span>
                  <span v-if="user.projects.length > 2" class="text-[10px] text-muted-foreground">+{{ user.projects.length - 2 }}</span>
                  <span v-if="!user.projects.length" class="text-muted-foreground text-sm">—</span>
                </div>
              </TableCell>
            </TableRow>
          </TableBody>
        </Table>
      </CardContent>
      <div v-if="totalPages > 1" class="flex items-center justify-between px-4 py-3 border-t text-sm">
        <span class="text-muted-foreground text-xs">{{ filteredUsers.length }} usuarios · Página {{ currentPage }} de {{ totalPages }}</span>
        <div class="flex items-center gap-1">
          <a href="#" class="inline-flex items-center justify-center size-7 rounded border text-xs hover:bg-muted" :class="currentPage <= 1 ? 'opacity-30 pointer-events-none' : ''" @click.prevent="goToPage(currentPage - 1)">‹</a>
          <a href="#" v-for="p in pageNumbers" :key="p" class="inline-flex items-center justify-center size-7 rounded border text-xs" :class="p === currentPage ? 'bg-primary text-primary-foreground' : 'hover:bg-muted'" @click.prevent="typeof p === 'number' && goToPage(p)">{{ p }}</a>
          <a href="#" class="inline-flex items-center justify-center size-7 rounded border text-xs hover:bg-muted" :class="currentPage >= totalPages ? 'opacity-30 pointer-events-none' : ''" @click.prevent="goToPage(currentPage + 1)">›</a>
        </div>
      </div>
    </Card>
  </div>
</template>
