'use client';
import React, { useState, useEffect } from 'react';
import { Save, X, UserX, Trash2 } from 'lucide-react';
import Button from '@/components/Form/Button';
import CheckBox from '@/components/Form/CheckBox';
import { useNotification } from '@/context/NotificationContext';

export default function EvaluationGradeTable({
  evaluation,
  students,
  studentEvaluations,
  onSave,
  onClose,
  onDeleteGrade,
}) {
  const [grades, setGrades] = useState({});
  const [isSaving, setIsSaving] = useState(false);
  const { showNotification } = useNotification();

  // Initialiser les notes à partir des données existantes
  useEffect(() => {
    const initialGrades = {};
    students.forEach((student) => {
      const existingEval = studentEvaluations.find(
        (se) => se.student === student.id && se.evaluation === evaluation.id
      );
      initialGrades[student.id] = {
        score: existingEval?.score ?? '',
        comment: existingEval?.comment ?? '',
        is_absent: existingEval?.is_absent ?? false,
      };
    });
    setGrades(initialGrades);
  }, [students, studentEvaluations, evaluation]);

  const handleScoreChange = (studentId, value) => {
    const numValue = value === '' ? '' : parseFloat(value);
    if (value !== '' && (numValue < 0 || numValue > evaluation.max_score)) {
      return;
    }
    setGrades((prev) => ({
      ...prev,
      [studentId]: {
        ...prev[studentId],
        score: value,
        is_absent: false,
      },
    }));
  };

  const handleAbsentToggle = (studentId) => {
    setGrades((prev) => ({
      ...prev,
      [studentId]: {
        ...prev[studentId],
        is_absent: !prev[studentId]?.is_absent,
        score: !prev[studentId]?.is_absent ? '' : prev[studentId]?.score,
      },
    }));
  };

  const handleCommentChange = (studentId, value) => {
    setGrades((prev) => ({
      ...prev,
      [studentId]: {
        ...prev[studentId],
        comment: value,
      },
    }));
  };

  const handleSave = async () => {
    setIsSaving(true);
    try {
      const dataToSave = Object.entries(grades).map(([studentId, data]) => ({
        student_id: parseInt(studentId),
        evaluation_id: evaluation.id,
        score: data.score === '' ? null : parseFloat(data.score),
        comment: data.comment,
        is_absent: data.is_absent,
      }));

      await onSave(dataToSave);
      showNotification('Notes enregistrées avec succès', 'success', 'Succès');
    } catch (error) {
      showNotification('Erreur lors de la sauvegarde', 'error', 'Erreur');
    } finally {
      setIsSaving(false);
    }
  };

  // Calculer les statistiques
  const stats = React.useMemo(() => {
    const validScores = Object.values(grades)
      .filter((g) => g.score !== '' && !g.is_absent)
      .map((g) => parseFloat(g.score));

    if (validScores.length === 0) return null;

    const sum = validScores.reduce((a, b) => a + b, 0);
    const avg = sum / validScores.length;
    const min = Math.min(...validScores);
    const max = Math.max(...validScores);
    const absentCount = Object.values(grades).filter((g) => g.is_absent).length;

    return { avg, min, max, count: validScores.length, absentCount };
  }, [grades]);

  return (
    <div className="bg-white rounded-lg border border-gray-200 shadow-lg">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 bg-gray-50 rounded-t-lg">
        <div className="flex items-center justify-between">
          <div>
            <h3 className="font-headline font-semibold text-lg text-gray-800">
              {evaluation.name}
            </h3>
            <div className="text-sm text-gray-500 flex gap-3">
              <span>{evaluation.speciality_name}</span>
              <span>•</span>
              <span>Note max: {evaluation.max_score}</span>
              {evaluation.date && (
                <>
                  <span>•</span>
                  <span>
                    {new Date(evaluation.date).toLocaleDateString('fr-FR')}
                  </span>
                </>
              )}
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-200 rounded-full"
          >
            <X size={20} className="text-gray-500" />
          </button>
        </div>
      </div>

      {/* Table */}
      <div className="overflow-x-auto max-h-[60vh]">
        <table className="min-w-full">
          <thead className="bg-gray-50 sticky top-0">
            <tr>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">
                Élève
              </th>
              <th className="px-4 py-3 text-center text-sm font-medium text-gray-600 w-32">
                Note / {evaluation.max_score}
              </th>
              <th className="px-4 py-3 text-center text-sm font-medium text-gray-600 w-24">
                Absent
              </th>
              <th className="px-4 py-3 text-left text-sm font-medium text-gray-600">
                Commentaire
              </th>
              {onDeleteGrade && (
                <th className="px-4 py-3 text-center text-sm font-medium text-gray-600 w-20">
                  Actions
                </th>
              )}
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-100">
            {students.map((student) => {
              const studentGrade = grades[student.id] || {};
              const isAbsent = studentGrade.is_absent;
              const existingEval = studentEvaluations.find(
                (se) => se.student === student.id && se.evaluation === evaluation.id
              );

              return (
                <tr
                  key={student.id}
                  className={`hover:bg-gray-50 ${isAbsent ? 'bg-red-50' : ''}`}
                >
                  <td className="px-4 py-3">
                    <div className="font-medium text-gray-800">
                      {student.last_name} {student.first_name}
                    </div>
                  </td>
                  <td className="px-4 py-3 text-center">
                    <input
                      type="number"
                      step="0.5"
                      min="0"
                      max={evaluation.max_score}
                      value={studentGrade.score ?? ''}
                      onChange={(e) =>
                        handleScoreChange(student.id, e.target.value)
                      }
                      disabled={isAbsent}
                      className={`w-20 px-2 py-1 text-center border rounded focus:ring-2 focus:ring-primary focus:border-primary ${
                        isAbsent
                          ? 'bg-gray-100 text-gray-400 cursor-not-allowed'
                          : 'border-gray-300'
                      }`}
                    />
                  </td>
                  <td className="px-4 py-3 text-center">
                    <button
                      onClick={() => handleAbsentToggle(student.id)}
                      className={`p-2 rounded ${
                        isAbsent
                          ? 'bg-red-100 text-red-600'
                          : 'bg-gray-100 text-gray-400 hover:bg-gray-200'
                      }`}
                      title={isAbsent ? 'Marquer présent' : 'Marquer absent'}
                    >
                      <UserX size={18} />
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <input
                      type="text"
                      value={studentGrade.comment ?? ''}
                      onChange={(e) =>
                        handleCommentChange(student.id, e.target.value)
                      }
                      placeholder="Commentaire..."
                      className="w-full px-2 py-1 border border-gray-300 rounded focus:ring-2 focus:ring-primary focus:border-primary"
                    />
                  </td>
                  {onDeleteGrade && (
                    <td className="px-4 py-3 text-center">
                      {existingEval && (
                        <button
                          onClick={() => {
                            if (confirm('Supprimer cette note ?')) {
                              onDeleteGrade(existingEval.id);
                              setGrades((prev) => ({
                                ...prev,
                                [student.id]: { score: '', comment: '', is_absent: false },
                              }));
                            }
                          }}
                          className="p-2 text-red-600 hover:bg-red-50 rounded"
                          title="Supprimer la note"
                        >
                          <Trash2 size={18} />
                        </button>
                      )}
                    </td>
                  )}
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Footer avec statistiques et boutons */}
      <div className="p-4 border-t border-gray-200 bg-gray-50 rounded-b-lg">
        <div className="flex items-center justify-between">
          {/* Statistiques */}
          {stats && (
            <div className="flex gap-4 text-sm text-gray-600">
              <span>
                Moyenne:{' '}
                <span className="font-semibold text-primary">
                  {stats.avg.toFixed(2)}
                </span>
              </span>
              <span>
                Min:{' '}
                <span className="font-semibold text-red-600">{stats.min}</span>
              </span>
              <span>
                Max:{' '}
                <span className="font-semibold text-green-600">{stats.max}</span>
              </span>
              <span>
                Notés: {stats.count}/{students.length}
              </span>
              {stats.absentCount > 0 && (
                <span className="text-red-600">
                  Absents: {stats.absentCount}
                </span>
              )}
            </div>
          )}

          {/* Boutons */}
          <div className="flex gap-2">
            <Button text="Fermer" onClick={onClose} />
            <Button
              primary
              text={isSaving ? 'Enregistrement...' : 'Enregistrer'}
              icon={<Save size={16} />}
              onClick={handleSave}
              disabled={isSaving}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
