'use client';

import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  useReactTable,
  getCoreRowModel,
  flexRender,
  createColumnHelper,
} from '@tanstack/react-table';
import { AppDispatch, RootState } from '@/store/store';
import { fetchGroups } from '@/store/features/groupsSlice';
import { PlusIcon, TrashIcon } from '@heroicons/react/24/solid';
import Link from 'next/link';
import axios from 'axios';
import toast, { Toaster } from 'react-hot-toast';

interface Group {
  id: string;
  name: string;
  description: string;
}

const columnHelper = createColumnHelper<Group>();

const columns = [
  columnHelper.accessor('id', {
    header: 'ID',
    cell: info => info.getValue(),
  }),
  columnHelper.accessor('name', {
    header: 'Nom',
    cell: info => info.getValue(),
  }),
  columnHelper.accessor('description', {
    header: 'Description',
    cell: info => info.getValue(),
  }),
  columnHelper.display({
    id: 'actions',
    header: 'Actions',
    cell: ({ row }) => {
      const handleDelete = async () => {
        if (window.confirm('Êtes-vous sûr de vouloir supprimer ce groupe ?')) {
          try {
            await axios.delete(`http://127.0.0.1:8000/api/groups/${row.original.id}`, {
              headers: {
                'Accept': 'application/json',
              },
            });
            toast.success('Groupe supprimé avec succès !', {
              duration: 4000,
              position: 'top-right',
              style: {
                background: '#10B981',
                color: '#fff',
              },
            });
            // Refresh the groups list
            dispatch(fetchGroups());
          } catch (error) {
            const errorMessage = axios.isAxiosError(error)
              ? error.response?.data?.message || 'Échec de la suppression du groupe'
              : 'Une erreur inattendue est survenue';
            toast.error(errorMessage, {
              duration: 4000,
              position: 'top-right',
              style: {
                background: '#EF4444',
                color: '#fff',
              },
            });
          }
        }
      };

      return (
        <button
          onClick={handleDelete}
          className="text-red-600 hover:text-red-900 focus:outline-none"
          title="Supprimer le groupe"
        >
          <TrashIcon className="h-5 w-5" />
        </button>
      );
    },
  }),
];

export default function GroupsPage() {
  const dispatch = useDispatch<AppDispatch>();
  const { groups, loading, error } = useSelector((state: RootState) => state.groups);

  useEffect(() => {
    console.log('Groups page mounted, fetching groups...');
    dispatch(fetchGroups());
  }, [dispatch]);

  const table = useReactTable({
    data: groups || [],
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-lg">Chargement...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-lg text-red-600">Erreur : {error}</div>
      </div>
    );
  }

  return (
    <div className="p-6">
      <Toaster />
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-semibold">Groupes</h1>
        <Link
          href="/admin/groups/create"
          className="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors duration-200"
        >
          <PlusIcon className="h-5 w-5 mr-2" />
          Créer un groupe
        </Link>
      </div>
      <div className="bg-white shadow-md rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              {table.getHeaderGroups().map(headerGroup => (
                <tr key={headerGroup.id}>
                  {headerGroup.headers.map(header => (
                    <th
                      key={header.id}
                      className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                    >
                      {flexRender(
                        header.column.columnDef.header,
                        header.getContext()
                      )}
                    </th>
                  ))}
                </tr>
              ))}
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {table.getRowModel().rows.map(row => (
                <tr key={row.id}>
                  {row.getVisibleCells().map(cell => (
                    <td
                      key={cell.id}
                      className="px-6 py-4 whitespace-nowrap text-sm text-gray-500"
                    >
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
} 