'use client'

import { useState, useEffect } from 'react'
import Link from 'next/link'
import { ClipboardCheck, Users, ChevronRight, X } from 'lucide-react'

export default function SurveyBanner() {
  const [surveys, setSurveys] = useState<any[]>([])
  const [popupSurveys, setPopupSurveys] = useState<any[]>([])
  const [showPopup, setShowPopup] = useState(false)
  const [dismissed, setDismissed] = useState(false)

  useEffect(() => {
    const fetchSurveys = async () => {
      try {
        const slug = process.env.NEXT_PUBLIC_SITE_SLUG || 'butonkab'
        const base = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api'

        const [homeRes, popupRes] = await Promise.all([
          fetch(`${base}/public/sites/${slug}/surveys`, { cache: 'no-store' }),
          fetch(`${base}/public/sites/${slug}/surveys/popup`, { cache: 'no-store' }),
        ])

        const homeData = await homeRes.json()
        const popupData = await popupRes.json()

        setSurveys(homeData.data || [])
        setPopupSurveys(popupData.data || [])

        if ((popupData.data || []).length > 0) {
          const popupDismissed = sessionStorage.getItem('survey_popup_dismissed')
          if (!popupDismissed) {
            setTimeout(() => setShowPopup(true), 2000)
          }
        }
      } catch { /* empty */ }
    }
    fetchSurveys()
  }, [])

  const dismissPopup = () => {
    setShowPopup(false)
    setDismissed(true)
    sessionStorage.setItem('survey_popup_dismissed', 'true')
  }

  if (surveys.length === 0) return null

  return (
    <>
      {/* Section di beranda */}
      <section className="py-16 bg-gradient-to-br from-purple-50 to-blue-50">
        <div className="max-w-7xl mx-auto px-4">
          <div className="flex items-end justify-between mb-8">
            <div>
              <div className="inline-flex items-center gap-2 bg-purple-100 rounded-full px-3 py-1 mb-3">
                <ClipboardCheck size={14} className="text-purple-600" />
                <span className="text-xs text-purple-600 font-medium uppercase tracking-wider">Survey</span>
              </div>
              <h2 className="text-2xl sm:text-3xl font-display font-bold text-gray-800">Survey Kepuasan Masyarakat</h2>
              <p className="text-gray-500 text-sm mt-1">Bantu kami meningkatkan kualitas pelayanan publik</p>
            </div>
            <Link href="/survey" className="hidden sm:inline-flex items-center gap-1.5 text-[#1e3a5f] font-medium text-sm hover:text-[#c8102e] transition-colors">
              Lihat Semua
              <ChevronRight size={14} />
            </Link>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {surveys.slice(0, 3).map((survey) => (
              <Link key={survey.id} href={`/survey/${survey.id}`} className="block bg-white rounded-2xl shadow-sm border border-purple-100 hover:shadow-md transition-all overflow-hidden group">
                {survey.featured_image && (
                  <div className="h-40 overflow-hidden">
                    <img src={survey.featured_image} alt="" className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300" />
                  </div>
                )}
                <div className="p-6">
                  <h3 className="font-bold text-gray-800 group-hover:text-purple-600 transition-colors font-display line-clamp-2">{survey.title}</h3>
                  {survey.description && <p className="text-gray-500 text-sm mt-2 line-clamp-2">{survey.description}</p>}
                  <div className="flex items-center gap-3 mt-4 text-xs text-gray-400">
                    <span className="flex items-center gap-1"><Users size={12} /> {survey.total_respondents || 0} responden</span>
                    <span className="flex items-center gap-1"><ClipboardCheck size={12} /> {survey.questions_count || 0} pertanyaan</span>
                  </div>
                  <div className="mt-4 flex items-center gap-1 text-purple-600 text-sm font-medium">
                    Isi Sekarang <ChevronRight size={14} />
                  </div>
                </div>
              </Link>
            ))}
          </div>

          <div className="text-center mt-6 sm:hidden">
            <Link href="/survey" className="text-[#1e3a5f] font-medium text-sm hover:text-[#c8102e]">
              Lihat Semua Survey &rarr;
            </Link>
          </div>
        </div>
      </section>

      {/* Popup */}
      {showPopup && popupSurveys.length > 0 && (
        <div className="fixed inset-0 z-[9999] flex items-center justify-center p-4">
          <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={dismissPopup} />
          <div className="relative bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden animate-in fade-in zoom-in-95 duration-200">
            <div className="bg-gradient-to-r from-[#1e3a5f] to-[#2d5a8e] p-6 text-white">
              <button onClick={dismissPopup} className="absolute top-4 right-4 text-white/70 hover:text-white">
                <X size={20} />
              </button>
              <div className="w-12 h-12 bg-white/20 rounded-xl flex items-center justify-center mb-3">
                <ClipboardCheck size={24} />
              </div>
              <h3 className="text-xl font-bold">Survey Kepuasan Masyarakat</h3>
              <p className="text-white/70 text-sm mt-1">Partisipasi Anda sangat berarti bagi perbaikan pelayanan kami</p>
            </div>

            <div className="p-6 space-y-3 max-h-[300px] overflow-y-auto">
              {popupSurveys.map((survey) => (
                <Link key={survey.id} href={`/survey/${survey.id}`} onClick={dismissPopup} className="block p-4 rounded-xl border border-gray-200 hover:border-purple-300 hover:bg-purple-50 transition-colors group">
                  <div className="flex items-center gap-3">
                    {survey.featured_image && (
                      <img src={survey.featured_image} alt="" className="w-14 h-14 rounded-lg object-cover flex-shrink-0" />
                    )}
                    <div className="flex-1">
                      <h4 className="font-semibold text-gray-800 group-hover:text-purple-600 text-sm">{survey.title}</h4>
                      <div className="flex items-center gap-3 mt-2 text-xs text-gray-400">
                        <span>{survey.total_respondents || 0} responden</span>
                        <span>{survey.questions_count || 0} pertanyaan</span>
                      </div>
                    </div>
                  </div>
                </Link>
              ))}
            </div>

            <div className="p-4 border-t bg-gray-50 flex justify-between items-center">
              <button onClick={dismissPopup} className="text-sm text-gray-500 hover:text-gray-700">
                Nanti Saja
              </button>
              <Link href="/survey" onClick={dismissPopup} className="bg-[#1e3a5f] text-white px-4 py-2 rounded-lg text-sm font-medium hover:bg-[#152d4a]">
                {popupSurveys.length === 1 ? 'Isi Survey Sekarang' : `Lihat ${popupSurveys.length} Survey`}
              </Link>
            </div>
          </div>
        </div>
      )}
    </>
  )
}
