"use client"

import * as React from "react"
import { motion } from "framer-motion"
import { staggerContainer } from "@/lib/motion"
import { Bookmark, BookmarkCheck, TrendingUp } from "lucide-react"

interface StatItem {
  category: string
  title: string
  value: string
  dateLabel: string
  cagr: string
  chartType: string
  chartColor: string
}

interface TrendingData {
  badge: string
  title: string
  filters: string[]
  stats: StatItem[]
}

export function TrendingStats({ data }: { data: TrendingData }) {
  const [activeFilter, setActiveFilter] = React.useState("All")
  const [bookmarks, setBookmarks] = React.useState<Record<number, boolean>>({})

  if (!data) return null

  const toggleBookmark = (idx: number, e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    setBookmarks(prev => ({
      ...prev,
      [idx]: !prev[idx]
    }))
  }

  const renderChart = (idx: number) => {
    if (idx === 0) {
      return (
        <svg viewBox="0 0 300 70" preserveAspectRatio="none" className="w-full h-16 block">
          <defs>
            <linearGradient id="g1" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#E8A020" stopOpacity="0.22" />
              <stop offset="100%" stopColor="#E8A020" stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d="M0 60 L50 54 L100 46 L150 34 L200 24 L250 13 L300 4 L300 70 L0 70Z" fill="url(#g1)" />
          <path d="M0 60 L50 54 L100 46 L150 34 L200 24 L250 13 L300 4" fill="none" stroke="#E8A020" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
        </svg>
      )
    }
    if (idx === 1) {
      return (
        <svg viewBox="0 0 300 70" preserveAspectRatio="none" className="w-full h-16 block">
          <defs>
            <linearGradient id="g2" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#0D2B55" stopOpacity="0.18" />
              <stop offset="100%" stopColor="#0D2B55" stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d="M0 62 L50 56 L100 50 L150 40 L200 30 L250 19 L300 9 L300 70 L0 70Z" fill="url(#g2)" />
          <path d="M0 62 L50 56 L100 50 L150 40 L200 30 L250 19 L300 9" fill="none" stroke="#0D2B55" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
        </svg>
      )
    }
    if (idx === 2) {
      return (
        <svg viewBox="0 0 300 70" preserveAspectRatio="none" className="w-full h-16 block">
          <g fill="#1A7340">
            <rect x="6" y="44" width="28" height="26" rx="2" opacity="0.5" />
            <rect x="46" y="40" width="28" height="30" rx="2" opacity="0.58" />
            <rect x="86" y="35" width="28" height="35" rx="2" opacity="0.66" />
            <rect x="126" y="30" width="28" height="40" rx="2" opacity="0.74" />
            <rect x="166" y="24" width="28" height="46" rx="2" opacity="0.82" />
            <rect x="206" y="17" width="28" height="53" rx="2" opacity="0.9" />
            <rect x="246" y="9" width="28" height="61" rx="2" />
          </g>
        </svg>
      )
    }
    if (idx === 3) {
      return (
        <svg viewBox="0 0 300 70" preserveAspectRatio="none" className="w-full h-16 block">
          <defs>
            <linearGradient id="g4" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#5a3fb0" stopOpacity="0.16" />
              <stop offset="100%" stopColor="#5a3fb0" stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d="M0 58 L50 52 L100 48 L150 42 L200 33 L250 25 L300 16 L300 70 L0 70Z" fill="url(#g4)" />
          <path d="M0 58 L50 52 L100 48 L150 42 L200 33 L250 25 L300 16" fill="none" stroke="#5a3fb0" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
        </svg>
      )
    }
    if (idx === 4) {
      return (
        <svg viewBox="0 0 300 70" preserveAspectRatio="none" className="w-full h-16 block">
          <defs>
            <linearGradient id="g5" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#0E7490" stopOpacity="0.18" />
              <stop offset="100%" stopColor="#0E7490" stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d="M0 60 L50 56 L100 51 L150 46 L200 40 L250 33 L300 26 L300 70 L0 70Z" fill="url(#g5)" />
          <path d="M0 60 L50 56 L100 51 L150 46 L200 40 L250 33 L300 26" fill="none" stroke="#0E7490" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
        </svg>
      )
    }
    return (
      <svg viewBox="0 0 300 70" preserveAspectRatio="none" className="w-full h-16 block">
        <defs>
          <linearGradient id="g6" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#E8A020" stopOpacity="0.2" />
            <stop offset="100%" stopColor="#E8A020" stopOpacity="0" />
          </linearGradient>
        </defs>
        <path d="M0 60 L50 53 L100 45 L150 36 L200 27 L250 18 L300 8 L300 70 L0 70Z" fill="url(#g6)" />
        <path d="M0 60 L50 53 L100 45 L150 36 L200 27 L250 18 L300 8" fill="none" stroke="#E8A020" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
      </svg>
    )
  }

  // Basic client-side filtering logic
  const filteredStats = data.stats.filter(item => {
    if (activeFilter === "All") return true
    if (activeFilter === "Energy") return item.category.includes("Energy")
    if (activeFilter === "ICT & AI") return item.category.includes("ICT") || item.category.includes("AI")
    if (activeFilter === "Food") return item.category.includes("Food") || item.category.includes("Beverages")
    return true
  })

  return (
    <section className="bg-[#F7F6F3] py-18 pb-20 border-b border-hairline">
      <div className="max-w-[1240px] mx-auto px-7">
        <motion.div
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true, margin: "-100px" }}
          variants={staggerContainer}
          className="space-y-8"
        >
          {/* Header */}
          <div className="flex justify-between items-end gap-6 flex-wrap">
            <div className="space-y-3">
              <div className="inline-flex items-center gap-2 text-[11px] font-bold tracking-wider uppercase text-gold">
                <span className="w-5 h-[1.5px] bg-gold" />
                {data.badge}
              </div>
              <h2 className="font-display text-[34px] leading-[1.12] tracking-[-0.3px] text-ink">
                {data.title}
              </h2>
            </div>
            
            {/* Filter tags */}
            <div className="flex gap-1.5 flex-wrap">
              {data.filters.map((filter, idx) => {
                const isActive = activeFilter === filter
                return (
                  <span
                    key={idx}
                    onClick={() => setActiveFilter(filter)}
                    className={`text-[12.5px] font-semibold px-3.5 py-2 border rounded-[3px] cursor-pointer transition-all duration-150 ${
                      isActive
                        ? "bg-navy border-navy text-white"
                        : "border-[#C8C3BA] text-muted-gray hover:bg-black/5"
                    }`}
                  >
                    {filter}
                  </span>
                )
              })}
            </div>
          </div>

          {/* Cards Grid */}
          <div className="grid md:grid-cols-3 gap-4">
            {filteredStats.map((item, idx) => {
              const isBookmarked = !!bookmarks[idx]
              return (
                <div
                  key={idx}
                  className="bg-white border border-[#E2DDD6] rounded-[6px] overflow-hidden flex flex-col hover:shadow-[0_12px_30px_rgba(10,13,20,0.10)] hover:border-[#C8C3BA] hover:-translate-y-0.5 transition-all duration-200 cursor-pointer"
                >
                  <div className="p-[18px_20px_12px] flex justify-between items-start gap-2.5">
                    <div className="text-[10.5px] font-bold tracking-[0.06em] uppercase text-gold">
                      {item.category}
                    </div>
                    <span
                      onClick={(e) => toggleBookmark(idx, e)}
                      className={`cursor-pointer transition-colors duration-150 ${
                        isBookmarked ? "text-gold" : "text-[#C8C3BA] hover:text-gold"
                      }`}
                    >
                      {isBookmarked ? (
                        <BookmarkCheck className="size-[17px] fill-gold" />
                      ) : (
                        <Bookmark className="size-[17px]" />
                      )}
                    </span>
                  </div>

                  <div className="px-5 text-[15.5px] font-semibold text-ink leading-[1.4] min-h-[44px]">
                    {item.title}
                  </div>

                  {/* SVG Chart wrapper */}
                  <div className="px-5 py-3.5 pb-1">
                    {renderChart(idx)}
                  </div>

                  {/* Bottom strip */}
                  <div className="px-5 py-4 pb-4.5 mt-auto flex items-end justify-between border-t border-[#F0EDE8] pt-3.5">
                    <div>
                      <div className="font-display text-2xl text-navy leading-none">
                        {item.value}
                      </div>
                      <div className="text-[11.5px] text-[#9A968E] mt-0.5">
                        {item.dateLabel}
                      </div>
                    </div>
                    <span className="text-[13px] font-bold text-[#1A7340] flex items-center gap-1">
                      <TrendingUp className="size-3.5" />
                      {item.cagr}
                    </span>
                  </div>
                </div>
              )
            })}
          </div>

        </motion.div>
      </div>
    </section>
  )
}
