'use client'
import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Table from '@/components/Table';
import { Edit, Users } from 'lucide-react';
import StatusLabel from '@/components/StatusLabel';
import { FE_PARENTS_EDIT_INSCRIPTION_URL } from '@/utils/Url';
import { fetchChildren } from '@/app/actions/subscriptionAction';
import logger from '@/utils/logger';
import { useSession } from 'next-auth/react';
import { FE_USERS_LOGIN_URL } from '@/utils/Url';
import { useEstablishment } from '@/context/EstablishmentContext';

export default function ParentHomePage() {
  const [children, setChildren] = useState([]);
  const { data: session, status } = useSession();
  const [userId, setUserId] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [establishments, setEstablishments] = useState([]);
  const { selectedEstablishmentId, setSelectedEstablishmentId } = useEstablishment();

  const router = useRouter();

  useEffect(() => {
    if (status === 'loading') return;

    if (!session) {
      router.push(`${FE_USERS_LOGIN_URL}`);
    } else {
      const userIdFromSession = session.user.user_id;
      setUserId(userIdFromSession);

      const userEstablishments = session.user.roles.map(role => ({
        id: role.establishment__id,
        name: role.establishment__name,
        role_type: role.role_type
      }));
      setEstablishments(userEstablishments);

      if (!selectedEstablishmentId && userEstablishments.length > 0) {
        setSelectedEstablishmentId(userEstablishments[0].id);
      }

      fetchChildren(userIdFromSession, selectedEstablishmentId).then(data => {
        setChildren(data);
      });
    }
  }, [status, session, selectedEstablishmentId]);

  const handleEstablishmentChange = (e) => {
    const establishmentId = parseInt(e.target.value, 10);
    setSelectedEstablishmentId(establishmentId);
  };

  function handleEdit(eleveId) {
    // Logique pour éditer le dossier de l'élève
    logger.debug(`Edit dossier for student id: ${eleveId}`);
    router.push(`${FE_PARENTS_EDIT_INSCRIPTION_URL}?id=${userId}&studentId=${eleveId}`);
  }

  const actionColumns = [
    { name: 'Action', transform: (row) => row.action },
  ];

  const getShadowColor = (status) => {
    switch (status) {
      case 1:
        return 'shadow-blue-500'; // Couleur d'ombre plus visible
      case 2:
        return 'shadow-orange-500'; // Couleur d'ombre plus visible
      case 3:
        return 'shadow-purple-500'; // Couleur d'ombre plus visible
      case 4:
        return 'shadow-red-500'; // Couleur d'ombre plus visible
      case 5:
        return 'shadow-green-500'; // Couleur d'ombre plus visible
      case 6:
        return 'shadow-red-500'; // Couleur d'ombre plus visible
      default:
        return 'shadow-green-500'; // Couleur d'ombre plus visible
    }
  };

  // Définir les colonnes du tableau
  const childrenColumns = [
    { name: 'Nom', transform: (row) => `${row.student.last_name} ${row.student.first_name}` },
    {
      name: 'Statut',
      transform: (row) => (
        <div className="flex justify-center items-center">
          <StatusLabel status={row.status} showDropdown={false}/>
        </div>
      )
    },
    {
      name: 'Actions',
      transform: (row) => (
        <div className="flex justify-center">
          <button
            className="p-2 hover:bg-gray-100 rounded-full transition-colors"
            onClick={(e) => {
              e.stopPropagation();
              handleEdit(row.student.id);
            }}
            aria-label="Modifier"
          >
            <Edit className="h-5 w-5" />
          </button>
        </div>
      )
    }
  ];

  const itemsPerPage = 5;
  const totalPages = Math.ceil(children.length / itemsPerPage) || 1;

  const handlePageChange = (newPage) => {
    setCurrentPage(newPage);
  };

  return (
    <div className="px-2 py-4 md:px-4 max-w-full">
      <div>
        <h2 className="text-xl font-semibold mb-3 px-1 flex items-center gap-2">
          <Users className="h-6 w-6 text-emerald-600" />
          Enfants
        </h2>
        {establishments.length > 1 && (
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">Sélectionnez un établissement :</label>
            <select
              value={selectedEstablishmentId}
              onChange={handleEstablishmentChange}
              className="block w-full mt-1 p-2 border border-gray-300 rounded-md"
            >
              {establishments.map(establishment => (
                <option key={establishment.id} value={establishment.id}>
                  {establishment.name}
                </option>
              ))}
            </select>
          </div>
        )}
        <div className="overflow-x-auto">
          <Table
            data={children}
            columns={childrenColumns}
            itemsPerPage={itemsPerPage}
            currentPage={currentPage}
            totalPages={totalPages}
            onPageChange={handlePageChange}
            defaultTheme="bg-gray-50"
          />
        </div>
      </div>
    </div>
  );
}
