<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue"
import { useI18n } from "vue-i18n"
import { useProjectsStore } from "@/stores/projects"
import { useUsersStore, type AlphaUser } from "@/stores/users"
import { storage } from "@/services/storage"
import { IconFolder, IconExclamationCircle, IconUsers, IconUserPlus, IconX, IconSearch } from "@tabler/icons-vue"
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Skeleton } from "@/components/ui/skeleton"
import { Button } from "@/components/ui/button"
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogTrigger,
} from "@/components/ui/dialog"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"

const { t } = useI18n()
const projects = useProjectsStore()
const usersStore = useUsersStore()

// ─── Description modal ───────────────────────
const descProject = ref<{ id: number; name: string; description?: string } | null>(null)
const descOpen = ref(false)

function openDescription(p: { id: number; initiative_name?: string; name?: string; description?: string }) {
  descProject.value = {
    id: p.id,
    name: p.initiative_name || p.name || t('projects.unnamedFallback', { id: p.id }),
    description: p.description,
  }
  descOpen.value = true
}

function getInitials(name: string): string {
  return name
    .split(' ')
    .map(w => w[0])
    .filter(Boolean)
    .slice(0, 2)
    .join('')
    .toUpperCase()
}

// ─── Per-project team members ───────────────
const teamByProject = ref<Map<number, number[]>>(new Map())
const teamInitialized = ref(false)
const teamDialogProjectId = ref<number | null>(null)
const teamDialogOpen = ref(false)
const pendingTeam = ref<Set<number>>(new Set())
const teamSearch = ref('')

const filteredUsers = computed(() => {
  const q = teamSearch.value.toLowerCase().trim()
  if (!q) return usersStore.activeUsers
  return usersStore.activeUsers.filter(u =>
    (u.full_name || '').toLowerCase().includes(q) ||
    (u.email || '').toLowerCase().includes(q) ||
    (u.role || '').toLowerCase().includes(q) ||
    (u.cell || '').toLowerCase().includes(q)
  )
})

const storageKey = (projectId: number) => `project_team_${projectId}`

async function loadTeam(projectId: number): Promise<number[]> {
  const saved = storage.getJSON<number[]>(storageKey(projectId))
  if (saved) return saved
  return getDefaultTeam(projectId)
}

function getDefaultTeam(projectId: number): number[] {
  const p = projects.projects.find(pr => pr.id === projectId)
  if (!p) return []
  const name = p.initiative_name || p.name || ''
  if (!name) return []
  const devs = usersStore.devsByProject.get(name)
  return devs ? devs.map(u => u.id) : []
}

async function loadAllTeams() {
  const map = new Map<number, number[]>()
  for (const p of projects.projects) {
    const ids = await loadTeam(p.id)
    map.set(p.id, ids)
  }
  teamByProject.value = map
}

watch(
  [() => projects.projects.length, () => usersStore.users.length],
  async ([pLen, uLen]) => {
    if (pLen > 0 && uLen > 0 && !teamInitialized.value) {
      teamInitialized.value = true
      await loadAllTeams()
    }
  },
  { immediate: true }
)

function getTeamMembers(projectId: number): AlphaUser[] {
  const ids = teamByProject.value.get(projectId) ?? []
  return ids.map(id => usersStore.users.find(u => u.id === id)).filter(Boolean) as AlphaUser[]
}

function openTeamDialog(projectId: number) {
  teamDialogProjectId.value = projectId
  const current = teamByProject.value.get(projectId) ?? getDefaultTeam(projectId)
  pendingTeam.value = new Set(current)
  teamDialogOpen.value = true
}

function toggleTeamMember(userId: number) {
  if (pendingTeam.value.has(userId)) {
    pendingTeam.value.delete(userId)
  } else {
    pendingTeam.value.add(userId)
  }
}

async function saveTeam() {
  const pid = teamDialogProjectId.value
  if (pid === null) return
  const ids = Array.from(pendingTeam.value)
  await storage.setJSON(storageKey(pid), ids)
  teamByProject.value.set(pid, ids)
  teamDialogOpen.value = false
}

function removeTeamMember(projectId: number, userId: number) {
  const ids = teamByProject.value.get(projectId) ?? []
  const filtered = ids.filter(id => id !== userId)
  teamByProject.value.set(projectId, filtered)
  storage.setJSON(storageKey(projectId), filtered)
}

// ─── Status helpers ─────────────────────────
function getStatusVariant(status?: string) {
  const s = String(status ?? '').toLowerCase()
  if (s === 'true' || ['active', 'completado', 'done', 'completed'].includes(s)) return 'default'
  if (s === 'false' || ['inactive', 'paused', 'cancelled'].includes(s)) return 'secondary'
  return 'outline'
}

