'use client'

import { useState, useEffect, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Progress } from '@/components/ui/progress'
import { Separator } from '@/components/ui/separator'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog'
import {
  Bot,
  BookOpen,
  Clock,
  Users,
  Target,
  Plus,
  Play,
  Pause,
  RotateCcw,
  CheckCircle,
  Trash2,
  ExternalLink,
  MessageCircle,
  Wrench,
  Sparkles,
  Timer,
  ChevronRight,
} from 'lucide-react'
import { BRAND } from '@/lib/constants'

/* ------------------------------------------------------------------ */
/* Study Timer (Pomodoro)                                              */
/* ------------------------------------------------------------------ */

function StudyTimer() {
  const [mode, setMode] = useState<'focus' | 'break'>('focus')
  const [focusMinutes, setFocusMinutes] = useState(25)
  const [breakMinutes, setBreakMinutes] = useState(5)
  const [secondsLeft, setSecondsLeft] = useState(25 * 60)
  const [isRunning, setIsRunning] = useState(false)
  const [sessions, setSessions] = useState(0)
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null)

  const totalSeconds = mode === 'focus' ? focusMinutes * 60 : breakMinutes * 60
  const progress = ((totalSeconds - secondsLeft) / totalSeconds) * 100

  useEffect(() => {
    if (isRunning) {
      intervalRef.current = setInterval(() => {
        setSecondsLeft((prev) => {
          if (prev <= 1) {
            setIsRunning(false)
            if (mode === 'focus') {
              setSessions((s) => s + 1)
              setMode('break')
              return breakMinutes * 60
            } else {
              setMode('focus')
              return focusMinutes * 60
            }
          }
          return prev - 1
        })
      }, 1000)
    } else if (intervalRef.current) {
      clearInterval(intervalRef.current)
    }
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current)
    }
  }, [isRunning, mode, focusMinutes, breakMinutes])

  const reset = () => {
    setIsRunning(false)
    setMode('focus')
    setSecondsLeft(focusMinutes * 60)
  }

  const minutes = Math.floor(secondsLeft / 60)
  const seconds = secondsLeft % 60

  return (
    <div className="text-center">
      {/* Mode Tabs */}
      <div className="flex gap-2 mb-4">
        <Button
          size="sm"
          variant={mode === 'focus' ? 'default' : 'outline'}
          onClick={() => { setMode('focus'); setIsRunning(false); setSecondsLeft(focusMinutes * 60) }}
          className={`rounded-lg text-xs flex-1 ${mode === 'focus' ? 'text-white' : ''}`}
          style={mode === 'focus' ? { background: BRAND.colors.primaryGradient } : {}}
        >
          Focus
        </Button>
        <Button
          size="sm"
          variant={mode === 'break' ? 'default' : 'outline'}
          onClick={() => { setMode('break'); setIsRunning(false); setSecondsLeft(breakMinutes * 60) }}
          className={`rounded-lg text-xs flex-1 ${mode === 'break' ? 'text-white' : ''}`}
          style={mode === 'break' ? { background: 'linear-gradient(135deg, #27ae60 0%, #2ecc71 100%)' } : {}}
        >
          Break
        </Button>
      </div>

      {/* Timer Display */}
      <div className="relative w-40 h-40 mx-auto mb-4">
        <svg className="w-full h-full -rotate-90" viewBox="0 0 100 100">
          <circle cx="50" cy="50" r="45" fill="none" stroke="#e5e7eb" strokeWidth="6" />
          <circle
            cx="50" cy="50" r="45" fill="none"
            stroke={mode === 'focus' ? '#91C4D9' : '#27ae60'}
            strokeWidth="6"
            strokeLinecap="round"
            strokeDasharray={`${2 * Math.PI * 45}`}
            strokeDashoffset={`${2 * Math.PI * 45 * (1 - progress / 100)}`}
            className="transition-all duration-1000"
          />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className="text-3xl font-bold text-gray-900 font-mono">
            {String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}
          </span>
          <span className="text-xs text-gray-500 capitalize">{mode}</span>
        </div>
      </div>

      {/* Controls */}
      <div className="flex items-center justify-center gap-2 mb-4">
        <Button
          size="sm"
          variant="outline"
          onClick={reset}
          className="rounded-full w-9 h-9 p-0"
        >
          <RotateCcw className="w-4 h-4" />
        </Button>
        <Button
          size="lg"
          onClick={() => setIsRunning(!isRunning)}
          className="rounded-full w-12 h-12 text-white"
          style={{ background: BRAND.colors.primaryGradient }}
        >
          {isRunning ? <Pause className="w-5 h-5" /> : <Play className="w-5 h-5 ml-0.5" />}
        </Button>
        <div className="w-9" />
      </div>

      {/* Duration Settings */}
      <div className="flex items-center justify-center gap-4 text-xs text-gray-500">
        <label className="flex items-center gap-1">
          Focus:
          <Input
            type="number"
            min={1}
            max={90}
            value={focusMinutes}
            onChange={(e) => {
              const val = parseInt(e.target.value) || 25
              setFocusMinutes(val)
              if (mode === 'focus' && !isRunning) setSecondsLeft(val * 60)
            }}
            className="w-12 h-7 text-center text-xs rounded"
          />
          min
        </label>
        <label className="flex items-center gap-1">
          Break:
          <Input
            type="number"
            min={1}
            max={30}
            value={breakMinutes}
            onChange={(e) => {
              const val = parseInt(e.target.value) || 5
              setBreakMinutes(val)
              if (mode === 'break' && !isRunning) setSecondsLeft(val * 60)
            }}
            className="w-12 h-7 text-center text-xs rounded"
          />
          min
        </label>
      </div>

      {sessions > 0 && (
        <p className="text-xs text-gray-400 mt-3">
          <CheckCircle className="w-3 h-3 inline mr-1" />
          {sessions} focus session{sessions !== 1 ? 's' : ''} completed today
        </p>
      )}
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Goal Tracker                                                        */
/* ------------------------------------------------------------------ */

interface Goal {
  id: string
  title: string
  target: number
  current: number
  unit: string
  createdAt: string
}

function GoalTracker() {
  const [goals, setGoals] = useState<Goal[]>(() => {
    if (typeof window !== 'undefined') {
      const stored = localStorage.getItem('studo-goals')
      if (stored) {
        try { return JSON.parse(stored) } catch { return [] }
      }
    }
    return []
  })
  const [showDialog, setShowDialog] = useState(false)
  const [formTitle, setFormTitle] = useState('')
  const [formTarget, setFormTarget] = useState('')
  const [formUnit, setFormUnit] = useState('sessions')

  const saveGoals = (updated: Goal[]) => {
    setGoals(updated)
    localStorage.setItem('studo-goals', JSON.stringify(updated))
  }

  const addGoal = () => {
    if (!formTitle || !formTarget) return
    const newGoal: Goal = {
      id: Date.now().toString(),
      title: formTitle,
      target: parseInt(formTarget),
      current: 0,
      unit: formUnit,
      createdAt: new Date().toISOString(),
    }
    saveGoals([...goals, newGoal])
    setFormTitle('')
    setFormTarget('')
    setShowDialog(false)
  }

  const updateGoal = (id: string, delta: number) => {
    saveGoals(goals.map((g) => g.id === id ? { ...g, current: Math.max(0, g.current + delta) } : g))
  }

  const deleteGoal = (id: string) => {
    saveGoals(goals.filter((g) => g.id !== id))
  }

  return (
    <div>
      {goals.length === 0 && (
        <div className="text-center py-4">
          <Target className="w-8 h-8 text-gray-300 mx-auto mb-2" />
          <p className="text-xs text-gray-500">No goals set yet. Create your first study goal!</p>
        </div>
      )}

      <div className="space-y-3 max-h-64 overflow-y-auto">
        {goals.map((goal) => {
          const pct = Math.min((goal.current / goal.target) * 100, 100)
          const isComplete = goal.current >= goal.target
          return (
            <div key={goal.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg">
              <div className="flex-1 min-w-0">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm font-medium text-gray-700 truncate">{goal.title}</span>
                  {isComplete && <CheckCircle className="w-4 h-4 text-green-500 shrink-0" />}
                </div>
                <Progress value={pct} className="h-2" />
                <p className="text-[10px] text-gray-400 mt-1">
                  {goal.current} / {goal.target} {goal.unit} ({Math.round(pct)}%)
                </p>
              </div>
              <div className="flex flex-col gap-1">
                <Button
                  size="sm"
                  variant="outline"
                  className="h-7 w-7 p-0 rounded-full"
                  onClick={() => updateGoal(goal.id, 1)}
                >
                  <Plus className="w-3 h-3" />
                </Button>
                <Button
                  size="sm"
                  variant="ghost"
                  className="h-7 w-7 p-0 rounded-full text-red-400 hover:text-red-600"
                  onClick={() => deleteGoal(goal.id)}
                >
                  <Trash2 className="w-3 h-3" />
                </Button>
              </div>
            </div>
          )
        })}
      </div>

      <Button
        variant="outline"
        size="sm"
        className="w-full mt-3 rounded-lg"
        onClick={() => setShowDialog(true)}
      >
        <Plus className="w-3.5 h-3.5 mr-1.5" />
        Add Goal
      </Button>

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="sm:max-w-sm">
          <DialogHeader>
            <DialogTitle>New Study Goal</DialogTitle>
          </DialogHeader>
          <div className="space-y-3">
            <div>
              <Label className="text-sm font-medium">Goal Title</Label>
              <Input
                value={formTitle}
                onChange={(e) => setFormTitle(e.target.value)}
                placeholder="e.g., Complete Maths exercises"
                className="mt-1 rounded-lg"
              />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <Label className="text-sm font-medium">Target</Label>
                <Input
                  type="number"
                  min={1}
                  value={formTarget}
                  onChange={(e) => setFormTarget(e.target.value)}
                  placeholder="10"
                  className="mt-1 rounded-lg"
                />
              </div>
              <div>
                <Label className="text-sm font-medium">Unit</Label>
                <select
                  value={formUnit}
                  onChange={(e) => setFormUnit(e.target.value)}
                  className="mt-1 w-full h-9 rounded-lg border border-gray-300 px-3 text-sm bg-white"
                >
                  <option value="sessions">Sessions</option>
                  <option value="hours">Hours</option>
                  <option value="chapters">Chapters</option>
                  <option value="exercises">Exercises</option>
                  <option value="pages">Pages</option>
                  <option value="past papers">Past Papers</option>
                </select>
              </div>
            </div>
          </div>
          <DialogFooter className="gap-2">
            <Button variant="outline" onClick={() => setShowDialog(false)} className="rounded-lg">Cancel</Button>
            <Button
              onClick={addGoal}
              disabled={!formTitle || !formTarget}
              className="rounded-lg text-white"
              style={{ background: BRAND.colors.primaryGradient }}
            >
              Create Goal
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}

/* ------------------------------------------------------------------ */
/* Quick Links                                                         */
/* ------------------------------------------------------------------ */

const aiQuickLinks = [
  { subject: 'Mathematics', query: 'Help me understand calculus concepts for Grade 12' },
  { subject: 'Physical Sciences', query: 'Explain Newton\'s laws of motion with examples' },
  { subject: 'Life Sciences', query: 'Help me revise genetics and DNA for exams' },
  { subject: 'Accounting', query: 'Explain the accounting equation and balance sheet' },
  { subject: 'English', query: 'Help me write a better essay introduction' },
  { subject: 'History', query: 'Summarise the causes of World War 2 for Grade 11' },
]

const pastPapers = [
  { title: 'NSC Past Papers (DBE)', url: 'https://www.education.gov.za/Curriculum/NationalSeniorCertificateNSCExaminations.aspx', description: 'Official DBE past exam papers and memos' },
  { title: 'Vuma Maths', url: 'https://www.vuma.com.za/', description: 'Free CAPS-aligned Maths resources' },
  { title: 'Mindset Learn', url: 'https://www.mindset.co.za/learn', description: 'Video lessons and study materials' },
  { title: 'Siyavula', url: 'https://www.siyavula.com/', description: 'Open textbooks and practice problems' },
  { title: 'MiBrain', url: 'https://mibrain.co.za/', description: 'Study notes and exam preparation' },
]

/* ------------------------------------------------------------------ */
/* Main Page                                                           */
/* ------------------------------------------------------------------ */

export default function StudyToolsPage() {
  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
      {/* Page Header */}
      <div className="mb-6">
        <div className="flex items-center gap-2 mb-1">
          <div
            className="w-8 h-8 rounded-lg flex items-center justify-center"
            style={{ background: BRAND.colors.primaryGradient }}
          >
            <Wrench className="w-4 h-4 text-white" />
          </div>
          <h1 className="text-2xl font-bold text-gray-900">Study Tools</h1>
        </div>
        <p className="text-sm text-gray-500">
          Boost your learning with AI-powered tools and resources
        </p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* AI Study Buddy */}
        <Card className="border-[#91C4D9]/30 bg-gradient-to-br from-white to-[#f0f9ff]/30">
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-base flex items-center gap-2">
                <Bot className="w-5 h-5 text-[#5b9ebd]" />
                AI Study Buddy
              </CardTitle>
              <Badge variant="secondary" className="text-[10px] bg-[#f0f9ff] text-[#5b9ebd]">
                <Sparkles className="w-3 h-3 mr-1" />
                AI-Powered
              </Badge>
            </div>
            <p className="text-xs text-gray-500">Ask the AI Coach about any subject for instant help</p>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
              {aiQuickLinks.map((link) => (
                <a
                  key={link.subject}
                  href={`/ai-coach?msg=${encodeURIComponent(link.query)}`}
                  className="flex items-center gap-2 p-2.5 bg-white rounded-lg border border-gray-100 hover:border-[#91C4D9]/50 hover:shadow-sm transition-all group"
                >
                  <MessageCircle className="w-4 h-4 text-gray-400 group-hover:text-[#5b9ebd] transition-colors shrink-0" />
                  <span className="text-xs font-medium text-gray-700 group-hover:text-[#5b9ebd] truncate transition-colors">
                    {link.subject}
                  </span>
                </a>
              ))}
            </div>
            <a href="/ai-coach">
              <Button
                variant="outline"
                className="w-full mt-3 rounded-lg text-xs"
              >
                <ChevronRight className="w-3 h-3 mr-1" />
                Open Full AI Coach
              </Button>
            </a>
          </CardContent>
        </Card>

        {/* Study Timer */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <Timer className="w-5 h-5 text-[#5b9ebd]" />
              Study Timer
            </CardTitle>
            <p className="text-xs text-gray-500">Pomodoro technique for focused study sessions</p>
          </CardHeader>
          <CardContent>
            <StudyTimer />
          </CardContent>
        </Card>

        {/* Past Papers */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <BookOpen className="w-5 h-5 text-[#5b9ebd]" />
              Past Papers & Resources
            </CardTitle>
            <p className="text-xs text-gray-500">Essential SA exam preparation resources</p>
          </CardHeader>
          <CardContent className="space-y-2 max-h-80 overflow-y-auto">
            {pastPapers.map((paper) => (
              <a
                key={paper.title}
                href={paper.url}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-3 p-3 rounded-lg hover:bg-gray-50 transition-colors group"
              >
                <div className="w-9 h-9 rounded-lg bg-[#f0f9ff] flex items-center justify-center shrink-0">
                  <ExternalLink className="w-4 h-4 text-[#5b9ebd] group-hover:text-[#91C4D9]" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-700 group-hover:text-[#5b9ebd] truncate transition-colors">
                    {paper.title}
                  </p>
                  <p className="text-xs text-gray-400 truncate">{paper.description}</p>
                </div>
              </a>
            ))}
          </CardContent>
        </Card>

        {/* Goal Tracker */}
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-base flex items-center gap-2">
              <Target className="w-5 h-5 text-[#5b9ebd]" />
              Goal Tracker
            </CardTitle>
            <p className="text-xs text-gray-500">Set study goals and track your progress</p>
          </CardHeader>
          <CardContent>
            <GoalTracker />
          </CardContent>
        </Card>

        {/* Study Group Finder Placeholder */}
        <Card className="lg:col-span-2 border-dashed">
          <CardContent className="p-6 flex flex-col sm:flex-row items-center justify-center gap-4 text-center sm:text-left">
            <div className="w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center shrink-0">
              <Users className="w-6 h-6 text-gray-400" />
            </div>
            <div>
              <h3 className="font-semibold text-gray-700 mb-1">Study Group Finder</h3>
              <p className="text-sm text-gray-500 max-w-md">
                Coming soon! Match with study partners in your area or online. Collaborate on subjects, share notes, and learn together.
              </p>
              <Badge variant="outline" className="mt-2 text-[10px]">
                Coming Soon
              </Badge>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
