'use client';

import React, { useState, useMemo, useRef, useEffect } from 'react';
import { Star, X, ZoomIn, Loader2 } from 'lucide-react';
import { BUCKET_ROOT } from '@/utils/apis';

interface ReviewTableProps {
  data?: any;
  reviewsList?: any[];
  overallRating?: number;
  totalCount?: number;
  loading?: boolean;
  loadingMore?: boolean;
  hasMore?: boolean;
  onLoadMore?: () => void;
}

const StarRating = ({ rating, size = 18 }: { rating: number; size?: number }) => {
  const normalizedRating = Math.max(0, Math.min(5, Number(rating) || 0));

  return (
    <div className="flex items-center gap-1">
      {[1, 2, 3, 4, 5].map((starIndex) => {
        const isFull = normalizedRating >= starIndex;
        const isHalf = !isFull && normalizedRating >= starIndex - 0.5;

        return (
          <div key={starIndex} className="relative inline-block leading-none">
            {isFull ? (
              <Star
                size={size}
                className="fill-[#FBBF24] text-[#FBBF24]"
              />
            ) : isHalf ? (
              <div className="relative">
                <Star size={size} className="fill-gray-100 text-gray-200" />
                <div className="absolute top-0 left-0 overflow-hidden w-1/2">
                  <Star size={size} className="fill-[#FBBF24] text-[#FBBF24]" />
                </div>
              </div>
            ) : (
              <Star
                size={size}
                className="fill-gray-100 text-gray-200"
              />
            )}
          </div>
        );
      })}
    </div>
  );
};

