'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 { fetchAlarms } from '@/store/features/alarmsSlice';
import { PlusIcon, TrashIcon } from '@heroicons/react/24/solid';
import Link from 'next/link';
import axios from 'axios';
import toast, { Toaster } from 'react-hot-toast';
import { getApiEndpoint } from '@/utils/api';

interface Alarm {
  id: string;
  identifiant: string;
  hostname: string;
  id_ticket: string;
  description: string;
  action: string;
  severity: string;
  serviceId: string;
  stateId: string;
  service?: {
    id: string;
    name: string;
  };
  state?: {
    id: string;
    nom: string;
  };
}

const columnHelper = createColumnHelper<Alarm>();

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

  useEffect(() => {
    console.log('Alarms page mounted, fetching alarms...');
    dispatch(fetchAlarms());
  }, [dispatch]);

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

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

  const columns = [
    columnHelper.accessor('identifiant', {
      header: 'Identifiant',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('hostname', {
      header: 'Nom d\'hôte',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('id_ticket', {
      header: 'ID Ticket',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('description', {
      header: 'Description',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('action', {
      header: 'Action',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('severity', {
      header: 'Sévérité',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('service', {
      header: 'Service',
      cell: info => info.getValue()?.name || 'Service inconnu',
    }),
    columnHelper.accessor('state', {
      header: 'État',
      cell: info => info.getValue()?.nom || 'État inconnu',
    }),
    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 l'alerte"
        >
          <TrashIcon className="h-5 w-5" />
        </button>
      ),
    }),
  ];

  const table = useReactTable({
    data: alarms || [],
    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">Alertes</h1>
        <Link
          href="/admin/alarms/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 une alerte
        </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>
  );
} 