'use client'
import React, { useEffect, useState } from 'react'
import { pb } from '@/lib/pocketbase'
import { getAuthUser } from '@/lib/auth'
import { WeekHeader } from '@/components/employee/WeekHeader'
import { TopicCard } from '@/components/employee/TopicCard'
import type {
  EmployeeCurriculumState,
  CurriculumWeek,
  Topic,
  SessionCompletion,
} from '@/types'

export default function SessionPage() {
  const user = getAuthUser()

  const [curriculumState, setCurriculumState] = useState<EmployeeCurriculumState | null>(null)
  const [week, setWeek] = useState<CurriculumWeek | null>(null)
  const [topics, setTopics] = useState<Topic[]>([])
  const [completions, setCompletions] = useState<SessionCompletion[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  async function load() {
    if (!user) return
    setLoading(true)
    try {
      let state: EmployeeCurriculumState
      try {
        const results = await pb
          .collection('employee_curriculum_state')
          .getFullList<EmployeeCurriculumState>({
            filter: `user="${user.id}"`,
          })
        if (results.length > 0 && results[0]) {
          state = results[0]
        } else {
          state = await pb
            .collection('employee_curriculum_state')
            .create<EmployeeCurriculumState>({
              user: user.id,
              current_cycle: 1,
              current_week: 1,
              start_date: new Date().toISOString(),
            })
        }
      } catch {
        setLoading(false)
        return
      }

      setCurriculumState(state)

      const weekResult = await pb
        .collection('curriculum_weeks')
        .getFullList<CurriculumWeek>({
          filter: `week_number=${state.current_week}`,
          expand: 'theme,topics',
        })

      const currentWeek = weekResult[0]
      if (!currentWeek) {
        setLoading(false)
        return
      }
      setWeek(currentWeek)

      if (currentWeek.expand?.topics && currentWeek.expand.topics.length > 0) {
        setTopics(currentWeek.expand.topics)
      } else if (currentWeek.topics.length > 0) {
        const topicList = await pb.collection('topics').getFullList<Topic>({
          filter: currentWeek.topics.map((id) => `id="${id}"`).join('||'),
        })
        setTopics(topicList)
      }

      const compList = await pb
        .collection('session_completions')
        .getFullList<SessionCompletion>({
          filter: `user="${user.id}" && week_number=${state.current_week} && cycle=${state.current_cycle}`,
        })
      setCompletions(compList)

      setError(null)
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load session')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void load()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [user?.id])

  function handleTopicComplete(topicId: string) {
    setCompletions((prev) => [
      ...prev,
      {
        id: `temp-${topicId}`,
        user: user?.id ?? '',
        topic: topicId,
        micro_learning: '',
        week_number: curriculumState?.current_week ?? 1,
        cycle: curriculumState?.current_cycle ?? 1,
        completed_at: new Date().toISOString(),
      },
    ])
  }

  const completedTopicIds = new Set(completions.map((c) => c.topic))

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

  if (loading) {
    return (
      <div style={{ color: 'var(--fg-muted)', padding: 'var(--s-6)' }}>
        Loading your session…
      </div>
    )
  }

  if (error) {
    return (
      <div
        style={{
          background: '#f8d7da',
          color: '#c0392b',
          borderRadius: 'var(--r-sm)',
          padding: 'var(--s-4)',
          margin: 'var(--s-4)',
        }}
      >
        {error}
      </div>
    )
  }

  if (!curriculumState || !week) {
    return (
      <div
        style={{
          textAlign: 'center',
          padding: 'var(--s-8) var(--s-5)',
          display: 'flex',
          flexDirection: 'column',
          gap: 'var(--s-4)',
          alignItems: 'center',
        }}
      >
        <h2 style={{ margin: 0, fontSize: 'var(--t-h3)', color: 'var(--fg)' }}>
          No curriculum yet
        </h2>
        <p style={{ margin: 0, fontSize: 'var(--t-body)', color: 'var(--fg-muted)' }}>
          Ask your admin to generate and activate a curriculum.
        </p>
      </div>
    )
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
      <WeekHeader
        curriculumState={curriculumState}
        week={week}
        completedCount={completedTopicIds.size}
        totalCount={topics.length}
      />

      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-3)' }}>
        {topics.length === 0 ? (
          <div style={{ color: 'var(--fg-muted)', fontSize: 'var(--t-body)', textAlign: 'center', padding: 'var(--s-6)' }}>
            No topics this week.
          </div>
        ) : (
          topics.map((topic) => (
            <TopicCard
              key={topic.id}
              topic={topic}
              weekNumber={curriculumState.current_week}
              userId={user.id}
              isCompleted={completedTopicIds.has(topic.id)}
              onComplete={handleTopicComplete}
            />
          ))
        )}
      </div>
    </div>
  )
}
