<script setup lang="ts">
import { computed, ref } from 'vue'
import { useAuthStore } from '@/stores/auth'
import type { ProfileResponse } from '@/api/types'
import OrgSwitcher from '@/components/layout/OrgSwitcher.vue'

const props = defineProps<{ profile: ProfileResponse }>()
const auth = useAuthStore()

const copied = ref(false)

function copySub() {
  navigator.clipboard.writeText(props.profile.sub)
  copied.value = true
  setTimeout(() => { copied.value = false }, 1500)
}

const initials = computed(() => {
  const name = props.profile.name || props.profile.email
  return name
    .split(/[\s@]+/)
    .slice(0, 2)
    .map(w => w[0]?.toUpperCase() ?? '')
    .join('')
})

const roleBadgeClass = computed(() => {
  switch (props.profile.inferred_role) {
    case 'admin':
      return 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
    case 'editor':
      return 'bg-accent-100 text-accent-700 dark:bg-accent-900/30 dark:text-accent-400'
    default:
      return 'bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400'
  }
})

const roleLabel = computed(() => {
  return props.profile.inferred_role.charAt(0).toUpperCase() + props.profile.inferred_role.slice(1)
})

const formattedLastLogin = computed(() => {
  if (!props.profile.last_login_at) return null
  return new Date(props.profile.last_login_at).toLocaleString()
})

const authMethodLabel = computed(() => {
  switch (props.profile.auth_method) {
    case 'session':
      return 'Auth0 Session'
    case 'jwt':
      return 'JWT Access Token'
    case 'api_key':
      return 'API Key'
    default:
      return 'Anonymous'
  }
})

const githubDisplayName = computed(() => {
  if (!props.profile.github_user) return null
  const { login, name } = props.profile.github_user
  if (name && name !== login) return `${name} (${login})`
  return login
})
</script>

<template>
  <div class="max-w-2xl mx-auto space-y-6">
    <h1 class="text-2xl font-bold font-display text-slate-800 dark:text-slate-100">Profile</h1>

    <!-- Profile Header -->
    <div class="bg-surface-light dark:bg-slate-800/50 rounded-lg border border-border-light dark:border-slate-700 p-6">
      <div class="flex items-start gap-4">
        <img
          v-if="profile.picture"
          :src="profile.picture"
          :alt="profile.name"
          class="w-16 h-16 rounded-full ring-2 ring-gray-200 dark:ring-slate-600"
        />
        <div
          v-else
          class="w-16 h-16 rounded-full bg-accent-100 dark:bg-accent-900/30 flex items-center justify-center text-xl font-bold text-accent-600 dark:text-accent-400 ring-2 ring-gray-200 dark:ring-slate-600"
        >
          {{ initials }}
        </div>
        <div class="flex-1 min-w-0">
          <h2 class="text-lg font-semibold text-slate-800 dark:text-slate-100 truncate">{{ profile.name || 'Unknown' }}</h2>
          <p class="text-sm text-slate-500 dark:text-slate-400 truncate">{{ profile.email }}</p>
          <div v-if="profile.github_user" class="mt-1">
            <a
              :href="`https://github.com/${profile.github_user.login}`"
              target="_blank"
              rel="noopener"
              class="inline-flex items-center gap-1 text-sm text-accent-500 hover:text-accent-400 transition-colors"
            >
              <svg class="w-4 h-4" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" /></svg>
              {{ githubDisplayName }}
            </a>
          </div>
          <button
            class="mt-2 inline-flex items-center gap-1 text-xs font-mono text-slate-400 dark:text-slate-500 hover:text-slate-600 dark:hover:text-slate-300 transition-colors cursor-pointer truncate max-w-full"
            :title="copied ? 'Copied!' : 'Click to copy'"
            @click="copySub"
          >
            {{ profile.sub }}
            <svg v-if="!copied" class="w-3 h-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9.75a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184" />
            </svg>
            <svg v-else class="w-3 h-3 flex-shrink-0 text-green-500" fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
            </svg>
          </button>
          <p v-if="formattedLastLogin" class="mt-1 text-xs text-slate-400 dark:text-slate-500">
            Last login: {{ formattedLastLogin }}
          </p>
        </div>
      </div>
    </div>

    <!-- Roles & Permissions -->
    <div class="bg-surface-light dark:bg-slate-800/50 rounded-lg border border-border-light dark:border-slate-700 p-6">
      <h3 class="text-sm font-semibold text-slate-800 dark:text-slate-200 uppercase tracking-wider mb-4">Roles & Permissions</h3>
      <div class="flex items-center gap-3 mb-4">
        <span :class="['inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium', roleBadgeClass]">
          {{ roleLabel }}
        </span>
        <span class="text-xs text-slate-400 dark:text-slate-500">via {{ authMethodLabel }}</span>
      </div>
      <ul class="space-y-2">
        <li v-for="perm in profile.all_permissions" :key="perm" class="flex items-center gap-2 text-sm">
          <svg
            v-if="profile.permissions.includes(perm)"
            class="w-4 h-4 text-green-500 flex-shrink-0"
            fill="none"
            viewBox="0 0 24 24"
            stroke-width="2"
            stroke="currentColor"
          >
            <path stroke-linecap="round" stroke-linejoin="round" d="M4.5 12.75l6 6 9-13.5" />
          </svg>
          <svg
            v-else
            class="w-4 h-4 text-slate-300 dark:text-slate-600 flex-shrink-0"
            fill="none"
            viewBox="0 0 24 24"
            stroke-width="2"
            stroke="currentColor"
          >
            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
          </svg>
          <code class="font-mono text-xs" :class="profile.permissions.includes(perm) ? 'text-slate-700 dark:text-slate-300' : 'text-slate-400 dark:text-slate-500'">{{ perm }}</code>
        </li>
      </ul>
      <p class="mt-4 text-xs text-slate-400 dark:text-slate-500">
        Permissions are assigned via Auth0 roles. Contact your org admin to change access.
      </p>
    </div>

    <!-- Organization -->
    <div class="bg-surface-light dark:bg-slate-800/50 rounded-lg border border-border-light dark:border-slate-700 p-6">
      <h3 class="text-sm font-semibold text-slate-800 dark:text-slate-200 uppercase tracking-wider mb-4">Organization</h3>
      <p class="text-sm text-slate-700 dark:text-slate-300">{{ profile.org_login || auth.org }}</p>
      <div class="mt-3 flex items-center gap-3">
        <OrgSwitcher v-if="auth.orgs.length > 1" />
        <router-link
          :to="`/app/${profile.org_login || auth.org}/`"
          class="text-sm text-accent-500 hover:text-accent-400 transition-colors"
        >
          Dashboard
        </router-link>
      </div>
    </div>
  </div>
</template>
