"use client"; import { useEffect, useState, useCallback } from "react"; import { useRouter } from "next/navigation"; import { useAuth } from "@/lib/auth"; import { getGoals, getGoal, createGoal, updateGoal, deleteGoal, generateGoalPlan, getGoalReport, getGroups, Goal, GoalPlanResult, GoalReport, Group, } from "@/lib/api"; export default function GoalsPage() { const { token } = useAuth(); const router = useRouter(); const [goals, setGoals] = useState([]); const [groups, setGroups] = useState([]); const [loading, setLoading] = useState(true); const [showForm, setShowForm] = useState(false); const [selectedGoal, setSelectedGoal] = useState<(Goal & { tasks?: unknown[] }) | null>(null); const [planResult, setPlanResult] = useState(null); const [report, setReport] = useState(null); const [aiLoading, setAiLoading] = useState(null); const [error, setError] = useState(null); // Form state const [formTitle, setFormTitle] = useState(""); const [formDate, setFormDate] = useState(""); const [formGroup, setFormGroup] = useState(""); const loadData = useCallback(async () => { if (!token) return; setLoading(true); try { const [goalsRes, groupsRes] = await Promise.all([ getGoals(token), getGroups(token), ]); setGoals(goalsRes.data || []); setGroups(groupsRes.data || []); } catch (err) { console.error("Chyba pri nacitani:", err); setError("Nepodarilo se nacist data"); } finally { setLoading(false); } }, [token]); useEffect(() => { if (!token) { router.replace("/login"); return; } loadData(); }, [token, router, loadData]); async function handleCreate(e: React.FormEvent) { e.preventDefault(); if (!token || !formTitle.trim()) return; try { await createGoal(token, { title: formTitle.trim(), target_date: formDate || null, group_id: formGroup || null, }); setFormTitle(""); setFormDate(""); setFormGroup(""); setShowForm(false); loadData(); } catch (err) { console.error("Chyba pri vytvareni:", err); setError("Nepodarilo se vytvorit cil"); } } async function handleSelectGoal(goal: Goal) { if (!token) return; try { const res = await getGoal(token, goal.id); setSelectedGoal(res.data); setPlanResult(null); setReport(null); } catch (err) { console.error("Chyba pri nacitani cile:", err); } } async function handleGeneratePlan(goalId: string) { if (!token) return; setAiLoading("plan"); setError(null); try { const res = await generateGoalPlan(token, goalId); setPlanResult(res.data); // Reload goal to get updated plan const updated = await getGoal(token, goalId); setSelectedGoal(updated.data); loadData(); } catch (err) { console.error("Chyba pri generovani planu:", err); setError("Nepodarilo se vygenerovat plan. Zkuste to znovu."); } finally { setAiLoading(null); } } async function handleGetReport(goalId: string) { if (!token) return; setAiLoading("report"); setError(null); try { const res = await getGoalReport(token, goalId); setReport(res.data); } catch (err) { console.error("Chyba pri ziskavani reportu:", err); setError("Nepodarilo se ziskat report. Zkuste to znovu."); } finally { setAiLoading(null); } } async function handleUpdateProgress(goalId: string, pct: number) { if (!token) return; try { await updateGoal(token, goalId, { progress_pct: pct } as Partial); loadData(); if (selectedGoal && selectedGoal.id === goalId) { setSelectedGoal({ ...selectedGoal, progress_pct: pct }); } } catch (err) { console.error("Chyba pri aktualizaci:", err); } } async function handleDelete(goalId: string) { if (!token) return; if (!confirm("Opravdu chcete smazat tento cil?")) return; try { await deleteGoal(token, goalId); setSelectedGoal(null); loadData(); } catch (err) { console.error("Chyba pri mazani:", err); } } function formatDate(d: string | null) { if (!d) return "Bez terminu"; return new Date(d).toLocaleDateString("cs-CZ", { day: "numeric", month: "short", year: "numeric" }); } function progressColor(pct: number) { if (pct >= 80) return "bg-green-500"; if (pct >= 50) return "bg-blue-500"; if (pct >= 20) return "bg-yellow-500"; return "bg-gray-400"; } if (!token) return null; return (
{/* Header */}

Cile

{/* Error */} {error && (
{error}
)} {/* Create form */} {showForm && (
setFormTitle(e.target.value)} placeholder="Napr. Naucit se TypeScript" className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 min-h-[44px]" required />
setFormDate(e.target.value)} className="w-full px-3 py-2 border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500 min-h-[44px]" />
)} {/* Goals list */} {loading ? (
) : goals.length === 0 ? (
🎯

Zadne cile

Vytvorte svuj prvni cil

) : (
{goals.map((goal) => ( ))}
)} {/* Goal detail panel */} {selectedGoal && (

{selectedGoal.title}

{formatDate(selectedGoal.target_date)} | Progres: {selectedGoal.progress_pct}%

{/* Progress slider */}
handleUpdateProgress(selectedGoal.id, parseInt(e.target.value))} className="w-full h-2 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-blue-600" />
{/* AI Action buttons */}
{/* Plan result */} {planResult && (

Vygenerovany plan ({planResult.tasks_created} ukolu vytvoreno)

{planResult.plan.weeks ? (
{(planResult.plan.weeks as Array<{ week_number: number; focus: string; tasks: Array<{ title: string; duration_hours?: number; day_of_week?: string }> }>).map((week, i) => (

Tyden {week.week_number}: {week.focus}

    {(week.tasks || []).map((t, j) => (
  • {t.title} {t.duration_hours && ({t.duration_hours}h)} {t.day_of_week && [{t.day_of_week}]}
  • ))}
))}
) : (
                  {JSON.stringify(planResult.plan, null, 2)}
                
)}
)} {/* AI Report */} {report && (

AI Report

{report.stats.done}/{report.stats.total} splneno ({report.stats.pct}%)

{report.report}

)} {/* Existing plan */} {selectedGoal.plan && Object.keys(selectedGoal.plan).length > 0 && !planResult && (

Ulozeny plan

{(selectedGoal.plan as Record).weeks ? (
{((selectedGoal.plan as Record).weeks as Array<{ week_number: number; focus: string; tasks: Array<{ title: string; duration_hours?: number; day_of_week?: string }> }>).map((week, i) => (

Tyden {week.week_number}: {week.focus}

    {(week.tasks || []).map((t, j) => (
  • {t.title}
  • ))}
))}
) : (
                  {JSON.stringify(selectedGoal.plan, null, 2)}
                
)}
)} {/* Related tasks */} {selectedGoal.tasks && selectedGoal.tasks.length > 0 && (

Souvisejici ukoly ({selectedGoal.tasks.length})

{(selectedGoal.tasks as Array<{ id: string; title: string; status: string }>).map((task) => (
{task.title} {task.status}
))}
)} {/* Delete button */}
)}
); }