'use client'
import React, { useEffect, useState } from 'react'
import { pb } from '@/lib/pocketbase'
import { getAuthUser, logout } from '@/lib/auth'
import { Heatmap } from '@/components/gamification/Heatmap'
import { BadgeGrid } from '@/components/gamification/BadgeGrid'
import { Leaderboard } from '@/components/gamification/Leaderboard'
import { ActivityFeed } from '@/components/gamification/ActivityFeed'
import { Button } from '@/components/ui/Button'
import { getLeaderboard, getFeed } from '@/lib/services'
import type {
  GamificationProfile,
  EmployeeBadge,
  Badge,
  SessionCompletion,
  LeaderboardEntry,
  FeedEntry,
} from '@/types'

type Tab = 'profile' | 'leaderboard' | 'feed'

const LEVEL_LABELS: Record<string, string> = {
  intern: 'Intern',
  junior: 'Junior',
  medior: 'Medior',
  senior: 'Senior',
  staff: 'Staff',
  principal: 'Principal',
}

export default function ProfilePage() {
  const user = getAuthUser()
  const [tab, setTab] = useState<Tab>('profile')

  const [gamification, setGamification] = useState<GamificationProfile | null>(null)
  const [earnedBadges, setEarnedBadges] = useState<EmployeeBadge[]>([])
  const [allBadges, setAllBadges] = useState<Badge[]>([])
  const [completions, setCompletions] = useState<SessionCompletion[]>([])
  const [leaderboard, setLeaderboard] = useState<LeaderboardEntry[]>([])
  const [feed, setFeed] = useState<FeedEntry[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!user) return

    async function load() {
      setLoading(true)
      try {
        const [gamResult, badgeResult, allBadgeResult, compResult] = await Promise.allSettled([
          pb
            .collection('gamification_profiles')
            .getFullList<GamificationProfile>({ filter: `user="${user!.id}"`, expand: 'user' })
            .then((r) => r[0] ?? null),
          pb
            .collection('employee_badges')
            .getFullList<EmployeeBadge>({ filter: `user="${user!.id}"`, expand: 'badge' }),
          pb.collection('badges').getFullList<Badge>({ sort: 'tier,label' }),
          pb
            .collection('session_completions')
            .getFullList<SessionCompletion>({ filter: `user="${user!.id}"`, sort: '-completed_at' }),
        ])

        if (gamResult.status === 'fulfilled') setGamification(gamResult.value)
        if (badgeResult.status === 'fulfilled') setEarnedBadges(badgeResult.value)
        if (allBadgeResult.status === 'fulfilled') setAllBadges(allBadgeResult.value)
        if (compResult.status === 'fulfilled') setCompletions(compResult.value)
      } catch {
        // best-effort
      } finally {
        setLoading(false)
      }
    }

    void load()
  }, [user?.id])

  useEffect(() => {
    if (tab === 'leaderboard') {
      getLeaderboard().then(setLeaderboard).catch(() => {})
    }
    if (tab === 'feed') {
      getFeed().then(setFeed).catch(() => {})
    }
  }, [tab])

  if (!user) {
    return (
      <div style={{ color: 'var(--fg-muted)', textAlign: 'center', padding: 'var(--s-6)' }}>
        Not logged in.
      </div>
    )
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-5)' }}>
      {/* User card */}
      <div
        style={{
          background: 'var(--bg-dark)',
          color: 'var(--paper)',
          borderRadius: 'var(--r-lg)',
          padding: 'var(--s-5)',
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--s-4)',
        }}
      >
        <div
          style={{
            width: '56px',
            height: '56px',
            borderRadius: '50%',
            background: 'var(--accent)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: 'var(--t-h3)',
            fontWeight: 700,
            flexShrink: 0,
          }}
        >
          {user.display_name?.[0]?.toUpperCase() ?? user.email[0]?.toUpperCase()}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h2
            style={{
              margin: '0 0 var(--s-1)',
              fontSize: 'var(--t-body)',
              fontWeight: 700,
            }}
          >
            {user.display_name || user.email}
          </h2>
          {gamification && (
            <p
              style={{
                margin: 0,
                fontSize: 'var(--t-small)',
                opacity: 0.8,
              }}
            >
              {LEVEL_LABELS[gamification.current_level] ?? gamification.current_level} ·{' '}
              {gamification.total_commits} commits · {gamification.current_streak_weeks}w streak
            </p>
          )}
        </div>
        <Button
          variant="ghost"
          size="sm"
          onClick={logout}
          style={{ color: 'rgba(255,255,255,0.7)', borderColor: 'rgba(255,255,255,0.25)', flexShrink: 0 }}
        >
          Logout
        </Button>
      </div>

      {/* Tabs */}
      <div
        style={{
          display: 'flex',
          borderBottom: '2px solid var(--cream)',
        }}
      >
        {(['profile', 'leaderboard', 'feed'] as Tab[]).map((t) => (
          <button
            key={t}
            onClick={() => setTab(t)}
            style={{
              flex: 1,
              background: 'none',
              border: 'none',
              borderBottom: `2px solid ${tab === t ? 'var(--accent)' : 'transparent'}`,
              marginBottom: '-2px',
              padding: 'var(--s-3)',
              fontSize: 'var(--t-small)',
              fontFamily: 'var(--font-sans)',
              fontWeight: tab === t ? 700 : 400,
              color: tab === t ? 'var(--accent)' : 'var(--fg-muted)',
              cursor: 'pointer',
              textTransform: 'capitalize',
              minHeight: '44px',
              transition: 'color 150ms',
            }}
          >
            {t}
          </button>
        ))}
      </div>

      {/* Tab content */}
      {tab === 'profile' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-6)' }}>
          {loading ? (
            <div style={{ color: 'var(--fg-muted)' }}>Loading…</div>
          ) : (
            <>
              {/* Stats */}
              {gamification && (
                <div
                  style={{
                    display: 'grid',
                    gridTemplateColumns: 'repeat(2, 1fr)',
                    gap: 'var(--s-3)',
                  }}
                >
                  <StatCard label="Total commits" value={String(gamification.total_commits)} />
                  <StatCard label="Current streak" value={`${gamification.current_streak_weeks}w`} />
                  <StatCard label="Longest streak" value={`${gamification.longest_streak_weeks}w`} />
                  <StatCard label="Types explored" value={String(gamification.types_used.length)} />
                </div>
              )}

              {/* Heatmap */}
              <div>
                <h3
                  style={{
                    margin: '0 0 var(--s-3)',
                    fontSize: 'var(--t-small)',
                    fontWeight: 700,
                    color: 'var(--fg)',
                  }}
                >
                  Activity
                </h3>
                <Heatmap completions={completions} />
              </div>

              {/* Badges */}
              <div>
                <h3
                  style={{
                    margin: '0 0 var(--s-3)',
                    fontSize: 'var(--t-small)',
                    fontWeight: 700,
                    color: 'var(--fg)',
                  }}
                >
                  Badges ({earnedBadges.length}/{allBadges.length})
                </h3>
                <BadgeGrid allBadges={allBadges} earned={earnedBadges} />
              </div>
            </>
          )}
        </div>
      )}

      {tab === 'leaderboard' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
          <Leaderboard entries={leaderboard} currentUserId={user.id} />
        </div>
      )}

      {tab === 'feed' && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
          <ActivityFeed entries={feed} />
        </div>
      )}
    </div>
  )
}

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <div
      style={{
        background: 'var(--bg-warm)',
        borderRadius: 'var(--r-md)',
        padding: 'var(--s-4)',
        display: 'flex',
        flexDirection: 'column',
        gap: 'var(--s-1)',
      }}
    >
      <span
        style={{
          fontSize: 'var(--t-label)',
          fontFamily: 'var(--font-mono)',
          textTransform: 'uppercase',
          letterSpacing: 'var(--label-ls)',
          color: 'var(--fg-muted)',
        }}
      >
        {label}
      </span>
      <span style={{ fontSize: 'var(--t-h3)', fontWeight: 700, color: 'var(--fg)' }}>
        {value}
      </span>
    </div>
  )
}
