"use client";

import type { CommunityPostRecord } from "@/features/community/communityRecord";
import PostCard from "./CommunityPostCard";
import React, { useEffect, useRef, useState } from "react";
import { useResponsiveValue } from "@/hooks/useViewportWidth";
import Carousel from "react-multi-carousel";
import "react-multi-carousel/lib/styles.css";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/navigation";
import { useLanguageStore } from "@/store/languageStore";
import { toast } from "sonner";
import apiClient from "@/lib/api/client";
import { toastApiError } from "@/lib/api/toastApiError";
import { useQueryClient } from "@tanstack/react-query";
import { invalidateCommunityFeeds } from "@/features/community/communityQueryKeys";
import Loader from "@/components/ui/Loader";
import { useIsMounted } from "@/hooks/useIsMounted";

/**
 * One post on the homepage carousel.
 *
 * `CommunityPostRecord` — the transcription of `WebsitePostResource` — rather
 * than the six-field subset this used to declare. The subset was not just
 * incomplete (no `title_*`, no `post_images`, no `tags`, no counts): it said
 * `idea_text_en` / `idea_text_ar` were `string` where both columns are
 * nullable, and `user` was a required `UserProfile` where the resource emits
 * `null` for a post with no author.
 */
export type PostData = CommunityPostRecord;

interface CommunityCardProps {
  posts: PostData[];
  onNavigationVisibilityChange?: (isVisible: boolean) => void;
  refetch?: () => void;
}

const responsive = {
  superLargeDesktop: { breakpoint: { max: 4000, min: 1200 }, items: 2 },
  desktop: { breakpoint: { max: 1200, min: 800 }, items: 2 },
  tablet: { breakpoint: { max: 800, min: 464 }, items: 1 },
  mobile: { breakpoint: { max: 464, min: 0 }, items: 1 },
};

export default function CommunityCard({
  posts,
  onNavigationVisibilityChange,
  refetch,
}: CommunityCardProps) {
  const selectedLanguage = useLanguageStore((s) => s.language);
  const { t } = useTranslation();
  const [currentSlide, setCurrentSlide] = useState(0);
  /*
   * Derived, not stored. `totalItems` was `useState(0)` written by a mount /
   * data effect, so on the first render after new data it was still the
   * previous length — which is what `goToNext` and the arrow-disabled checks
   * read, briefly disabling "next" on a list that had just grown. It is
   * `posts?.length ?? 0` and nothing else, so it is computed here.
   */
  const totalItems = posts?.length ?? 0;
  /*
   * `maxVisibleItems` is a measurement of the viewport, not state this
   * component owns. It was `useState` seeded with a guess and overwritten by a
   * mount effect plus a `resize` listener — the shape
   * `react-hooks/set-state-in-effect` flags, and the one `useViewportWidth`
   * exists for. `useResponsiveValue` reads the same three breakpoints through
   * `useSyncExternalStore`, which has a separate server snapshot and so needs
   * no post-mount write.
   *
   * Before measurement the value is the narrowest entry rather than the old
   * hard-coded 2. Only the arrow/dot visibility reads it — the carousel
   * itself takes `responsive` directly — so this affects one frame on first
   * paint, mobile-first, which is the direction the effect corrected to
   * anyway.
   */
  const maxVisibleItems = useResponsiveValue(
    [
      { minWidth: 1200, value: responsive.superLargeDesktop.items },
      { minWidth: 800, value: responsive.desktop.items },
      { minWidth: 0, value: responsive.tablet.items },
    ],
    responsive.tablet.items
  );
  const carouselRef = useRef<Carousel>(null);
  const router = useRouter();
  const queryClient = useQueryClient();

  const isMounted = useIsMounted();

  useEffect(() => {
    const isNavigationVisible = (posts?.length || 0) > maxVisibleItems;
    onNavigationVisibilityChange?.(isNavigationVisible);
  }, [posts?.length, maxVisibleItems, onNavigationVisibilityChange]);

  const goToPrevious = () => {
    if (carouselRef.current && currentSlide > 0) {
      carouselRef.current.previous(1);
      setCurrentSlide((prev) => Math.max(prev - 1, 0));
    }
  };

  const goToNext = () => {
    const maxSlideIndex = Math.max(0, totalItems - maxVisibleItems);
    if (carouselRef.current && currentSlide < maxSlideIndex) {
      carouselRef.current.next(1);
      setCurrentSlide((prev) => Math.min(prev + 1, maxSlideIndex));
    }
  };

  /* Server reason on failure (not a generic toast), one request at a time, and
     the community feed's cache follows the delete too. */
  const deletingRef = useRef(false);
  const handleDelete = async (postId: number) => {
    if (deletingRef.current || !confirm(t("COMMON.ARE_YOU_SURE_DELETE_POST"))) return;
    deletingRef.current = true;
    try {
      await apiClient.delete(`/posts/${postId}/`);
      toast.success(t("COMMON.TOAST.POST_DELETED_SUCCESSFULLY"));
      refetch?.();
      void invalidateCommunityFeeds(queryClient);
    } catch (err) {
      toastApiError(err, selectedLanguage, t("COMMON.TOAST.DELETE_POST_FAILED"));
    } finally {
      deletingRef.current = false;
    }
  };

  const hasNoPosts = (posts?.length || 0) === 0;

  if (!isMounted) {
    return <Loader />;
  }

  return (
    <div className={`carousel-frame home-aligned-carousel ${posts.length > maxVisibleItems ? "carousel-frame-with-arrows" : ""}`}>
      {hasNoPosts ? (
        <div className="text-center py-8 text-white text-lg font-medium">
          {t("COMMON.NO_POSTS_AVAILABLE")}
        </div>
      ) : (
        <>
          <Carousel
            rtl={selectedLanguage === "ar"}
            ref={carouselRef}
            responsive={responsive}
            infinite
            autoPlay={false}
            showDots={true}
            arrows={false}
            keyBoardControl
            customTransition="transform 500ms ease-in-out"
            containerClass="carousel-container mobilescreen:pb-10 my-[5px]"
          >
            {posts.map((post) => (
              <PostCard
                key={post.id}
                post={post}
                onDelete={() => handleDelete(post.id)}
                router={router}
                selectedLanguage={selectedLanguage}
              />
            ))}
          </Carousel>
          {posts?.length > maxVisibleItems && (
            <div className="flex justify-center mobilescreen:hidden">
              <button
                onClick={selectedLanguage === "ar" ? goToNext : goToPrevious}
                aria-label={t("COMMON.PREVIOUS") || "Previous"}
                disabled={
                  selectedLanguage === "ar"
                    ? currentSlide >= totalItems - maxVisibleItems
                    : currentSlide === 0
                }
                className="bg-white text-primary-5 p-3 carousel-navigation carousel-navigation-left rounded-full shadow-lg hover:bg-secondary-103 transition absolute top-[50%] -translate-y-1/2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <ChevronLeft size={20} />
              </button>
              <button
                onClick={selectedLanguage === "ar" ? goToPrevious : goToNext}
                aria-label={t("COMMON.NEXT") || "Next"}
                disabled={
                  selectedLanguage === "ar"
                    ? currentSlide === 0
                    : currentSlide >= totalItems - maxVisibleItems
                }
                className="bg-white text-primary-5 p-3 carousel-navigation carousel-navigation-right rounded-full shadow-lg hover:bg-secondary-103 transition absolute top-[50%] -translate-y-1/2 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <ChevronRight size={20} />
              </button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
