'use client';

import React, { useState, useEffect } from 'react';
import { useSearchParams, useRouter } from 'next/navigation';
import Button from '@/components/Form/Button';
import GradeView from '@/components/Grades/GradeView';
import {
  fetchStudentCompetencies,
  editStudentCompetencies,
} from '@/app/actions/subscriptionAction';
import { Award, ArrowLeft } from 'lucide-react';
import logger from '@/utils/logger';
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.push('/admin/grades');
      })
      .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">
      <div className="flex items-center gap-3 mb-4">
        <button
          onClick={() => router.push('/admin/grades')}
          className="p-2 rounded hover:bg-gray-100 border border-gray-200 min-h-[44px] min-w-[44px] flex items-center justify-center transition-colors"
          aria-label="Retour à la fiche élève"
        >
          <ArrowLeft size={20} />
        </button>
        <h1 className="font-headline text-xl font-bold text-gray-800">Bilan de compétence</h1>
      </div>
      <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="Enregistrer" primary type="submit" />
          </div>
        </form>
      </div>
    </div>
  );
}
