'use client';

import React, { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Button from '@/components/Button';
import GradeView from '@/components/Grades/GradeView';
import {
  fetchStudentCompetencies,
  editStudentCompetencies,
} from '@/app/actions/subscriptionAction';
import SectionHeader from '@/components/SectionHeader';
import { Award } from 'lucide-react';
import { useCsrfToken } from '@/context/CsrfContext';
import { useNotification } from '@/context/NotificationContext';

export default function StudentCompetenciesPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const csrfToken = useCsrfToken();
  const { showNotification } = useNotification();
  const [studentCompetencies, setStudentCompetencies] = useState([]);
  const [grades, setGrades] = useState({});
  const studentId = searchParams.get('studentId');
  const period = searchParams.get('period');

  useEffect(() => {
    fetchStudentCompetencies(studentId, period)
      .then((data) => {
        setStudentCompetencies(data);
      })
      .catch((error) =>
        logger.error('Error fetching studentCompetencies:', error)
      );
  }, []);

  useEffect(() => {
    if (studentCompetencies.data) {
      const initialGrades = {};
      studentCompetencies.data.forEach((domaine) => {
        domaine.categories.forEach((cat) => {
          cat.competences.forEach((comp) => {
            initialGrades[comp.competence_id] = comp.score ?? 0;
          });
        });
      });
      setGrades(initialGrades);
    }
  }, [studentCompetencies.data]);

  const handleGradeChange = (competenceId, level) => {
    setGrades((prev) => ({
      ...prev,
      [competenceId]: level,
    }));
  };

  const handleSubmit = () => {
    const data = Object.entries(grades)
      .filter(([_, score]) => [1, 2, 3].includes(score))
      .map(([competenceId, score]) => ({
        studentId,
        competenceId,
        grade: score,
        period: period,
      }));
    editStudentCompetencies(data, csrfToken)
      .then(() => {
        showNotification(
          'Bilan de compétence sauvegardé avec succès',
          'success',
          'Succès'
        );
        router.back();
      })
      .catch((error) => {
        showNotification(
          "Erreur lors de l'enregistrement du bilan de compétence",
          'error',
          'Erreur'
        );
      });
  };

  return (
    <div className="h-full flex flex-col p-4">
      <SectionHeader
        icon={Award}
        title="Bilan de compétence"
        description="Evaluez les compétence de l'élève"
      />
      <div className="flex-1 min-h-0 flex flex-col">
        <form
          className="flex-1 min-h-0 flex flex-col"
          onSubmit={(e) => {
            e.preventDefault();
            handleSubmit();
          }}
        >
          {/* Zone scrollable pour les compétences */}
          <div className="flex-1 min-h-0 overflow-y-auto">
            <GradeView
              data={studentCompetencies.data}
              grades={grades}
              onGradeChange={handleGradeChange}
            />
          </div>
          <div className="mt-6 flex justify-end">
            <Button
              text="Retour"
              type="button"
              onClick={(e) => {
                e.preventDefault();
                router.back();
              }}
              className="mr-2 bg-gray-200 text-gray-700 hover:bg-gray-300"
            />
            <Button text="Enregistrer" primary type="submit" />
          </div>
        </form>
      </div>
    </div>
  );
}
