'use client';

import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  useReactTable,
  getCoreRowModel,
  flexRender,
  createColumnHelper,
} from '@tanstack/react-table';
import { AppDispatch, RootState } from '@/store/store';
import { fetchStates } from '@/store/features/statesSlice';
import { fetchServices } from '@/store/features/servicesSlice';
import {  TrashIcon, PlayIcon } from '@heroicons/react/24/solid';
//import Link from 'next/link';
import axios from 'axios';
import toast, { Toaster } from 'react-hot-toast';
import Select, { MultiValue } from 'react-select';
import { getApiEndpoint } from '@/utils/api';

interface State {
  id: string;
  nom: string;
  createdBy: string;
  description: string;
}

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

interface ServiceOption {
  value: string;
  label: string;
}

const columnHelper = createColumnHelper<State>();

export default function StatesPage() {
  const dispatch = useDispatch<AppDispatch>();
  const { states, loading, error } = useSelector((state: RootState) => state.states);
  const { services } = useSelector((state: RootState) => state.services);
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [selectedServices, setSelectedServices] = useState<Service[]>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);

  useEffect(() => {
    console.log('States page mounted, fetching states and services...');
    dispatch(fetchStates());
    dispatch(fetchServices());
  }, [dispatch]);

  const handlePlayClick = () => {
    setIsPopupOpen(true);
  };

  const handleClosePopup = () => {
    setIsPopupOpen(false);
    setSelectedServices([]);
  };

  const generateRandomString = (length: number) => {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');
  };

  const generateRandomSeverity = () => {
    const severities = ['low', 'medium', 'high', 'critical'];
    return severities[Math.floor(Math.random() * severities.length)];
  };

  const createAlarm = async (serviceId: string, stateId: string) => {
    const alarmData = {
      identifiant: generateRandomString(8),
      hostname: generateRandomString(8),
      id_ticket: generateRandomString(8),
      description: `Random alarm description ${generateRandomString(5)}`,
      action: `Random action ${generateRandomString(5)}`,
      severity: generateRandomSeverity(),
      service_id:serviceId,
      state_id:stateId,
    };

    try {
      await axios.post(getApiEndpoint('alarms'), alarmData, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      });
    } catch (error) {
      console.error('Error creating alarm:', error);
      throw error;
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (selectedServices.length === 0) {
      toast.error('Veuillez sélectionner au moins un service', {
        duration: 4000,
        position: 'top-right',
        style: {
          background: '#EF4444',
          color: '#fff',
        },
      });
      return;
    }

    setIsSubmitting(true);
    try {
      const stateData = {
        nom: `État_${generateRandomString(6)}`,
        description: `Description aléatoire de l'état ${generateRandomString(8)}`,
      };

      const stateResponse = await axios.post(getApiEndpoint('states'), stateData, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
        },
      });

      const newStateId = stateResponse.data.id;

      await Promise.all(
        selectedServices.map(service => createAlarm(service.id, newStateId))
      );

      toast.success('État et alertes créés avec succès !', {
        duration: 4000,
        position: 'top-right',
        style: {
          background: '#10B981',
          color: '#fff',
        },
      });
      handleClosePopup();
      dispatch(fetchStates());
    } catch (error) {
      const errorMessage = axios.isAxiosError(error)
        ? error.response?.data?.message || 'Échec de la création de l\'état et des alertes'
        : 'Une erreur inattendue est survenue';
      toast.error(errorMessage, {
        duration: 4000,
        position: 'top-right',
        style: {
          background: '#EF4444',
          color: '#fff',
        },
      });
    } finally {
      setIsSubmitting(false);
    }
  };

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

  const columns = [
    columnHelper.accessor('nom', {
      header: 'Nom',
      cell: info => info.getValue(),
    }),
    columnHelper.accessor('description', {
      header: 'Description',
      cell: info => info.getValue(),
    }),
    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'état"
        >
          <TrashIcon className="h-5 w-5" />
        </button>
      ),
    }),
  ];

  const table = useReactTable({
    data: states || [],
    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">
        <div className="flex items-center space-x-4">
          <h1 className="text-2xl font-semibold">États</h1>
          <button
            onClick={handlePlayClick}
            className="inline-flex items-center px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors duration-200"
          >
            <PlayIcon className="h-5 w-5 mr-2" />
            Créer un état
          </button>
        </div>
        {/* <Link
          href="/admin/states/create"
          className="inline-flex items-center px-4 py-2 bg-blue-800 text-white rounded-md hover:bg-blue-900 transition-colors duration-200"
        >
          <PlusIcon className="h-5 w-5 mr-2" />
          Créer un état
        </Link> */}
      </div>

      {/* Popup Form */}
      {isPopupOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg p-6 w-full max-w-md">
            <h2 className="text-xl font-semibold mb-4">Créer un nouvel état</h2>
            <form onSubmit={handleSubmit}>
              <div className="mb-4">
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Services
                </label>
                <Select
                  isMulti
                  options={services?.map(service => ({
                    value: service.id,
                    label: service.name,
                  }))}
                  onChange={(selected: MultiValue<ServiceOption>) => {
                    setSelectedServices(
                      selected.map(option => ({
                        id: option.value,
                        name: option.label,
                      }))
                    );
                  }}
                  className="basic-multi-select"
                  classNamePrefix="select"
                />
              </div>
              <div className="flex justify-end space-x-4">
                <button
                  type="button"
                  onClick={handleClosePopup}
                  className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                >
                  Annuler
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? 'Création en cours...' : 'Créer'}
                </button>
              </div>
            </form>
          </div>
        </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>
  );
} 