import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import NoticeCard from "../components/NoticeCard";
import { useAuthStore } from "../store/authStore";
import { useNoticesStore } from "../store/noticesStore";

export default function MyNotices() {
  const { user_id } = useAuthStore();
  const { notices, deleteNotice, fetchNotices } = useNoticesStore();
  const [isLoading, setIsLoading] = useState(true);

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

    const loadNotices = async () => {
      setIsLoading(true);
      try {
        await fetchNotices();
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    };

    loadNotices();

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

  const userNotices = useMemo(
    () =>
      notices
        .filter((notice) => String(notice.clientId) === String(user_id))
        .sort((a, b) => new Date(b.publishDate) - new Date(a.publishDate)),
    [notices, user_id]
  );

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

  return (
    <section className="space-y-4">
      <div className="flex items-center justify-between gap-3">
        <h1 className="text-2xl font-bold text-gray-900">Moje ogloszenia</h1>
        <Link
          className="inline-flex rounded-md bg-primary px-4 py-2 text-sm font-semibold text-white hover:bg-primary/90"
          to="/notices/create"
        >
          Dodaj nowe
        </Link>
      </div>

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

      {!isLoading && userNotices.length === 0 ? (
        <div className="rounded-lg border border-dashed border-gray-300 bg-white p-8 text-center text-sm text-gray-600">
          Nie masz jeszcze ogloszen.
        </div>
      ) : null}

      {!isLoading && userNotices.length > 0 ? (
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          {userNotices.map((notice) => (
            <NoticeCard
              actions={
                <>
                  {/* {notice.status === "INACTIVE" ? (*/
                    <Link
                      className="rounded-md border border-primary px-3 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-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-50"
                    onClick={() => handleDelete(notice.noticeId)}
                    type="button"
                  >
                    Usun
                  </button>
                </>
              }
              key={notice.noticeId}
              notice={notice}
            />
          ))}
        </div>
      ) : null}
    </section>
  );
}
