import { useState } from 'react'

import { useRouter } from "next/router";
import axiosInstance from '../../src/axiosSecure';

import { TrashIcon } from "@heroicons/react/24/outline";



export default function LocationCard({ location }) {

  const router = useRouter();
  const [isCardVisible, setIsCardVisible] = useState(true);
  const handleDelete = async (id) => {
    try {
      console.log("card: deleting location = ", id, "url: ", `/locations/${id}`);
      const response = await axiosInstance.delete(`/api/data/locations/${id}`);
      if (response.status === 200) {
        document.getElementById(`location-card-${id}`).classList.add('cardFadeOut');
        setTimeout(() => setIsCardVisible(false), 300);
      }
    } catch (error) {
      console.log(JSON.stringify(error));
    }
  };

  return isCardVisible ? (
    <>
      <div
        id={`location-card-${location.id}`}
        className={`relative block p-6 max-w-sm rounded-lg border border-gray-200 shadow-md hover:bg-gray-100 dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700 mb-3 cursor-pointer ${location.isActive ? 'text-gray-900 dark:text-white font-bold' : 'text-gray-400 dark:text-gray-600'}`}
        onClick={() => router.push(`/cart/locations/edit/${location.id}`)}
      >
        <h5 className={`mb-2 text-2xl tracking-tight`}>
          {location.name} ({location.isActive ? "active" : "inactive"})
        </h5>
        <p className="font-normal text-gray-700 dark:text-gray-200">
          {location.address}
        </p>
        <div
          onClick={(e) => {
            e.stopPropagation(); // This should now work as expected
            handleDelete(location.id);
          }}
          className="absolute bottom-2 right-2 z-20"
        >
          <button
            aria-label="Изтрий местоположението"
            className="text-red-600 bg-transparent hover:bg-red-100 p-1 hover:border-red-700 rounded"
          >
            <TrashIcon className="h-6 w-6" />
          </button>
        </div>
      </div>
    </>
  ) : null;

}
