'use client';
import React, { useState, useEffect } from 'react';
import { useTranslations } from 'next-intl';
import { Users, Clock, CalendarCheck, School, TrendingUp } from 'lucide-react';
import Loader from '@/components/Loader';
import ClasseDetails from '@/components/ClasseDetails';
import { fetchClasses } from '@/app/actions/schoolAction';
import StatCard from '@/components/StatCard';
import logger from '@/utils/logger';
import {
  fetchRegisterForms,
  fetchAbsences,
} from '@/app/actions/subscriptionAction';
import { fetchUpcomingEvents } from '@/app/actions/planningAction';
import { useEstablishment } from '@/context/EstablishmentContext';
import { useNotification } from '@/context/NotificationContext';
import Attendance from '@/components/Grades/Attendance';

// Composant EventCard pour afficher les événements
const EventCard = ({ title, date, description, type }) => (
  <div className="bg-stone-50 p-4 rounded-lg shadow-sm border border-gray-100 mb-4">
    <div className="flex items-center gap-3">
      <CalendarCheck className="text-blue-500" size={20} />
      <div>
        <h4 className="font-medium">{title}</h4>
        <p className="text-sm text-gray-500">{date}</p>
        <p className="text-sm mt-1">{description}</p>
      </div>
    </div>
  </div>
);

export default function DashboardPage() {
  const t = useTranslations('dashboard');
  const [isLoading, setIsLoading] = useState(false);
  const [totalStudents, setTotalStudents] = useState(0);
  const [pendingRegistration, setPendingRegistration] = useState(0);
  const [structureCapacity, setStructureCapacity] = useState(0);
  const [upcomingEvents, setUpcomingEvents] = useState([]);
  const [monthlyStats, setMonthlyStats] = useState({
    inscriptions: [],
    completionRate: 0,
  });

  const [classes, setClasses] = useState([]);
  const [absencesToday, setAbsencesToday] = useState([]);
  const { selectedEstablishmentId, selectedEstablishmentTotalCapacity } =
    useEstablishment();
  const { showNotification } = useNotification();

  useEffect(() => {
    if (!selectedEstablishmentId) return;

    setIsLoading(true); // Début du chargement

    // Fetch des classes
    fetchClasses(selectedEstablishmentId)
      .then((data) => {
        setClasses(data);
        logger.info('Classes fetched:', data);

        const nbMaxStudents = data.reduce(
          (acc, classe) => acc + classe.number_of_students,
          0
        );
        const nbStudents = data.reduce(
          (acc, classe) => acc + classe.students.length,
          0
        );
        setStructureCapacity(nbMaxStudents);
        setTotalStudents(nbStudents);
      })
      .catch((error) => {
        logger.error('Error fetching classes:', error);
        showNotification(
          'Error fetching classes: ' + error.message,
          'error',
          'Erreur'
        );
      });

    // Fetch des formulaires d'inscription
    fetchRegisterForms(selectedEstablishmentId)
      .then((data) => {
        logger.info('Pending registrations fetched:', data);
        setPendingRegistration(data.count);
      })
      .catch((error) => {
        logger.error('Error fetching pending registrations:', error);
      });

    // Fetch des événements à venir
    fetchUpcomingEvents(selectedEstablishmentId)
      .then((data) => {
        setUpcomingEvents(data);
      })
      .catch((error) => {
        logger.error('Error fetching upcoming events:', error);
      });

    // Fetch absences/retards du jour
    fetchAbsences(selectedEstablishmentId)
      .then((data) => {
        const today = new Date().toISOString().split('T')[0];
        const absToday = (data || []).filter((a) => a.day === today);
        // Mapping pour Attendance
        setAbsencesToday(
          absToday.map((a) => ({
            id: a.id,
            date: a.day,
            type: [1, 2].includes(a.reason) ? 'Absence' : 'Retard',
            justified: [1, 3].includes(a.reason),
            commentaire: a.commentaire,
            student_name: a.student_name,
          }))
        );
      })
      .catch((error) => {
        logger.error('Erreur lors du fetch des absences du jour:', error);
      })
      .finally(() => {
        setIsLoading(false); // Fin du chargement
      });
  }, [selectedEstablishmentId]);

  if (isLoading) return <Loader />;

  return (
    <div key={selectedEstablishmentId} className="p-6">
      <h1 className="text-2xl font-bold mb-6">{t('dashboard')}</h1>

      {/* Statistiques principales */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard
          title={t('totalStudents')}
          value={totalStudents}
          icon={<Users className="text-blue-500" size={24} />}
        />
        <StatCard
          title={t('pendingRegistrations')}
          value={`${pendingRegistration} `}
          icon={<Clock className="text-green-500" size={24} />}
          color="green"
        />
        <StatCard
          title={t('structureCapacity')}
          value={`${selectedEstablishmentTotalCapacity}`}
          icon={<School className="text-green-500" size={24} />}
          color="emerald"
        />
        <StatCard
          title={t('capacityRate')}
          value={`${((totalStudents / selectedEstablishmentTotalCapacity) * 100).toFixed(1)}%`}
          icon={<School className="text-orange-500" size={24} />}
          color="orange"
        />
      </div>

      {/* Événements et KPIs */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-6">
        {/* Graphique des inscriptions */}
        <div className="lg:col-span-2 bg-stone-50 p-6 rounded-lg shadow-sm border border-gray-100">
          <h2 className="text-lg font-semibold mb-4">
            {t('inscriptionTrends')}
          </h2>
          {/* Insérer ici un composant de graphique */}
          <div className="h-64 bg-gray-50 rounded flex items-center justify-center mb-6">
            <TrendingUp size={48} className="text-gray-300" />
          </div>
        </div>

        {/* Événements à venir */}
        <div className="bg-stone-50 p-6 rounded-lg shadow-sm border border-gray-100">
          <h2 className="text-lg font-semibold mb-4">{t('upcomingEvents')}</h2>
          {upcomingEvents.map((event, index) => (
            <EventCard key={index} {...event} />
          ))}
        </div>
      </div>

      {/* Ajout du composant Attendance en dessous, en lecture seule */}
      <Attendance absences={absencesToday} readOnly={true} />
    </div>
  );
}
