"use client" import { useEffect, useMemo, useState } from 'react' import { useRouter } from 'next/navigation' import { api } from '@/lib/api' import { getCurrentPersianYear } from '@/lib/date/persian-date' import { Calendar as CalendarIcon, Database, TrendingUp } from 'lucide-react' import Loading from '@/components/Loading' import { Card } from '@/components/common' import { YearSelector } from '@/components/calendar' import { MonthCard } from '@/components/cards' import { StatsCard } from '@/components/cards' import { AppShell } from '@/components/layout' const monthNames = ['فروردین', 'اردیبهشت', 'خرداد', 'تیر', 'مرداد', 'شهریور', 'مهر', 'آبان', 'آذر', 'دی', 'بهمن', 'اسفند'] function useQueryParam(name: string) { const [value, setValue] = useState(null) useEffect(() => { if (typeof window !== 'undefined') { const params = new URLSearchParams(window.location.search) setValue(params.get(name)) } }, [name]) return value } export default function CalendarPage() { const router = useRouter() const deviceIdParam = useQueryParam('deviceId') const [deviceId, setDeviceId] = useState(1) const [year, setYear] = useState(getCurrentPersianYear()) const [activeMonths, setActiveMonths] = useState([]) const [monthDays, setMonthDays] = useState>({}) const [loading, setLoading] = useState(true) const years = useMemo(() => Array.from({ length: 10 }, (_, i) => getCurrentPersianYear() - 2 + i), []) // وقتی deviceIdParam تغییر کرد، deviceId را به روز کن useEffect(() => { if (deviceIdParam) { setDeviceId(Number(deviceIdParam)) } }, [deviceIdParam]) useEffect(() => { let mounted = true setMonthDays({}) setActiveMonths([]) setLoading(true) api.activeMonths(deviceId, year) .then(async (months) => { if (!mounted) return setActiveMonths(months) const entries = await Promise.all(months.map(async m => { const days = await api.monthDays(deviceId, year, m) const records = days.reduce((s, d) => s + d.count, 0) return [m, { days: days.length, records }] as const })) if (!mounted) return setMonthDays(Object.fromEntries(entries)) }) .catch(console.error) .finally(() => { if (mounted) setLoading(false) }) return () => { mounted = false } }, [deviceId, year]) const totalDays = useMemo(() => Object.values(monthDays).reduce((s, v) => s + (v?.days ?? 0), 0), [monthDays]) const totalRecords = useMemo(() => Object.values(monthDays).reduce((s, v) => s + (v?.records ?? 0), 0), [monthDays]) if (loading) { return } return (
{/* Main Card */} {/* Year Selector */} {/* Summary Stats */}
{/* Months Grid */}
{monthNames.map((name, idx) => { const m = idx + 1 const isActive = activeMonths.includes(m) const stats = monthDays[m] return ( isActive && router.replace(`/day-details?deviceId=${deviceId}&year=${year}&month=${m}`)} /> ) })}
) }