'use client';

import React, { useEffect, useState, useMemo } from 'react';
import { useRouter } from 'next/navigation';
import apis, { BUCKET_ROOT } from '@/utils/apis';
import { Star } from 'lucide-react';

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

  return (
    <div className="flex items-center gap-0.5">
      {[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-200 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-200 text-gray-200" />
            )}
          </div>
        );
      })}
    </div>
  );
};

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}`;
};

const RatingsAndReviewsSection = () => {
  const router = useRouter();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(false);

  const fetchedRef = React.useRef(false);

  useEffect(() => {
    if (fetchedRef.current) return;
    fetchedRef.current = true;

    const fetchReviews = async () => {
      setLoading(true);
      try {
        const res: any = await apis.User.review();
        setData(res);
      } catch (error) {
        console.error('Error fetching reviews:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchReviews();
  }, []);

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

  const overallRating = Number(raw?.overall_rating ?? data?.overall_rating ?? 0);
  const totalCount = Number(
    raw?.count ??
    data?.count ??
    (Array.isArray(raw?.data) ? raw.data.length : (Array.isArray(data) ? data.length : 0))
  );

  const reviewsList: any[] = 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]);

  return (
    <div className="w-full bg-white rounded-2xl p-6 border border-[#F0F0F2] shadow-sm flex flex-col justify-between h-[440px]">
      <div className="flex flex-col h-full">
        {/* Header */}
        <div className="flex items-start justify-between pb-3 flex-shrink-0">
          <div>
            <h3 className="text-base font-bold text-gray-900">Ratings & Reviews</h3>
            <p className="text-xs text-gray-400 mt-0.5">What customers are saying</p>
          </div>
          <button
            type="button"
            onClick={() => router.push('/reviews')}
            className="text-xs font-semibold text-[#FF7400] hover:underline cursor-pointer"
          >
            View All
          </button>
        </div>

        {/* Score Summary */}
        <div className="flex items-center gap-3 my-4 flex-shrink-0">
          <span className="text-3xl font-extrabold text-gray-900">
            {displayRating > 0 ? displayRating.toFixed(1) : '0.0'}
          </span>
          <div className="space-y-0.5">
            <StarRating rating={displayRating} size={15} />
            <p className="text-xs text-gray-400 underline font-medium">
              {totalCount.toLocaleString()} {totalCount === 1 ? 'Review' : 'Reviews'}
            </p>
          </div>
        </div>

        {/* Reviews Cards List */}
        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <div className="w-6 h-6 border-2 border-[var(--primary-brand)] border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : reviewsList.length === 0 ? (
          <div className="flex-1 flex items-center justify-center text-xs text-gray-400">
            No reviews yet
          </div>
        ) : (
          <div className="flex-1 overflow-y-auto pr-1 space-y-3 custom-scrollbar">
            {reviewsList.slice(0, 5).map((item, idx) => {
              const customerPhoto = item?.customer_image || item?.user_image;
              const customerName = item?.customer_name || 'Anonymous Customer';
              const ratingVal = Number(item?.rating) || 0;
              const description = item?.description || item?.comment || item?.review || '';
              const itemImage = item?.image;
              const timeStr = timeAgo(item?.created_at || item?.createdAt || item?.updatedAt);

              return (
                <div
                  key={item?._id || item?.id || idx}
                  className="bg-[#F8F9FA] rounded-2xl p-4 space-y-2.5 border border-transparent hover:bg-gray-100/80 transition-colors"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2.5 min-w-0">
                      {customerPhoto ? (
                        <img
                          src={getImageUrl(customerPhoto)}
                          alt={customerName}
                          className="w-8 h-8 rounded-full object-cover shrink-0 border border-gray-200/60"
                        />
                      ) : (
                        <div
                          className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-[11px] font-bold ${getAvatarBg(
                            customerName
                          )}`}
                        >
                          {getInitials(customerName)}
                        </div>
                      )}
                      <span className="text-xs font-bold text-gray-900 truncate">
                        {customerName}
                      </span>
                    </div>
                    <StarRating rating={ratingVal} size={13} />
                  </div>

                  {description && (
                    <p className="text-xs text-gray-600 leading-relaxed font-normal">
                      &ldquo;{description}&rdquo;
                    </p>
                  )}

                  {itemImage && (
                    <div className="pt-1">
                      <img
                        src={getImageUrl(itemImage)}
                        alt="Review attachment"
                        className="w-14 h-14 object-cover rounded-xl border border-gray-200/80 shadow-2xs"
                      />
                    </div>
                  )}

                  {timeStr && (
                    <p className="text-[11px] text-gray-400 pt-0.5">{timeStr}</p>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
};

export default RatingsAndReviewsSection;
