'use client';
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Table from '@/components/Table';
import {
  Edit3,
  Users,
  Download,
  Eye,
  Upload,
  CalendarDays,
} from 'lucide-react';
import StatusLabel from '@/components/StatusLabel';
import FileUpload from '@/components/FileUpload';
import { FE_PARENTS_EDIT_SUBSCRIPTION_URL } from '@/utils/Url';
import {
  fetchChildren,
  editRegisterForm,
} from '@/app/actions/subscriptionAction';
import { fetchUpcomingEvents } from '@/app/actions/planningAction';
import logger from '@/utils/logger';
import { BASE_URL } from '@/utils/Url';
import { useEstablishment } from '@/context/EstablishmentContext';
import { useCsrfToken } from '@/context/CsrfContext';
import { useClasses } from '@/context/ClassesContext';
import { PlanningProvider, PlanningModes } from '@/context/PlanningContext';
import SectionHeader from '@/components/SectionHeader';
import ParentPlanningSection from '@/components/ParentPlanningSection';
import EventCard from '@/components/EventCard';

export default function ParentHomePage() {
  const [children, setChildren] = useState([]);
  const { user, selectedEstablishmentId } = useEstablishment();
  const [uploadingStudentId, setUploadingStudentId] = useState(null); // ID de l'étudiant pour l'upload
  const [uploadedFile, setUploadedFile] = useState(null); // Fichier uploadé
  const [uploadState, setUploadState] = useState('off'); // État "on" ou "off" pour l'affichage du composant
  const [showPlanning, setShowPlanning] = useState(false);
  const [planningClassName, setPlanningClassName] = useState(null);
  const [upcomingEvents, setUpcomingEvents] = useState([]);
  const router = useRouter();
  const csrfToken = useCsrfToken();
  const [reloadFetch, setReloadFetch] = useState(false);
  const { getNiveauLabel } = useClasses();

  useEffect(() => {
    if (user !== null) {
      const userIdFromSession = user.user_id;
      fetchChildren(userIdFromSession, selectedEstablishmentId).then((data) => {
        setChildren(data);
      });
      setReloadFetch(false);
    }
  }, [selectedEstablishmentId, reloadFetch, user]);

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

  function handleView(eleveId) {
    logger.debug(`View dossier for student id: ${eleveId}`);
    router.push(
      `${FE_PARENTS_EDIT_SUBSCRIPTION_URL}?studentId=${eleveId}&enabled=false`
    );
  }

  function handleEdit(eleveId) {
    logger.debug(`Edit dossier for student id: ${eleveId}`);
    router.push(
      `${FE_PARENTS_EDIT_SUBSCRIPTION_URL}?studentId=${eleveId}&enabled=true`
    );
  }

  const handleFileUpload = (file) => {
    if (!file) {
      logger.error("Aucun fichier sélectionné pour l'upload.");
      return;
    }
    setUploadedFile(file); // Conserve le fichier en mémoire
    logger.debug('Fichier sélectionné :', file.name);
  };

  const handleSubmit = () => {
    if (!uploadedFile || !uploadingStudentId) {
      logger.error('Aucun fichier ou étudiant sélectionné.');
      return;
    }

    const jsonData = {
      status: 3,
    };
    const formData = new FormData();
    formData.append('data', JSON.stringify(jsonData));
    formData.append('sepa_file', uploadedFile); // Ajoute le fichier SEPA

    editRegisterForm(uploadingStudentId, formData, csrfToken)
      .then((response) => {
        logger.debug('RF mis à jour avec succès:', response);
        setReloadFetch(true);
        setUploadState('off');
      })
      .catch((error) => {
        logger.error('Erreur lors de la mise à jour du RF:', error);
      });
  };

  const toggleUpload = (studentId) => {
    if (uploadingStudentId === studentId && uploadState === 'on') {
      // Si le composant est déjà affiché pour cet étudiant, on le masque
      setUploadState('off');
      setUploadingStudentId(null);
      setUploadedFile(null); // Réinitialise le fichier
    } else {
      // Sinon, on l'affiche pour cet étudiant
      setUploadState('on');
      setUploadingStudentId(studentId);
    }
  };

  const showClassPlanning = (student) => {
    setPlanningClassName(
      `${student.associated_class_name} - ${getNiveauLabel(student.level)}`
    );
    setShowPlanning(true);
  };

  const childrenColumns = [
    {
      name: 'photo',
      transform: (row) => (
        <div className="flex justify-center items-center">
          {row.student.photo ? (
            <a
              href={`${BASE_URL}${row.student.photo}`} // Lien vers la photo
              target="_blank"
              rel="noopener noreferrer"
            >
              <img
                src={`${BASE_URL}${row.student.photo}`}
                alt={`${row.student.first_name} ${row.student.last_name}`}
                className="w-10 h-10 object-cover transition-transform duration-200 hover:scale-125 cursor-pointer rounded-full"
              />
            </a>
          ) : (
            <div className="w-10 h-10 flex items-center justify-center bg-gray-200 rounded-full">
              <span className="text-gray-500 text-sm font-semibold">
                {row.student.first_name[0]}
                {row.student.last_name[0]}
              </span>
            </div>
          )}
        </div>
      ),
    },
    { name: 'Nom', transform: (row) => `${row.student.last_name}` },
    { name: 'Prénom', transform: (row) => `${row.student.first_name}` },
    {
      name: 'Classe',
      transform: (row) => (
        <div className="text-center">{row.student.associated_class_name}</div>
      ),
    },
    {
      name: 'Niveau',
      transform: (row) => (
        <div className="text-center">{getNiveauLabel(row.student.level)}</div>
      ),
    },
    {
      name: 'Statut',
      transform: (row) => (
        <div className="flex justify-center items-center">
          <StatusLabel status={row.status} showDropdown={false} parent />
        </div>
      ),
    },
    {
      name: 'Actions',
      transform: (row) => (
        <div className="flex justify-center items-center gap-2">
          {row.status === 2 && (
            <button
              className="text-blue-500 hover:text-blue-700"
              onClick={(e) => {
                e.stopPropagation();
                handleEdit(row.student.id);
              }}
              aria-label="Remplir le dossier"
            >
              <Edit3 className="h-5 w-5" />
            </button>
          )}

          {(row.status === 3 || row.status === 8) && (
            <button
              className="text-purple-500 hover:text-purple-700"
              onClick={(e) => {
                e.stopPropagation();
                handleView(row.student.id);
              }}
              aria-label="Visualiser le dossier"
            >
              <Eye className="h-5 w-5" />
            </button>
          )}

          {row.status === 7 && (
            <>
              <button
                className="flex items-center justify-center w-8 h-8 rounded-full text-purple-500 hover:text-purple-700"
                onClick={(e) => {
                  e.stopPropagation();
                  handleView(row.student.id);
                }}
                aria-label="Visualiser le dossier"
              >
                <Eye className="h-5 w-5" />
              </button>
              <a
                href={`${BASE_URL}${row.sepa_file}`}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center justify-center w-8 h-8 rounded-full text-green-500 hover:text-green-700"
                aria-label="Télécharger le mandat SEPA"
              >
                <Download className="h-5 w-5" />
              </a>
              <button
                className={`flex items-center justify-center w-8 h-8 rounded-full ${
                  uploadingStudentId === row.student.id && uploadState === 'on'
                    ? 'bg-blue-100 text-blue-600 ring-3 ring-blue-500'
                    : 'text-blue-500 hover:text-blue-700'
                }`}
                onClick={(e) => {
                  e.stopPropagation();
                  toggleUpload(row.student.id);
                }}
                aria-label="Uploader un fichier"
              >
                <Upload className="h-5 w-5" />
              </button>
            </>
          )}

          {row.status === 5 && (
            <>
              <button
                className="text-purple-500 hover:text-purple-700"
                onClick={(e) => {
                  e.stopPropagation();
                  handleView(row.student.id);
                }}
                aria-label="Visualiser le dossier"
              >
                <Eye className="h-5 w-5" />
              </button>
              <button
                className="text-emerald-500 hover:text-emerald-700 ml-1"
                onClick={(e) => {
                  e.stopPropagation();
                  showClassPlanning(row.student);
                }}
                aria-label="Voir le planning de la classe"
              >
                <CalendarDays className="h-5 w-5" />
              </button>
            </>
          )}
        </div>
      ),
    },
  ];

  return (
    <div className="w-full h-full">
      {showPlanning && planningClassName ? (
        // Affichage grand format mais respectant la sidebar
        <>
          <div className="p-4 flex items-center border-b">
            <button
              className="text-emerald-600 hover:text-emerald-800 font-semibold flex items-center"
              onClick={() => setShowPlanning(false)}
            >
              ← Retour
            </button>
          </div>
          <div className="flex-1 flex overflow-hidden">
            <PlanningProvider
              establishmentId={selectedEstablishmentId}
              modeSet={PlanningModes.CLASS_SCHEDULE}
              readOnly={true}
            >
              <ParentPlanningSection planningClassName={planningClassName} />
            </PlanningProvider>
          </div>
        </>
      ) : (
        // Affichage classique avec le tableau des enfants
        <div>
          {/* Section des événements à venir */}
          {upcomingEvents.length > 0 && (
            <div className="mb-6">
              <SectionHeader
                icon={CalendarDays}
                title="Événements à venir"
                description="Prochains événements de l'établissement"
              />
              <div className="bg-stone-50 p-4 rounded-lg shadow-sm border border-gray-100">
                {upcomingEvents.slice(0, 3).map((event, index) => (
                  <EventCard key={index} {...event} />
                ))}
              </div>
            </div>
          )}

          <SectionHeader
            icon={Users}
            title="Vos enfants"
            description="Suivez le parcours de vos enfants"
          />
          <div className="overflow-x-auto">
            <Table data={children} columns={childrenColumns} />
          </div>
          {/* Composant FileUpload et bouton Valider en dessous du tableau */}
          {uploadState === 'on' && uploadingStudentId && (
            <div className="mt-4">
              <FileUpload
                selectionMessage="Sélectionnez un fichier à uploader"
                onFileSelect={handleFileUpload}
              />
              <button
                className={`mt-4 px-6 py-2 rounded-md ${
                  uploadedFile
                    ? 'bg-emerald-500 text-white hover:bg-emerald-600'
                    : 'bg-gray-300 text-gray-700 cursor-not-allowed'
                }`}
                onClick={handleSubmit}
                disabled={!uploadedFile}
              >
                Valider
              </button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
