import BotonAdd from '@/Components/BotonAdd';
import ModalAñadirCancion from '@/Components/ModalAñadirCancion';
import ModalEditarCancion from '@/Components/ModalEditarCancion';
import ModalRemoveCancion from '@/Components/ModalRemoveCancion';
import Authenticated from '@/Layouts/AuthenticatedLayout';
import { Cancion } from '@/types/types';
import { Head, router } from '@inertiajs/react';
import axios from 'axios';
import { FormEvent, useEffect, useState } from 'react';

export default function Index({ songs }: { songs: Cancion[] }) {
  const [showaddmodal, setshowmodal] = useState(false);
  const [showRemove, setRemove] = useState(false);
  const [showEdit, setEdit] = useState(false);
  const [selcan, setcan] = useState<Cancion>({} as Cancion);

  useEffect(() => {
    const handleKeyPress = (event: KeyboardEvent) => {
      if (event.ctrlKey && event.key === 'k') {
        event.preventDefault();
        setshowmodal(true);
      }
    };

    window.addEventListener('keydown', handleKeyPress);

    return () => {
      window.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

  function addcancion(event: FormEvent<HTMLFormElement>): void {
    event.preventDefault();

    const formData = new FormData(event.currentTarget);

    axios
      .post('/canciones', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      })
      .then((response: { data: string }) => {
        console.log('Song added successfully', response.data);
        window.location.reload();
      })
      .catch(() => {
        setshowmodal(false);
      });
  }

  function handleRemove(e: FormEvent) {
    e.preventDefault();
    axios
      .delete(`/canciones/${selcan.id}`)
      .then(() => {
        setcan({} as Cancion);
        setRemove(false);
        window.location.reload();
      })
      .catch((error) => {
        console.error('Error removing song:', error);
        setRemove(false);
      });
  }

  function handleUpdate(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    const formData = new FormData(event.currentTarget);
    const title = formData.get('title');
    const artist = formData.get('artist');

    axios
      .put(`/canciones/${selcan.id}`, {
        title: title,
        artist: artist,
      })
      .then(() => {
        setEdit(false);
        router.reload();
      })
      .catch((error) => {
        console.error('Error actualizando datos de la cancion', error);
        setEdit(false);
      });
  }

  return (
    <Authenticated
      header={
        <h2 className="text-xl font-semibold leading-tight text-gray-800 dark:text-gray-200">
          Crud Canciones
        </h2>
      }
    >
      <Head title="Canciones" />
      <div className="container">
        {songs.data.length === 0 ? (
          <p className="mt-4 w-full text-center text-xl text-gray-500 dark:text-gray-300">
            No hay canciones cargadas para tu usuario. Quiere Añadir una? Aprete{' '}
            <br className="mb-2" />
            <kbd className="rounded-md border bg-teal-950">Ctrl</kbd> +{' '}
            <kbd className="rounded-md border bg-teal-950">k</kbd>
          </p>
        ) : (
          <div className="mx-4 flex w-full justify-center overflow-x-scroll">
            <table className="mx-auto mt-2 table w-full">
              <thead>
                <tr className="border-b bg-gray-50 text-center text-sm font-semibold uppercase tracking-wider text-gray-700 dark:bg-gray-700 dark:text-gray-400">
                  <th className="px-6 py-3">Nombre</th>
                  <th className="px-6 py-3">Artista</th>
                  <th className="px-6 py-3">path</th>
                  <th className="px-6 py-3">Acciones</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200 bg-white dark:divide-gray-700 dark:bg-gray-800">
                {songs.data.map((song: Cancion) => (
                  <tr
                    key={song.id}
                    className="hover:bg-gray-50 dark:hover:bg-gray-700"
                  >
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900 dark:text-gray-200">
                      {song.title}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900 dark:text-gray-200">
                      {song.artist}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-900 dark:text-gray-200">
                      {song.path}
                    </td>
                    <td className="whitespace-nowrap px-6 py-4 text-sm">
                      <button
                        className="mr-2 rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700"
                        onClick={() => {
                          setcan(song);
                          setEdit(true);
                        }}
                      >
                        Editar
                      </button>
                      <button
                        className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700"
                        onClick={() => {
                          setcan(song);
                          setRemove(true);
                        }}
                      >
                        Eliminar
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
        <BotonAdd show={true} setshow={setshowmodal} />
        <ModalAñadirCancion
          showaddmodal={showaddmodal}
          addcancion={addcancion}
          setShowaddmodal={setshowmodal}
        />
        <ModalRemoveCancion
          show={showRemove}
          close={setRemove}
          cancion={selcan}
          remove={handleRemove}
        />
        <ModalEditarCancion
          song={selcan}
          showEditModal={showEdit}
          setShowEditModal={setEdit}
          UpdateCallback={handleUpdate}
        />
      </div>
    </Authenticated>
  );
}