function getStatusLabel(status?: string) {
  const s = String(status ?? '').toLowerCase()
  if (s === 'true' || s === 'active') return t('status.active')
  if (s === 'false' || s === 'inactive') return t('status.inactive')
  return s || '—'
}

const emit = defineEmits<{
  'select-project': [id: number]
}>()

onMounted(async () => {
  await projects.fetchProjects()
  usersStore.fetchAll()
})

</script>

<template>
  <div class="flex flex-col gap-6 px-4 lg:px-6">
    <div class="flex items-center justify-between">
      <div>
        <h2 class="text-2xl font-bold tracking-tight">{{ t('projects.title') }}</h2>
        <p class="text-muted-foreground">
          {{ t('projects.subtitle') }}
        </p>
      </div>
      <Badge variant="outline" class="text-sm">
        {{ t('projects.countLabel', { count: projects.count }) }}
      </Badge>
    </div>

    <!-- Loading -->
    <div v-if="projects.loading" class="grid grid-cols-1 gap-4 @lg:grid-cols-2 @3xl:grid-cols-3">
      <Card v-for="i in 6" :key="i">
        <CardHeader>
          <Skeleton class="h-5 w-3/4" />
          <Skeleton class="h-4 w-1/2" />
        </CardHeader>
      </Card>
    </div>

    <!-- Error -->
    <div v-else-if="projects.error" class="flex flex-col items-center gap-3 py-12 text-center">
      <IconExclamationCircle class="size-10 text-destructive" />
      <p class="text-lg font-medium">{{ t('projects.loadError') }}</p>
      <p class="text-sm text-muted-foreground">{{ projects.error }}</p>
      <button
        class="rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90"
        @click="projects.fetchProjects()"
      >
        {{ t('common.retry') }}
      </button>
    </div>

    <!-- Empty -->
    <div v-else-if="projects.count === 0" class="flex flex-col items-center gap-3 py-12 text-center">
      <IconFolder class="size-10 text-muted-foreground" />
      <p class="text-lg font-medium">{{ t('projects.emptyTitle') }}</p>
      <p class="text-sm text-muted-foreground">
        {{ t('projects.emptyDescription') }}
      </p>
    </div>

    <!-- Project Grid -->
    <div id="projects-grid" v-else class="grid grid-cols-1 gap-4 @lg:grid-cols-2 @3xl:grid-cols-3">
      <Card
        v-for="p in projects.projects"
        :key="p.id"
        :class="[
          'cursor-pointer transition-colors hover:border-primary/50',
          projects.selectedId === p.id ? 'border-primary' : '',
        ]"
        @click="projects.select(p.id); emit('select-project', p.id)"
      >
        <CardHeader>
          <!-- Title + Status -->
          <div class="flex items-start justify-between gap-2">
            <CardTitle class="text-base">
              <span class="font-mono text-xs text-muted-foreground mr-1.5">#{{ p.id }}</span>
              {{ p.initiative_name || p.name || t('projects.unnamedFallback', { id: p.id }) }}
            </CardTitle>
            <Badge id="projects-status-badge" :variant="getStatusVariant(p.status)">
              {{ getStatusLabel(p.status) }}
            </Badge>
          </div>

          <!-- Description (clickeable) -->
          <CardDescription
            class="line-clamp-2 cursor-pointer hover:text-foreground/80 transition-colors"
            :title="p.description ? t('projects.clickToExpand') : ''"
            @click.stop="p.description ? openDescription(p) : null"
          >
            {{ p.description || t('projects.noDescription') }}
          </CardDescription>

          <!-- Key + Date -->
          <div v-if="p.key" class="flex items-center gap-2 pt-1">
            <Badge variant="secondary" class="font-mono text-xs">
              {{ p.key }}
            </Badge>
            <span v-if="p.start_date" class="text-xs text-muted-foreground">
              {{ p.start_date }}
            </span>
          </div>

          <!-- Team Members -->
          <div class="pt-3 border-t">
            <div class="flex items-center justify-between gap-2">
              <div class="flex items-center gap-1.5 min-w-0">
                <IconUsers class="size-3.5 text-muted-foreground shrink-0" />
                <span class="text-xs text-muted-foreground font-medium">{{ t('projects.teamMembers') }}</span>
              </div>
              <Button
                variant="ghost"
                size="sm"
                class="h-6 text-xs gap-1 px-2 shrink-0"
                @click.stop="openTeamDialog(p.id)"
              >
                <IconUserPlus class="size-3" />
                {{ t('projects.manageTeam') }}
              </Button>
            </div>
            <div v-if="getTeamMembers(p.id).length > 0" class="flex items-center gap-1.5 pt-1.5 flex-wrap">
              <template v-for="member in getTeamMembers(p.id).slice(0, 5)" :key="member.id">
                <Tooltip>
                  <TooltipTrigger as-child>
                    <Avatar class="size-6 border-2 border-background">
                      <AvatarFallback class="text-[10px] bg-muted">
                        {{ getInitials(member.full_name || member.email) }}
                      </AvatarFallback>
                    </Avatar>
                  </TooltipTrigger>
                  <TooltipContent side="top" class="text-xs">
                    {{ member.full_name || member.email }}
                  </TooltipContent>
                </Tooltip>
              </template>
              <button
                v-if="getTeamMembers(p.id).length > 5"
                class="size-6 rounded-full bg-muted text-[10px] text-muted-foreground flex items-center justify-center border-2 border-background hover:bg-muted/80 transition-colors"
                :title="t('projects.moreMembers', { count: getTeamMembers(p.id).length - 5 })"
                @click.stop="openTeamDialog(p.id)"
              >
                +{{ getTeamMembers(p.id).length - 5 }}
              </button>
            </div>
            <div v-else class="pt-1.5">
              <span class="text-xs text-muted-foreground italic">{{ t('projects.noTeamMembers') }}</span>
            </div>
          </div>
        </CardHeader>
      </Card>
    </div>
  </div>

  <!-- Description Modal -->
  <Dialog v-model:open="descOpen">
    <DialogContent class="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">
      <DialogHeader>
        <DialogTitle>{{ descProject?.name }}</DialogTitle>
        <DialogDescription>{{ t('projects.descriptionModalTitle') }}</DialogDescription>
      </DialogHeader>
      <div class="text-sm leading-relaxed whitespace-pre-wrap">
        {{ descProject?.description || t('projects.noDescription') }}
      </div>
    </DialogContent>
  </Dialog>

  <!-- Team Members Modal -->
  <Dialog v-model:open="teamDialogOpen">
    <DialogContent class="sm:max-w-[480px] max-h-[80vh] flex flex-col">
      <DialogHeader>
        <DialogTitle>{{ t('projects.manageTeam') }}</DialogTitle>
        <DialogDescription>{{ t('projects.selectTeamMembers') }}</DialogDescription>
      </DialogHeader>
      <!-- Search -->
      <div class="relative">
        <IconSearch class="absolute left-3 top-1/2 -translate-y-1/2 size-4 text-muted-foreground" />
        <input
          v-model="teamSearch"
          :placeholder="t('siteHeader.search')"
          class="w-full h-9 rounded-md border border-input bg-background pl-9 pr-3 text-sm outline-none focus:border-ring focus:ring-1 focus:ring-ring transition-colors"
        />
      </div>
      <!-- Users list -->
      <div class="flex-1 overflow-y-auto space-y-0.5 py-2">
        <button
          v-for="u in filteredUsers"
          :key="u.id"
          class="w-full flex items-center gap-3 rounded-md px-3 py-2 text-left text-sm hover:bg-muted transition-colors"
          :class="pendingTeam.has(u.id) ? 'bg-accent' : ''"
          @click="toggleTeamMember(u.id)"
        >
          <Avatar class="size-7">
            <AvatarFallback class="text-xs bg-muted">
              {{ getInitials(u.full_name || u.email) }}
            </AvatarFallback>
          </Avatar>
          <div class="flex-1 min-w-0">
            <div class="font-medium truncate">{{ u.full_name || u.email }}</div>
            <div class="text-xs text-muted-foreground truncate">
              {{ [u.role, u.cell].filter(Boolean).join(' · ') }}
            </div>
          </div>
          <div
            class="size-4.5 rounded border flex items-center justify-center shrink-0 transition-colors"
            :class="pendingTeam.has(u.id) ? 'bg-primary border-primary' : 'border-input'"
          >
            <IconX v-if="pendingTeam.has(u.id)" class="size-3 text-primary-foreground" />
          </div>
        </button>
        <div v-if="filteredUsers.length === 0" class="py-8 text-center text-sm text-muted-foreground">
          {{ teamSearch ? t('siteHeader.noResults') : t('users.emptyTitle') }}
        </div>
      </div>
      <!-- Footer -->
      <div class="flex items-center justify-between pt-3 border-t">
        <span class="text-xs text-muted-foreground">
          {{ pendingTeam.size }} {{ t('projects.selectedCount') }}
        </span>
        <div class="flex gap-2">
          <Button variant="outline" size="sm" @click="teamDialogOpen = false">
            {{ t('common.cancel') }}
          </Button>
          <Button size="sm" @click="saveTeam">
            {{ t('common.save') }}
          </Button>
        </div>
      </div>
    </DialogContent>
  </Dialog>
</template>
