'use client';

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

interface Service {
  id: string;
  name: string;
  desc: string;
  groupId: string;
}


const columnHelper = createColumnHelper<Service>();

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

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

  useEffect(() => {
    if (services) {
      console.log('Services data:', services);
     // alert(JSON.stringify(services, null, 2));
    }
  }, [services]);

  const handleDelete = async (id: string) => {
    if (window.confirm('Êtes-vous sûr de vouloir supprimer ce service ?')) {
      try {
        await axios.delete(getApiEndpoint(`services/${id}`), {
          headers: {
            'Accept': 'application/json',
          },
        });
        toast.success('Service supprimé avec succès !', {
          duration: 4000,
          position: 'top-right',
          style: {
            background: '#10B981',
            color: '#fff',
          },
        });
        dispatch(fetchServices());
      } catch (error) {
        const errorMessage = axios.isAxiosError(error)
          ? error.response?.data?.message || 'Échec de la suppression du service'
          : 'Une erreur inattendue est survenue';
        toast.error(errorMessage, {
          duration: 4000,
          position: 'top-right',
          style: {
            background: '#EF4444',
            color: '#fff',
          },
        });
      }
    }
  };

  const columns = [
    columnHelper.accessor('name', {
      header: 'Nom',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('desc', {
      header: 'Description',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('groupId', {
      header: 'Groupe',
      cell: info => {
        const group = groups.find(g => g.id === info.getValue());
        return group?.name || '';
      },
    }),
    columnHelper.display({
      id: 'actions',
      header: 'Actions',
      cell: ({ row }) => (
        <button
          onClick={() => handleDelete(row.original.id)}
          className="text-red-600 hover:text-red-900 focus:outline-none"
          title="Supprimer le service"
        >
          <TrashIcon className="h-5 w-5" />
        </button>
      ),
    }),
  ];

  const table = useReactTable({
    data: services || [],
    columns: 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">Services</h1>
        <Link
          href="/admin/services/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 service
        </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>
  );
} 