import { useEffect, useMemo, useState } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { getAllImagesByNoticeId, getNoticeById } from "../api/notices";
import { useAuthStore } from "../store/authStore";
import { useNoticesStore } from "../store/noticesStore";

export default function NoticeDetails() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user_id } = useAuthStore();
  const { notices, deleteNotice, fetchNotices } = useNoticesStore();
  const [notice, setNotice] = useState(null);
  const [images, setImages] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isImagesLoading, setIsImagesLoading] = useState(true);

  useEffect(() => {
    let isMounted = true;

    const loadNotice = async () => {
      setIsLoading(true);
      try {
        let found = notices.find((item) => String(item.noticeId) === String(id));
        if (!found) {
          found = await getNoticeById(id);
        }
        if (isMounted) {
          setNotice(found);
        }
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    const loadImages = async () => {
      setIsImagesLoading(true);
      try {
        const imageUrls = await getAllImagesByNoticeId(id);
        if (isMounted) {
          setImages(imageUrls);
        } else {
          imageUrls.forEach((imageUrl) => {
            if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) {
              URL.revokeObjectURL(imageUrl);
            }
          });
        }
      } finally {
        if (isMounted) {
          setIsImagesLoading(false);
        }
      }
    };

    loadNotice();
    loadImages();

    return () => {
      isMounted = false;
    };
  }, [id, notices]);

  useEffect(() => {
    return () => {
      images.forEach((imageUrl) => {
        if (typeof imageUrl === "string" && imageUrl.startsWith("blob:")) {
          URL.revokeObjectURL(imageUrl);
        }
      });
    };
  }, [images]);

  const isOwner = useMemo(() => {
    if (!notice) {
      return false;
    }
    return String(notice.clientId) === String(user_id);
  }, [notice, user_id]);

  const handleDelete = async () => {
    const confirmed = window.confirm("Usunac ogloszenie?");
    if (!confirmed) {
      return;
    }

    await deleteNotice(Number(id));
    await fetchNotices();
    navigate("/dashboard/my-notices");
  };

  if (isLoading) {
    return (
      <div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
        Ladowanie ogloszenia...
      </div>
    );
  }

  if (!notice) {
    return (
      <div className="rounded-lg border border-gray-200 bg-white p-8 text-center text-sm text-gray-600">
        Nie znaleziono ogloszenia.
      </div>
    );
  }

  return (
    <section className="space-y-5">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">{notice.title}</h1>
          <p className="text-sm text-gray-500">{notice.category}</p>
        </div>
       
      </div>

      <div className="grid gap-3 sm:grid-cols-2">
        {isImagesLoading ? (
          <div className="flex aspect-4/3 w-full items-center justify-center rounded-lg border border-gray-200 bg-gray-100 sm:col-span-2">
            <span
              aria-label="Loading images"
              className="h-8 w-8 animate-spin rounded-full border-4 border-gray-300 border-t-primary"
              role="status"
            />
          </div>
        ) : images.length > 0 ? (
          images.map((image, index) => (
            <img
              alt={`${notice.title} ${index + 1}`}
              className="aspect-4/3 w-full rounded-lg border border-gray-200 bg-gray-100 object-cover"
              key={`${image}-${index}`}
              src={image}
            />
          ))
        ) : (
          <div className="flex aspect-4/3 w-full items-center justify-center rounded-lg border border-gray-200 bg-gray-100 sm:col-span-2">
            <span className="rounded-md bg-gray-200 px-3 py-1 text-sm font-medium text-gray-600">
              No Image
            </span>
          </div>
        )}
           <div className="rounded-lg border border-gray-200 bg-white p-4">
        <h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-gray-500">Opis</h2>
        <p className="whitespace-pre-wrap text-gray-700">{notice.description}</p>
         <span className="text-2xl font-bold text-primary">{notice.price} zl</span>
      </div>
      </div>


      {Array.isArray(notice.attributes) && notice.attributes.length > 0 ? (
        <div className="rounded-lg border border-gray-200 bg-white p-4">
          <h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-gray-500">
            Atrybuty
          </h2>
          <div className="flex flex-wrap gap-2">
            {notice.attributes.map((attr) => (
              <span
                className="rounded-full bg-gray-100 px-3 py-1 text-xs font-medium text-gray-700"
                key={`${attr.name}-${attr.value}`}
              >
                {attr.name}: {attr.value}
              </span>
            ))}
          </div>
        </div>
      ) : null}

      <div className="flex flex-wrap gap-2">
        <Link
          className="rounded-md border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-100"
          to="/notices"
        >
          Wroc do listy
        </Link>
        {isOwner ? (
          <>
            {notice.status === "INACTIVE" ? (
              <Link
                className="rounded-md border border-primary px-4 py-2 text-sm font-semibold text-primary hover:bg-primary/10"
                to={`/notices/${notice.noticeId}/edit`}
              >
                Edytuj
              </Link>
            ) : null}
            <button
              className="rounded-md border border-red-300 px-4 py-2 text-sm font-semibold text-red-600 hover:bg-red-50"
              onClick={handleDelete}
              type="button"
            >
              Usun
            </button>
          </>
        ) : null}
      </div>
    </section>
  );
}
