"use client"
import { useRef, useState, useCallback, useEffect } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { TestimonialsData } from '@/lib/strapi/types'
import { homepageDefaults } from '@/lib/api/defaults'

interface TestimonialsProps {
  data?: TestimonialsData
}

const starFilled = '/assets/testimonials/star-filled.svg'
const starHalf = '/assets/testimonials/star-half.svg'
const starEmpty = '/assets/testimonials/star-empty.svg'

const MOBILE_CARD_WIDTH = 277
const MOBILE_CARD_GAP = 16

function StarRating({ rating }: { rating: number }) {
  return (
    <div className="flex gap-1">
      {[1, 2, 3, 4, 5].map((i) => {
        if (i <= rating) {
          return (
            <img
              key={i}
              src={starFilled}
              alt=""
              loading="lazy"
              className="w-5 h-5"
            />
          )
        }
        if (i - 0.5 <= rating) {
          return (
            <img
              key={i}
              src={starHalf}
              alt=""
              loading="lazy"
              className="w-5 h-5"
            />
          )
        }
        return (
          <img
            key={i}
            src={starEmpty}
            alt=""
            loading="lazy"
            className="w-5 h-5"
          />
        )
      })}
    </div>
  )
}

export default function Testimonials({ data = homepageDefaults.testimonials }: TestimonialsProps) {
  const testimonials = data.testimonials
  const TOTAL_MOBILE_PAGES = testimonials.length
  const scrollRef = useRef<HTMLDivElement>(null)
  const [activeIndex, setActiveIndex] = useState(0)
  const [atStart, setAtStart] = useState(true)
  const [atEnd, setAtEnd] = useState(false)

  const scroll = useCallback(
    (direction: 'left' | 'right') => {
      if (!scrollRef.current) return
      const cardWidth = 416
      const scrollAmount = cardWidth + 24
      scrollRef.current.scrollBy({
        left: direction === 'right' ? scrollAmount : -scrollAmount,
        behavior: 'smooth',
      })
    },
    []
  )

  // Scroll tracking for both mobile and desktop
  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return
    const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current
    const pageWidth = MOBILE_CARD_WIDTH + MOBILE_CARD_GAP
    const page = Math.round(scrollLeft / pageWidth)
    setActiveIndex(Math.min(page, TOTAL_MOBILE_PAGES - 1))
    setAtStart(scrollLeft < 2)
    setAtEnd(scrollLeft + clientWidth >= scrollWidth - 2)
  }, [])

  useEffect(() => {
    const el = scrollRef.current
    if (!el) return
    handleScroll()
    el.addEventListener('scroll', handleScroll, { passive: true })
    return () => el.removeEventListener('scroll', handleScroll)
  }, [handleScroll])

  const scrollToPage = useCallback(
    (direction: 'prev' | 'next') => {
      if (!scrollRef.current) return
      const pageWidth = MOBILE_CARD_WIDTH + MOBILE_CARD_GAP
      const newPage =
        direction === 'next'
          ? Math.min(activeIndex + 1, TOTAL_MOBILE_PAGES - 1)
          : Math.max(activeIndex - 1, 0)
      scrollRef.current.scrollTo({ left: newPage * pageWidth, behavior: 'smooth' })
      setActiveIndex(newPage)
    },
    [activeIndex]
  )

  // Drag scroll
  const isDragging = useRef(false)
  const startX = useRef(0)
  const scrollLeftRef = useRef(0)

  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (!scrollRef.current) return
    isDragging.current = true
    startX.current = e.pageX - scrollRef.current.offsetLeft
    scrollLeftRef.current = scrollRef.current.scrollLeft
    scrollRef.current.style.cursor = 'grabbing'
  }, [])

  const handleMouseUp = useCallback(() => {
    isDragging.current = false
    if (scrollRef.current) scrollRef.current.style.cursor = 'grab'
  }, [])

  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    if (!isDragging.current || !scrollRef.current) return
    e.preventDefault()
    const x = e.pageX - scrollRef.current.offsetLeft
    const walk = (x - startX.current) * 1.5
    scrollRef.current.scrollLeft = scrollLeftRef.current - walk
  }, [])

  return (
    <section className="w-full bg-white py-16 lg:py-20 overflow-hidden">
      {/* Header: Badge + Description */}
      <div className="w-full max-w-[1297px] mx-auto px-5 lg:px-0">
        <div className="mb-14">
          <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-5 lg:gap-6">
            {/* Badge */}
            <div>
              <span className="inline-flex items-center gap-2 px-6 py-3 bg-[#ebebeb] rounded-full">
                <img
                  src={data.header.badgeIcon || "/assets/common/sparkle-vector.svg"}
                  alt=""
                  loading="lazy"
                  className="w-[17px] h-4"
                />
                <span className="font-heading text-black text-base uppercase leading-none">
                  {data.header.badge || 'Testimonials'}
                </span>
              </span>
            </div>

            {/* Description */}
            <div className="max-w-full lg:max-w-[524px]">
              {/* Mobile description */}
              <p className="lg:hidden font-sans font-medium text-base text-[rgba(16,36,67,0.6)] leading-[1.5]">
                {data.mobileDescription || data.header.description}
              </p>
              {/* Desktop description */}
              <p className="hidden lg:block font-sans font-normal text-base text-[#4a5565] leading-[24px]">
                {data.header.description}

              </p>
              <div className="mt-4 lg:mt-6 border-b border-[#102443]/20" />
            </div>
          </div>
        </div>

      </div>

      {/* Cards Carousel - full width */}
      <div className="w-full">
          <div
            ref={scrollRef}
            className="flex gap-4 lg:gap-6 overflow-x-auto scrollbar-hide cursor-grab active:cursor-grabbing pl-5 pr-0 lg:pl-[max(20px,calc((100vw-1297px)/2))] lg:pr-0"
            onMouseDown={handleMouseDown}
            onMouseUp={handleMouseUp}
            onMouseMove={handleMouseMove}
            onMouseLeave={handleMouseUp}
          >
          {testimonials.map((t, idx) => (
            <div
              key={idx}
              data-card
              className="group relative flex-shrink-0 w-[277px] lg:w-[416px] rounded-2xl overflow-hidden flex flex-col"
            >
              {/* Backgrounds */}
              <div 
                className="absolute inset-0 transition-opacity duration-300 opacity-100 group-hover:opacity-0"
                style={{ background: 'radial-gradient(ellipse at bottom left, rgba(255,232,233,1) 0%, rgba(255,232,233,0) 60%), linear-gradient(90deg, #fff 0%, #fff 100%)' }}
              />
              <div 
                className="absolute inset-0 transition-opacity duration-300 opacity-0 group-hover:opacity-100"
                style={{ background: 'linear-gradient(147.39deg, rgb(42,48,54) 16.68%, rgb(35,40,45) 95.23%)' }}
              />

              {/* Content Wrapper */}
              <div className="relative z-10 flex flex-col flex-1 p-4 lg:p-6 gap-6">
                {/* Quote */}
                <p className="flex-1 font-sans font-normal text-[20px] lg:text-2xl lg:font-medium leading-normal text-[#102443] group-hover:text-white transition-colors duration-300">
                  {t.quote}
                </p>

                {/* Divider */}
                <div className="border-b border-[#102443]/10 group-hover:border-white/20 transition-colors duration-300" />

                {/* Author row */}
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <img
                      src={t.avatar}
                      alt={t.name}
                      loading="lazy"
                      className="w-12 h-12 rounded-full object-cover flex-shrink-0"
                    />
                    <div className="flex flex-col">
                      {/* Stars - shown above name on mobile, hidden on desktop */}
                      <div className="lg:hidden">
                        <StarRating rating={t.rating} />
                      </div>
                      <p className="font-sans font-medium text-base leading-[24px] text-[#102443] group-hover:text-white transition-colors duration-300">
                        {t.name}
                      </p>
                      <p className="font-sans font-medium text-xs leading-[1.1] text-[rgba(16,36,67,0.5)] group-hover:text-white/50 transition-colors duration-300">
                        {t.role}
                      </p>
                    </div>
                  </div>
                  {/* Stars - desktop only, on the right */}
                  <div className="hidden lg:block">
                    <StarRating rating={t.rating} />
                  </div>
                </div>
              </div>
            </div>
          ))}
          </div>

          {/* Bottom: Progress indicators + Navigation arrows */}
          <div className="mt-6 max-w-[1297px] mx-auto px-5 lg:px-0">
            <div className="flex items-center justify-end">
              {/* Mobile Navigation Arrows */}
              <div className="flex lg:hidden items-center gap-2">
                <button
                  onClick={() => scrollToPage('prev')}
                  disabled={activeIndex === 0}
                  className={`w-[44px] h-[44px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${
                    activeIndex === 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'
                  }`}
                  aria-label="Previous testimonial"
                >
                  <ChevronLeft size={18} strokeWidth={1.5} className="text-[#d20010]" />
                </button>
                <button
                  onClick={() => scrollToPage('next')}
                  disabled={activeIndex === TOTAL_MOBILE_PAGES - 1}
                  className={`w-[44px] h-[44px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${
                    activeIndex === TOTAL_MOBILE_PAGES - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'
                  }`}
                  aria-label="Next testimonial"
                >
                  <ChevronRight size={18} strokeWidth={1.5} className="text-[#d20010]" />
                </button>
              </div>

              {/* Desktop Navigation Arrows */}
              <div className="hidden lg:flex items-center gap-2">
                <button
                  onClick={() => scroll('left')}
                  disabled={atStart}
                  className={`w-[60px] h-[58px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${atStart ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'}`}
                  aria-label="Previous testimonial"
                >
                  <ChevronLeft size={20} strokeWidth={1.5} className="text-[#d20010]" />
                </button>
                <button
                  onClick={() => scroll('right')}
                  disabled={atEnd}
                  className={`w-[60px] h-[58px] rounded-full border-2 border-[#d20010] flex items-center justify-center transition-all active:scale-95 ${atEnd ? 'opacity-30 cursor-not-allowed' : 'opacity-100 hover:opacity-80'}`}
                  aria-label="Next testimonial"
                >
                  <ChevronRight size={20} strokeWidth={1.5} className="text-[#d20010]" />
                </button>
              </div>
            </div>
          </div>
        </div>
    </section>
  )
}