const ReviewTable: React.FC<ReviewTableProps> = ({
  data,
  reviewsList: reviewsListProp,
  overallRating: overallRatingProp,
  totalCount: totalCountProp,
  loading = false,
  loadingMore = false,
  hasMore = false,
  onLoadMore
}) => {
  const [previewImage, setPreviewImage] = useState<string | null>(null);
  const sentinelRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!onLoadMore || !hasMore || loading || loadingMore) return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting) {
          onLoadMore();
        }
      },
      { threshold: 0.1, rootMargin: '150px' }
    );

    const currentTarget = sentinelRef.current;
    if (currentTarget) {
      observer.observe(currentTarget);
    }

    return () => {
      if (currentTarget) {
        observer.unobserve(currentTarget);
      }
    };
  }, [onLoadMore, hasMore, loading, loadingMore]);

  // Normalize API data structure
  const raw = data?.data && typeof data?.data === 'object' && !Array.isArray(data.data) ? data.data : data;

  const overallRating = overallRatingProp ?? Number(raw?.overall_rating ?? data?.overall_rating ?? 0);
  const totalCount = totalCountProp ?? Number(
    raw?.count ??
    data?.count ??
    (Array.isArray(raw?.data) ? raw.data.length : (Array.isArray(data) ? data.length : 0))
  );
  const reviewsList: any[] = reviewsListProp ?? (Array.isArray(raw?.data)
    ? raw.data
    : Array.isArray(data?.data)
      ? data.data
      : Array.isArray(data)
        ? data
        : []);

  const displayRating = useMemo(() => {
    if (overallRating > 0) return overallRating;
    const validRatings = reviewsList.filter((r) => Number(r.rating) > 0);
    if (validRatings.length > 0) {
      const sum = validRatings.reduce((acc, curr) => acc + Number(curr.rating), 0);
      return Number((sum / validRatings.length).toFixed(1));
    }
    return 0;
  }, [overallRating, reviewsList]);

  function timeAgo(dateString: any) {
    if (!dateString) return '';
    const now = new Date();
    const past = new Date(dateString);
    const diffInMs = now.getTime() - past.getTime();
    const diffInMinutes = Math.floor(diffInMs / (1000 * 60));
    const diffInHours = Math.floor(diffInMs / (1000 * 60 * 60));
    const diffInDays = Math.floor(diffInHours / 24);

    if (diffInMinutes < 1) return 'Just now';
    if (diffInMinutes === 1) return '1 min ago';
    if (diffInMinutes < 60) return `${diffInMinutes} mins ago`;
    if (diffInHours === 1) return '1 hr ago';
    if (diffInHours < 24) return `${diffInHours} hrs ago`;
    if (diffInDays === 1) return '1 day ago';
    if (diffInDays < 30) return `${diffInDays} days ago`;
    return past.toLocaleDateString('en-US', { day: 'numeric', month: 'short', year: 'numeric' });
  }

  const getInitials = (name: string) => {
    if (!name) return '?';
    const parts = name.trim().split(' ');
    if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
    return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
  };

  const getAvatarBg = (name: string) => {
    if (!name) return 'bg-gray-100 text-gray-500';
    const colors = [
      'bg-amber-50 text-amber-600 border border-amber-200/60',
      'bg-blue-50 text-blue-600 border border-blue-200/60',
      'bg-purple-50 text-purple-600 border border-purple-200/60',
      'bg-emerald-50 text-emerald-600 border border-emerald-200/60',
      'bg-rose-50 text-rose-600 border border-rose-200/60',
      'bg-teal-50 text-teal-600 border border-teal-200/60',
      'bg-indigo-50 text-indigo-600 border border-indigo-200/60',
    ];
    let hash = 0;
    for (let i = 0; i < name.length; i++) {
      hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }
    const index = Math.abs(hash) % colors.length;
    return colors[index];
  };

  const getImageUrl = (imagePath: string) => {
    if (!imagePath) return '';
    if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
      return imagePath;
    }
    const cleanBucket = BUCKET_ROOT?.endsWith('/') ? BUCKET_ROOT.slice(0, -1) : BUCKET_ROOT;
    const cleanPath = imagePath.startsWith('/') ? imagePath : `/${imagePath}`;
    return `${cleanBucket}${cleanPath}`;
  };

  if (loading) {
    return (
      <div className="w-full">
        <div className="flex items-center gap-4 mb-8 animate-pulse">
          <div className="h-12 w-20 bg-gray-200 rounded-xl" />
          <div className="space-y-2">
            <div className="h-4 w-28 bg-gray-200 rounded" />
            <div className="h-3 w-20 bg-gray-200 rounded" />
          </div>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 w-full">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <div key={i} className="rounded-2xl bg-gray-50 p-6 space-y-3 animate-pulse">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 rounded-full bg-gray-200" />
                  <div className="h-4 w-32 bg-gray-200 rounded" />
                </div>
                <div className="h-4 w-24 bg-gray-200 rounded" />
              </div>
              <div className="h-4 w-full bg-gray-200 rounded" />
              <div className="h-4 w-2/3 bg-gray-200 rounded" />
              <div className="h-3 w-16 bg-gray-200 rounded mt-2" />
            </div>
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="w-full">
      {/* Overall Rating Section */}
      <div className="flex items-center gap-4 mb-8">
        <span className="text-5xl font-black text-gray-900 tracking-tight leading-none">
          {displayRating > 0 ? displayRating.toFixed(1) : '0.0'}
        </span>
        <div className="flex flex-col gap-1.5 justify-center">
          <StarRating rating={displayRating} size={20} />
          <span className="text-sm font-medium text-gray-400 underline underline-offset-4 decoration-gray-300">
            {totalCount.toLocaleString()} {totalCount === 1 ? 'Review' : 'Reviews'}
          </span>
        </div>
      </div>

      {/* Review Cards Grid (1 column on mobile, 2 on tablet, 3 on desktop) */}
      {reviewsList.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 w-full">
          {reviewsList.map((item: any, index: number) => {
            const customerPhoto = item?.customer_image || item?.user_image;

            return (
              <div
                key={item?._id || index}
                className="rounded-2xl bg-[#F8F9FA] p-5 md:p-6 flex flex-col justify-between transition-all hover:bg-[#F3F4F6]/80 hover:shadow-xs border border-transparent"
              >
                <div>
                  {/* Header: Customer + Rating */}
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex items-center gap-3 min-w-0">
                      {customerPhoto ? (
                        <img
                          src={getImageUrl(customerPhoto)}
                          alt={item.customer_name || 'Customer'}
                          className="w-10 h-10 rounded-full object-cover shrink-0 border border-gray-200/60"
                        />
                      ) : (
                        <div
                          className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-xs font-bold ${getAvatarBg(
                            item?.customer_name
                          )}`}
                        >
                          {getInitials(item?.customer_name)}
                        </div>
                      )}
                      <div className="min-w-0">
                        <div className="flex items-center gap-1.5 flex-wrap">
                          <h4 className="font-bold text-gray-900 text-sm md:text-base truncate">
                            {item.customer_name || 'Anonymous Customer'}
                          </h4>
                          {item.order_id && (
                            <span className="inline-flex items-center text-[10px] font-semibold bg-white text-gray-600 border border-gray-200/80 px-2 py-0.5 rounded-full shadow-2xs">
                              #{item.order_id}
                            </span>
                          )}
                        </div>
                      </div>
                    </div>

                    {/* Stars on Right */}
                    <div className="shrink-0 pt-0.5">
                      <StarRating rating={item.rating || 0} size={15} />
                    </div>
                  </div>

                  {/* Description */}
                  {item.description && (
                    <p className="mt-3.5 text-sm text-gray-600 font-normal leading-relaxed">
                      &ldquo;{item.description}&rdquo;
                    </p>
                  )}

                  {/* Review Photo Attachment */}
                  {item.image && (
                    <div className="mt-3.5">
                      <div
                        onClick={() => setPreviewImage(getImageUrl(item.image))}
                        className="relative inline-block overflow-hidden rounded-xl border border-gray-200/80 cursor-pointer group shadow-2xs"
                      >
                        <img
                          src={getImageUrl(item.image)}
                          alt="Review attachment"
                          className="h-20 w-20 object-cover transition-transform duration-200 group-hover:scale-105"
                        />
                        <div className="absolute inset-0 bg-black/20 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center">
                          <ZoomIn size={18} className="text-white drop-shadow" />
                        </div>
                      </div>
                    </div>
                  )}
                </div>

                {/* Time Ago Footer */}
                <div className="mt-4 pt-2 flex items-center justify-between">
                  <span className="text-xs font-medium text-gray-400">
                    {timeAgo(item.created_at)}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="rounded-2xl bg-[#F8F9FA] p-12 text-center w-full">
          <div className="inline-flex h-14 w-14 items-center justify-center rounded-full bg-amber-50 text-amber-500 mb-3">
            <Star size={28} className="fill-amber-400" />
          </div>
          <h3 className="text-base font-bold text-gray-900">No reviews yet</h3>
          <p className="text-sm text-gray-400 mt-1 max-w-sm mx-auto">
            When customers leave reviews on their orders, they will show up here.
          </p>
        </div>
      )}

      {/* Scroll Pagination Sentinel & Footer */}
      {!loading && (hasMore || loadingMore) && (
        <div ref={sentinelRef} className="mt-8 flex flex-col items-center justify-center py-4 min-h-[50px]">
          {loadingMore && (
            <div className="flex items-center gap-2 text-sm font-semibold text-[var(--orange-500)]">
              <Loader2 className="w-5 h-5 animate-spin text-[var(--orange-500)]" />
              <span>Loading more reviews...</span>
            </div>
          )}
        </div>
      )}

      {/* Image Lightbox Modal */}
      {previewImage && (
        <div 
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-xs p-4"
          onClick={() => setPreviewImage(null)}
        >
          <div 
            className="relative max-h-[85vh] max-w-[90vw] overflow-hidden rounded-2xl bg-white p-2 shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            <button
              onClick={() => setPreviewImage(null)}
              className="absolute right-4 top-4 rounded-full bg-black/60 p-2 text-white hover:bg-black/80 transition-colors z-10 cursor-pointer"
            >
              <X size={18} />
            </button>
            <img
              src={previewImage}
              alt="Review item full preview"
              className="max-h-[80vh] max-w-[85vw] object-contain rounded-lg"
            />
          </div>
        </div>
      )}
    </div>
  );
};

export default ReviewTable;
