"use client";

import { motion, AnimatePresence } from "framer-motion";
import { BookCheck, Star, ChevronDown, ChevronUp, X } from "lucide-react";
import { useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import Image from "next/image";
import { Skeleton } from "./ui/Skeleton";

interface BookReview {
  id: string;
  hardcover_id?: string;
  book_title: string;
  book_author: string;
  book_image?: string;
  rating?: number | null;
  review?: string | null;
  finished_at?: string;
}

const StarRating = ({ rating }: { rating: number }) => {
  return (
    <div className="flex gap-0.5">
      {[1, 2, 3, 4, 5].map((star) => (
        <Star
          key={star}
          size={14}
          className={
            star <= rating
              ? "text-amber-500 fill-amber-500"
              : "text-stone-300 dark:text-stone-600"
          }
        />
      ))}
    </div>
  );
};

const stripHtml = (html: string) => {
  if (typeof window === 'undefined') return html; // Fallback for SSR
  const doc = new DOMParser().parseFromString(html, 'text/html');
  return doc.body.textContent || "";
};

const ReadBooks = () => {
  const locale = useLocale();
  const t = useTranslations("home.about.readBooks");
  const [reviews, setReviews] = useState<BookReview[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState(false);
  const [selectedReview, setSelectedReview] = useState<BookReview | null>(null);

  const INITIAL_SHOW = 3;

  useEffect(() => {
    const fetchReviews = async () => {
      try {
        const res = await fetch(
          `/api/book-reviews?locale=${encodeURIComponent(locale)}`,
          { cache: "default" }
        );

        if (!res.ok) {
          throw new Error("Failed to fetch");
        }

        const data = await res.json();
        if (data.bookReviews) {
          setReviews(data.bookReviews);
        } else {
          setReviews([]);
        }
      } catch (error) {
        if (process.env.NODE_ENV === "development") {
          console.error("Error fetching book reviews:", error);
        }
        setReviews([]);
      } finally {
        setLoading(false);
      }
    };

    fetchReviews();
  }, [locale]);

  if (loading) {
    return (
      <div className="space-y-6">
        {[1, 2].map((i) => (
          <div key={i} className="flex flex-col sm:flex-row gap-4 items-start">
            <Skeleton className="w-20 h-[7.5rem] sm:w-24 sm:h-32 rounded-lg shrink-0" />
            <div className="flex-1 space-y-2 w-full">
              <Skeleton className="h-5 w-1/2" />
              <Skeleton className="h-4 w-1/3" />
              <Skeleton className="h-3 w-1/4 pt-2" />
              <Skeleton className="h-12 w-full pt-2" />
            </div>
          </div>
        ))}
      </div>
    );
  }

  if (reviews.length === 0) {
    return (
      <div className="flex items-center gap-3 py-4 text-sm text-stone-400 dark:text-stone-500">
        <BookCheck size={16} className="shrink-0" />
        <span>{t("empty")}</span>
      </div>
    );
  }

  const visibleReviews = expanded ? reviews : reviews.slice(0, INITIAL_SHOW);
  const hasMore = reviews.length > INITIAL_SHOW;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center gap-2 mb-4">
        <BookCheck size={18} className="text-stone-600 dark:text-stone-300 flex-shrink-0" />
        <h3 className="text-lg font-bold text-stone-900 dark:text-stone-100">
          {t("title")} ({reviews.length})
        </h3>
      </div>

      {/* Book Reviews */}
      {visibleReviews.map((review, index) => (
        <motion.div
          key={review.id}
          initial={{ opacity: 0, y: 20 }}
          whileInView={{ opacity: 1, y: 0 }}
          viewport={{ once: true, margin: "-50px" }}
          transition={{
            duration: 0.6,
            delay: index * 0.1,
            ease: [0.25, 0.1, 0.25, 1],
          }}
          whileHover={{
            scale: 1.02,
            transition: { duration: 0.4, ease: "easeOut" },
          }}
          className="relative overflow-hidden bg-gradient-to-br from-liquid-mint/15 via-liquid-sky/10 to-liquid-teal/15 dark:from-stone-800 dark:via-stone-800 dark:to-stone-700 border-2 border-liquid-mint/30 dark:border-stone-700 rounded-xl p-5 backdrop-blur-sm hover:border-liquid-mint/50 dark:hover:border-stone-600 hover:from-liquid-mint/20 hover:via-liquid-sky/15 hover:to-liquid-teal/20 transition-all duration-500 ease-out"
        >
          {/* Background Blob */}
          <motion.div
            className="absolute -bottom-8 -left-8 w-28 h-28 bg-gradient-to-br from-liquid-mint/20 to-liquid-sky/20 dark:from-stone-700 dark:to-stone-600 rounded-full blur-2xl"
            animate={{
              scale: [1, 1.15, 1],
              opacity: [0.3, 0.45, 0.3],
            }}
            transition={{
              duration: 8,
              repeat: Infinity,
              ease: "easeInOut",
              delay: index * 0.5,
            }}
          />

          <div className="relative z-10 flex flex-col sm:flex-row gap-4 items-start">
            {/* Book Cover */}
            {review.book_image && (
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ duration: 0.5, delay: 0.2 + index * 0.1 }}
                className="flex-shrink-0"
              >
                <div className="relative w-20 h-[7.5rem] sm:w-24 sm:h-32 rounded-lg overflow-hidden shadow-lg border-2 border-white/50 dark:border-stone-600">
                  <Image
                    src={review.book_image}
                    alt={review.book_title}
                    fill
                    className="object-cover"
                    sizes="(max-width: 640px) 80px, 96px"
                  />
                  <div className="absolute inset-0 bg-gradient-to-tr from-white/20 via-transparent to-white/10 pointer-events-none" />
                </div>
              </motion.div>
            )}

            {/* Book Info */}
            <div className="flex-1 min-w-0">
              <h4 className="text-base font-bold text-stone-900 dark:text-stone-100 mb-0.5 line-clamp-2">
                {review.book_title}
              </h4>
              <p className="text-sm text-stone-600 dark:text-stone-400 mb-2 line-clamp-1">
                {review.book_author}
              </p>

              {/* Rating (Optional) */}
              {review.rating && review.rating > 0 && (
                <div className="flex items-center gap-2 mb-2">
                  <StarRating rating={review.rating} />
                  <span className="text-xs text-stone-500 dark:text-stone-400 font-medium">
                    {review.rating}/5
                  </span>
                </div>
              )}

              {/* Review Text (Optional) */}
              {review.review && (
                <div>
                  <p className="text-sm text-stone-700 dark:text-stone-300 leading-relaxed line-clamp-3 italic">
                    &ldquo;{stripHtml(review.review)}&rdquo;
                  </p>
                  <button
                    onClick={() => setSelectedReview(review)}
                    className="text-xs text-liquid-mint dark:text-liquid-sky hover:underline mt-1 font-medium"
                  >
                    {t("readMore", { defaultValue: "Read full review" })}
                  </button>
                </div>
              )}

              {/* Finished Date */}
              {review.finished_at && (
                <p className="text-xs text-stone-400 dark:text-stone-500 mt-2">
                  {t("finishedAt")}{" "}
                  {new Date(review.finished_at).toLocaleDateString(
                    locale === "de" ? "de-DE" : "en-US",
                    { year: "numeric", month: "short" }
                  )}
                </p>
              )}
            </div>
          </div>
        </motion.div>
      ))}

      {/* Show More / Show Less */}
      {hasMore && (
        <motion.button
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.3 }}
          onClick={() => setExpanded(!expanded)}
          className="w-full flex items-center justify-center gap-1.5 py-2.5 text-sm font-medium text-stone-600 dark:text-stone-400 hover:text-stone-800 dark:hover:text-stone-200 rounded-lg border-2 border-dashed border-stone-200 dark:border-stone-700 hover:border-stone-300 dark:hover:border-stone-600 transition-colors duration-300"
        >
          {expanded ? (
            <>
              {t("showLess")} <ChevronUp size={16} />
            </>
          ) : (
            <>
              {t("showMore", { count: reviews.length - INITIAL_SHOW })}{" "}
              <ChevronDown size={16} />
            </>
          )}
        </motion.button>
      )}

      {/* Modal for full review */}
      <AnimatePresence>
        {selectedReview && (
          <>
            {/* Backdrop */}
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setSelectedReview(null)}
              className="fixed inset-0 bg-black/70 backdrop-blur-md z-50"
            />

            {/* Modal */}
            <motion.div
              initial={{ opacity: 0, scale: 0.95, y: 40 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.95, y: 40 }}
              transition={{ type: "spring", damping: 30, stiffness: 400 }}
              className="fixed inset-x-4 bottom-4 top-20 sm:inset-auto sm:left-1/2 sm:top-1/2 sm:-translate-x-1/2 sm:-translate-y-1/2 sm:w-full sm:max-w-3xl sm:max-h-[85vh] z-50 bg-gradient-to-br from-white via-liquid-sky/5 to-liquid-mint/10 dark:from-stone-900 dark:via-stone-900 dark:to-stone-800 rounded-3xl shadow-2xl border-2 border-liquid-mint/30 dark:border-stone-700 overflow-hidden"
            >
              {/* Decorative blob */}
              <div className="absolute -top-20 -right-20 w-64 h-64 bg-gradient-to-br from-liquid-mint/20 to-liquid-sky/20 dark:from-stone-700/30 dark:to-stone-600/30 rounded-full blur-3xl pointer-events-none" />
              
              {/* Close button */}
              <button
                onClick={() => setSelectedReview(null)}
                className="absolute top-4 right-4 p-2.5 rounded-full bg-white/80 dark:bg-stone-800/80 backdrop-blur-sm hover:bg-white dark:hover:bg-stone-700 transition-all duration-200 z-10 shadow-lg border border-stone-200 dark:border-stone-600"
                aria-label="Close"
              >
                <X size={20} className="text-stone-600 dark:text-stone-300" />
              </button>

              {/* Content */}
              <div className="relative h-full overflow-y-auto overscroll-contain p-6 sm:p-8 md:p-10">
                <div className="flex flex-col sm:flex-row gap-6 mb-6">
                  {/* Book Cover */}
                  {selectedReview.book_image && (
                    <motion.div
                      initial={{ opacity: 0, x: -20 }}
                      animate={{ opacity: 1, x: 0 }}
                      transition={{ delay: 0.1 }}
                      className="flex-shrink-0 mx-auto sm:mx-0"
                    >
                      <div className="relative w-32 h-48 sm:w-36 sm:h-52 rounded-xl overflow-hidden shadow-2xl border-2 border-white/50 dark:border-stone-700">
                        <Image
                          src={selectedReview.book_image}
                          alt={selectedReview.book_title}
                          fill
                          className="object-cover"
                          sizes="(max-width: 640px) 128px, 144px"
                          priority
                        />
                        <div className="absolute inset-0 bg-gradient-to-tr from-white/20 via-transparent to-white/10 pointer-events-none" />
                      </div>
                    </motion.div>
                  )}

                  {/* Book Info */}
                  <motion.div
                    initial={{ opacity: 0, y: 10 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.15 }}
                    className="flex-1 min-w-0"
                  >
                    <h2 className="text-2xl sm:text-3xl font-bold text-stone-900 dark:text-stone-100 mb-2 leading-tight">
                      {selectedReview.book_title}
                    </h2>
                    <p className="text-base sm:text-lg text-stone-600 dark:text-stone-400 mb-4">
                      {selectedReview.book_author}
                    </p>

                    {selectedReview.rating && selectedReview.rating > 0 && (
                      <div className="flex items-center gap-3 mb-4">
                        <div className="flex gap-1">
                          {[1, 2, 3, 4, 5].map((star) => (
                            <Star
                              key={star}
                              size={18}
                              className={
                                star <= selectedReview.rating!
                                  ? "text-amber-500 fill-amber-500"
                                  : "text-stone-300 dark:text-stone-600"
                              }
                            />
                          ))}
                        </div>
                        <span className="text-base text-stone-600 dark:text-stone-400 font-semibold">
                          {selectedReview.rating}/5
                        </span>
                      </div>
                    )}

                    {selectedReview.finished_at && (
                      <p className="text-sm text-stone-500 dark:text-stone-400 flex items-center gap-2">
                        <BookCheck size={14} className="opacity-60" />
                        {t("finishedAt")}{" "}
                        {new Date(selectedReview.finished_at).toLocaleDateString(
                          locale === "de" ? "de-DE" : "en-US",
                          { year: "numeric", month: "long", day: "numeric" }
                        )}
                      </p>
                    )}
                  </motion.div>
                </div>

                {/* Full Review */}
                {selectedReview.review && (
                  <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2 }}
                    className="bg-gradient-to-br from-liquid-mint/10 via-liquid-sky/5 to-transparent dark:from-stone-800/50 dark:via-stone-800/30 dark:to-transparent rounded-2xl p-6 border-l-4 border-liquid-mint dark:border-liquid-sky"
                  >
                    <p className="text-base sm:text-lg text-stone-700 dark:text-stone-300 leading-relaxed italic">
                      &ldquo;{stripHtml(selectedReview.review)}&rdquo;
                    </p>
                  </motion.div>
                )}
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
};

export default ReadBooks;
