'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'

interface ContentSession {
  id: string
  title: string
  dayOfWeek: string
  topic: string
  description: string | null
  weekStart: string
  status: string
}

const dayColors: Record<string, string> = {
  Monday: 'bg-blue-500/10 border-blue-500/20 text-blue-400',
  Wednesday: 'bg-purple-500/10 border-purple-500/20 text-purple-400',
  Friday: 'bg-amber-500/10 border-amber-500/20 text-amber-400',
}

const dayTopics: Record<string, string> = {
  Monday: 'Industry / Freelance Strategy / Networking',
  Wednesday: 'AI Workflows / Prompting / Tool Stacks',
  Friday: 'Post-Production / Editing / Career Case Studies',
}

export default function ContentPage() {
  const [sessions, setSessions] = useState<ContentSession[]>([])
  const [loading, setLoading] = useState(true)
  const [showAdd, setShowAdd] = useState(false)
  const [newData, setNewData] = useState({ title: '', dayOfWeek: 'Monday', topic: '', weekStart: '' })
  const router = useRouter()

  const fetchSessions = () => {
    fetch('/api/content')
      .then(res => { if (res.status === 401) { router.push('/login'); return null } return res.json() })
      .then(d => { if (d) setSessions(d.sessions); setLoading(false) })
  }

  useEffect(() => { fetchSessions() }, [])

  const updateStatus = async (id: string, status: string) => {
    await fetch('/api/content', { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ id, status }) })
    fetchSessions()
  }

  const addSession = async () => {
    if (!newData.title.trim() || !newData.weekStart) return
    await fetch('/api/content', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(newData) })
    setNewData({ title: '', dayOfWeek: 'Monday', topic: '', weekStart: '' }); setShowAdd(false)
    fetchSessions()
  }

  if (loading) return <div className="flex items-center justify-center h-full"><div className="text-brand-muted">Loading...</div></div>

  // Group by week
  const weekMap = new Map<string, ContentSession[]>()
  sessions.forEach(s => {
    const key = new Date(s.weekStart).toISOString().split('T')[0]
    if (!weekMap.has(key)) weekMap.set(key, [])
    weekMap.get(key)!.push(s)
  })

  const planned = sessions.filter(s => s.status === 'planned').length
  const completed = sessions.filter(s => s.status === 'completed').length

  return (
    <div className="max-w-7xl mx-auto space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-brand-text">Content Calendar</h1>
          <p className="text-brand-muted text-sm mt-1">Weekly session rhythm — Mon / Wed / Fri</p>
        </div>
        <button onClick={() => setShowAdd(!showAdd)} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors">
          + Add Session
        </button>
      </div>

      {/* Weekly Rhythm */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {['Monday', 'Wednesday', 'Friday'].map(day => (
          <div key={day} className={`${dayColors[day]} border rounded-xl p-5`}>
            <p className="font-semibold text-sm">{day}</p>
            <p className="text-xs text-brand-muted mt-1">{dayTopics[day]}</p>
          </div>
        ))}
      </div>

      {/* Stats */}
      <div className="flex gap-6 text-sm">
        <div><span className="text-brand-muted">Planned: </span><span className="text-amber-400 font-medium">{planned}</span></div>
        <div><span className="text-brand-muted">Completed: </span><span className="text-green-400 font-medium">{completed}</span></div>
        <div><span className="text-brand-muted">Total: </span><span className="text-brand-text font-medium">{sessions.length}</span></div>
      </div>

      {/* Add Session */}
      {showAdd && (
        <div className="bg-brand-card border border-brand-border rounded-xl p-6 space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <input value={newData.title} onChange={e => setNewData({ ...newData, title: e.target.value })} placeholder="Session title" className="bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm placeholder-brand-muted/50 focus:outline-none focus:border-brand-accent" />
            <select value={newData.dayOfWeek} onChange={e => setNewData({ ...newData, dayOfWeek: e.target.value })} className="bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm focus:outline-none focus:border-brand-accent">
              <option value="Monday">Monday</option>
              <option value="Wednesday">Wednesday</option>
              <option value="Friday">Friday</option>
            </select>
            <input value={newData.topic} onChange={e => setNewData({ ...newData, topic: e.target.value })} placeholder="Topic" className="bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm placeholder-brand-muted/50 focus:outline-none focus:border-brand-accent" />
            <input type="date" value={newData.weekStart} onChange={e => setNewData({ ...newData, weekStart: e.target.value })} className="bg-brand-bg border border-brand-border rounded-lg px-3 py-2 text-brand-text text-sm focus:outline-none focus:border-brand-accent" />
          </div>
          <div className="flex gap-3">
            <button onClick={addSession} className="bg-brand-accent hover:bg-brand-accent-hover text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors">Add</button>
            <button onClick={() => setShowAdd(false)} className="text-brand-muted hover:text-brand-text text-sm px-4 py-2 transition-colors">Cancel</button>
          </div>
        </div>
      )}

      {/* Sessions by Week */}
      <div className="space-y-6">
        {Array.from(weekMap.entries()).map(([week, weekSessions]) => (
          <div key={week} className="bg-brand-card border border-brand-border rounded-xl p-6">
            <h3 className="text-sm font-semibold text-brand-text mb-4">Week of {new Date(week + 'T00:00:00').toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })}</h3>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              {['Monday', 'Wednesday', 'Friday'].map(day => {
                const daySessions = weekSessions.filter(s => s.dayOfWeek === day)
                return (
                  <div key={day} className="space-y-2">
                    {daySessions.map(s => (
                      <div key={s.id} className={`${dayColors[day]} border rounded-lg p-4`}>
                        <div className="flex items-start justify-between">
                          <div>
                            <p className="text-sm font-medium text-brand-text">{s.title}</p>
                            <p className="text-xs text-brand-muted mt-0.5">{s.topic}</p>
                          </div>
                          <span className={`text-xs px-2 py-0.5 rounded-full ${
                            s.status === 'completed' ? 'bg-green-400/10 text-green-400' :
                            s.status === 'cancelled' ? 'bg-red-400/10 text-red-400' :
                            'bg-amber-400/10 text-amber-400'
                          }`}>
                            {s.status}
                          </span>
                        </div>
                        {s.status === 'planned' && (
                          <div className="flex gap-2 mt-3">
                            <button onClick={() => updateStatus(s.id, 'completed')} className="text-xs text-green-400 hover:text-green-300 transition-colors">✓ Complete</button>
                            <button onClick={() => updateStatus(s.id, 'cancelled')} className="text-xs text-red-400 hover:text-red-300 transition-colors">✕ Cancel</button>
                          </div>
                        )}
                      </div>
                    ))}
                    {daySessions.length === 0 && (
                      <div className={`border border-dashed rounded-lg p-4 text-center ${dayColors[day].split(' ')[1]}`}>
                        <p className="text-xs text-brand-muted">{day} — no session</p>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
        ))}
        {weekMap.size === 0 && (
          <div className="bg-brand-card border border-brand-border rounded-xl p-12 text-center">
            <p className="text-brand-muted">No sessions scheduled yet. Add one to get started!</p>
          </div>
        )}
      </div>
    </div>
  )
}
