'use client'

import { useState, useEffect } from 'react'
import { Search, Copy, Heart, Play, X } from 'lucide-react'

export default function ScriptHub() {
  const [activeCategory, setActiveCategory] = useState('Scripts')
  const [scripts, setScripts] = useState([])
  const [vehicles, setVehicles] = useState([])
  const [weapons, setWeapons] = useState([])
  const [loading, setLoading] = useState(true)
  const [loadingMore, setLoadingMore] = useState(false)
  const [searchQuery, setSearchQuery] = useState('')
  const [showSuggestModal, setShowSuggestModal] = useState(false)
  const [suggestScript, setSuggestScript] = useState('')
  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)

  // fetchData
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true)
      setPage(1)
      setHasMore(true)
      try {
        const [scriptsRes, vehiclesRes, weaponsRes] = await Promise.all([
          fetch('/api/proxy?endpoint=scripts&page=1&limit=12&search='),
          fetch('/api/proxy?endpoint=vehicles&page=1&limit=12&search='),
          fetch('/api/proxy?endpoint=weapons&page=1&limit=12&search=')
        ])

        const scriptsData = await scriptsRes.json()
        const vehiclesData = await vehiclesRes.json()
        const weaponsData = await weaponsRes.json()

        console.log('Scripts response:', scriptsData)
        console.log('Vehicles response:', vehiclesData)
        console.log('Weapons response:', weaponsData)

        setScripts(scriptsData?.items || scriptsData?.data || [])
        setVehicles(vehiclesData?.items || vehiclesData?.data || [])
        setWeapons(weaponsData?.items || weaponsData?.data || [])
        
        const currentData = activeCategory === 'Scripts' ? scriptsData : 
                           activeCategory === 'Vehicles' ? vehiclesData : weaponsData
        const total = currentData?.total || 0
        const items = currentData?.items || currentData?.data || []
        setHasMore(items.length < total)
      } catch (error) {
        console.error('Failed to fetch data:', error)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // loadMoreItems
  const loadMoreItems = async () => {
    if (loadingMore || !hasMore) return
    
    setLoadingMore(true)
    try {
      const nextPage = page + 1
      const endpoint = activeCategory === 'Scripts' ? 'scripts' : 
                      activeCategory === 'Vehicles' ? 'vehicles' : 'weapons'
      
      const response = await fetch(`/api/proxy?endpoint=${endpoint}&page=${nextPage}&limit=12&search=`)
      const data = await response.json()
      
      console.log(`${activeCategory} page ${nextPage} response:`, data)
      
      const newItems = data?.items || data?.data || []
      
      if (activeCategory === 'Scripts') {
        setScripts(prev => [...prev, ...newItems])
      } else if (activeCategory === 'Vehicles') {
        setVehicles(prev => [...prev, ...newItems])
      } else {
        setWeapons(prev => [...prev, ...newItems])
      }
      
      setPage(nextPage)
      
      const total = data?.total || 0
      const currentTotal = activeCategory === 'Scripts' ? scripts.length : 
                          activeCategory === 'Vehicles' ? vehicles.length : weapons.length
      setHasMore(currentTotal + newItems.length < total)
    } catch (error) {
      console.error('Failed to load more items:', error)
    } finally {
      setLoadingMore(false)
    }
  }

  // handleScroll
  useEffect(() => {
    const handleScroll = () => {
      if (loading || loadingMore || !hasMore) return
      
      const scrollTop = window.scrollY
      const windowHeight = window.innerHeight
      const documentHeight = document.documentElement.scrollHeight
      
      if (scrollTop + windowHeight >= documentHeight - 500) {
        loadMoreItems()
      }
    }

    window.addEventListener('scroll', handleScroll)
    return () => window.removeEventListener('scroll', handleScroll)
  }, [loading, loadingMore, hasMore, page, activeCategory, scripts.length, vehicles.length, weapons.length])

  // Reset pagination when category changes
  useEffect(() => {
    setPage(1)
    setHasMore(true)
  }, [activeCategory])

  // getCurrentItems
  const getCurrentItems = () => {
    let items = []
    if (activeCategory === 'Scripts') items = scripts
    else if (activeCategory === 'Vehicles') items = vehicles
    else if (activeCategory === 'Weapons') items = weapons

    if (searchQuery.trim()) {
      return items.filter(item => 
        item.title?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        item.name?.toLowerCase().includes(searchQuery.toLowerCase())
      )
    }
    return items
  }

  const currentItems = getCurrentItems()

  // copyToClipboard
  const copyToClipboard = (text) => {
    navigator.clipboard.writeText(text)
  }

  // executeScript
  const executeScript = (script) => {
    console.log('Executing:', script)
  }

  // submitSuggestion
  const submitSuggestion = () => {
    if (!suggestScript.trim()) return
    console.log('Suggestion submitted:', suggestScript)
    setSuggestScript('')
    setShowSuggestModal(false)
  }

  return (
    <div className="min-h-screen" style={{ backgroundColor: '#000000' }}>
      <div className="p-8">
        <div 
          className="relative rounded-2xl border p-8 mb-6 overflow-hidden"
          style={{
            backgroundColor: 'rgba(10, 10, 10, 0.6)',
            borderColor: '#1a1a1a',
            backdropFilter: 'blur(20px)',
          }}
        >
          <div 
            className="absolute inset-0 opacity-30"
            style={{
              background: 'radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.15), transparent 50%), radial-gradient(circle at 80% 50%, rgba(168, 85, 247, 0.15), transparent 50%)',
            }}
          />
          
          <div className="relative z-10">
            <h1 
              className="text-4xl font-bold mb-2"
              style={{ 
                color: '#ffffff',
                textShadow: '0 0 30px rgba(255, 255, 255, 0.1)',
              }}
            >
              Script Hub
            </h1>
            <p 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              Browse and execute community scripts
            </p>
          </div>
        </div>

        {/* Controls bar */}
        <div className="mb-8">
          <div className="flex items-center justify-between mb-6">
            <div className="flex gap-3">
              {['Scripts', 'Vehicles', 'Weapons'].map((category) => (
                <button
                  key={category}
                  onClick={() => setActiveCategory(category)}
                  className="px-6 py-3 rounded-2xl text-sm font-bold transition-all duration-300 relative overflow-hidden"
                  style={{
                    backgroundColor: activeCategory === category 
                      ? 'rgba(255, 255, 255, 0.1)' 
                      : 'rgba(10, 10, 10, 0.6)',
                    border: activeCategory === category 
                      ? '1px solid rgba(255, 255, 255, 0.2)' 
                      : '1px solid #1a1a1a',
                    color: activeCategory === category ? '#ffffff' : '#6b7280',
                    cursor: 'pointer',
                    backdropFilter: 'blur(10px)',
                    boxShadow: activeCategory === category 
                      ? '0 0 20px rgba(255, 255, 255, 0.1), inset 0 1px 0 rgba(255, 255, 255, 0.1)' 
                      : 'none',
                  }}
                  onMouseEnter={(e) => {
                    if (activeCategory !== category) {
                      e.currentTarget.style.borderColor = '#2a2a2a'
                      e.currentTarget.style.color = '#ffffff'
                      e.currentTarget.style.backgroundColor = 'rgba(26, 26, 26, 0.8)'
                      e.currentTarget.style.transform = 'translateY(-2px)'
                    }
                  }}
                  onMouseLeave={(e) => {
                    if (activeCategory !== category) {
                      e.currentTarget.style.borderColor = '#1a1a1a'
                      e.currentTarget.style.color = '#6b7280'
                      e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.6)'
                      e.currentTarget.style.transform = 'translateY(0)'
                    }
                  }}
                >
                  {category}
                </button>
              ))}
            </div>

            <div className="flex gap-3">
              <div className="relative">
                <Search 
                  className="absolute left-4 top-1/2 transform -translate-y-1/2 h-5 w-5 transition-colors duration-200"
                  style={{ color: '#565656' }}
                />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search scripts..."
                  className="pl-12 pr-5 py-3 rounded-2xl text-sm transition-all duration-300"
                  style={{
                    width: '360px',
                    backgroundColor: 'rgba(10, 10, 10, 0.6)',
                    border: '1px solid #1a1a1a',
                    color: '#ffffff',
                    outline: 'none',
                    backdropFilter: 'blur(10px)',
                  }}
                  onFocus={(e) => {
                    e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                    e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.9)'
                    e.currentTarget.style.boxShadow = '0 0 20px rgba(255, 255, 255, 0.1)'
                    e.currentTarget.previousElementSibling.style.color = '#ffffff'
                  }}
                  onBlur={(e) => {
                    e.currentTarget.style.borderColor = '#1a1a1a'
                    e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.6)'
                    e.currentTarget.style.boxShadow = 'none'
                    e.currentTarget.previousElementSibling.style.color = '#565656'
                  }}
                />
              </div>

              <button
                onClick={() => setShowSuggestModal(true)}
                className="px-6 py-3 rounded-2xl text-sm font-bold transition-all duration-300"
                style={{
                  backgroundColor: 'rgba(10, 10, 10, 0.6)',
                  border: '1px solid #1a1a1a',
                  color: '#6b7280',
                  cursor: 'pointer',
                  backdropFilter: 'blur(10px)',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.15)'
                  e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                  e.currentTarget.style.color = '#ffffff'
                  e.currentTarget.style.transform = 'translateY(-2px)'
                  e.currentTarget.style.boxShadow = '0 0 20px rgba(255, 255, 255, 0.15)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.6)'
                  e.currentTarget.style.borderColor = '#1a1a1a'
                  e.currentTarget.style.color = '#6b7280'
                  e.currentTarget.style.transform = 'translateY(0)'
                  e.currentTarget.style.boxShadow = 'none'
                }}
              >
                Suggest Script
              </button>
            </div>
          </div>
        </div>

        {loading ? (
          <div className="flex flex-col items-center justify-center py-32">
            <div 
              className="w-16 h-16 rounded-full animate-spin mb-6 relative"
              style={{
                border: '3px solid #1a1a1a',
                borderTopColor: '#ffffff',
                boxShadow: '0 0 30px rgba(255, 255, 255, 0.2)',
              }}
            />
            <div className="text-base font-medium" style={{ color: '#6b7280' }}>
              Loading {activeCategory.toLowerCase()}...
            </div>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5">
            {currentItems.map((item, index) => (
              <div
                key={index}
                className="rounded-3xl border overflow-hidden transition-all duration-300 group relative"
                style={{
                  backgroundColor: 'rgba(10, 10, 10, 0.4)',
                  borderColor: '#1a1a1a',
                  backdropFilter: 'blur(20px)',
                  cursor: 'pointer',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                  e.currentTarget.style.transform = 'translateY(-6px) scale(1.02)'
                  e.currentTarget.style.boxShadow = '0 12px 40px rgba(255, 255, 255, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.1)'
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.8)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.borderColor = '#1a1a1a'
                  e.currentTarget.style.transform = 'translateY(0) scale(1)'
                  e.currentTarget.style.boxShadow = 'none'
                  e.currentTarget.style.backgroundColor = 'rgba(10, 10, 10, 0.4)'
                }}
              >
                {item.image && (
                  <div 
                    className="w-full h-48 bg-cover bg-center relative overflow-hidden"
                    style={{
                      backgroundImage: `url(${item.image})`,
                      backgroundColor: '#0a0a0a',
                    }}
                  >
                    <div 
                      className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-all duration-500"
                      style={{
                        background: 'linear-gradient(to top, rgba(0,0,0,0.95), rgba(255, 255, 255, 0.05) 60%, transparent)',
                      }}
                    />
                    <div 
                      className="absolute top-3 right-3 px-3 py-1.5 rounded-full text-xs font-bold opacity-0 group-hover:opacity-100 transition-all duration-300"
                      style={{
                        backgroundColor: 'rgba(255, 255, 255, 0.15)',
                        border: '1px solid rgba(255, 255, 255, 0.3)',
                        color: '#ffffff',
                        backdropFilter: 'blur(10px)',
                      }}
                    >
                      {activeCategory.slice(0, -1)}
                    </div>
                  </div>
                )}

                <div className="p-6">
                  <h3 
                    className="font-bold text-lg mb-3 truncate transition-colors duration-200"
                    style={{ 
                      color: '#ffffff',
                      letterSpacing: '-0.02em',
                    }}
                  >
                    {item.title || item.name}
                  </h3>

                  {item.description && (
                    <p 
                      className="text-sm mb-5 line-clamp-2 leading-relaxed"
                      style={{ color: '#6b7280' }}
                    >
                      {item.description}
                    </p>
                  )}

                  <div className="flex gap-2.5">
                    <button
                      onClick={() => copyToClipboard(item.script || item.code || '')}
                      className="flex items-center justify-center p-3 rounded-xl transition-all duration-300"
                      style={{
                        backgroundColor: 'rgba(0, 0, 0, 0.4)',
                        border: '1px solid #2a2a2a',
                        color: '#6b7280',
                        cursor: 'pointer',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.15)'
                        e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                        e.currentTarget.style.color = '#ffffff'
                        e.currentTarget.style.transform = 'scale(1.1) rotate(-5deg)'
                        e.currentTarget.style.boxShadow = '0 0 15px rgba(255, 255, 255, 0.2)'
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.4)'
                        e.currentTarget.style.borderColor = '#2a2a2a'
                        e.currentTarget.style.color = '#6b7280'
                        e.currentTarget.style.transform = 'scale(1) rotate(0deg)'
                        e.currentTarget.style.boxShadow = 'none'
                      }}
                    >
                      <Copy className="h-4 w-4" />
                    </button>

                    <button
                      onClick={() => executeScript(item)}
                      className="flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-xl text-sm font-bold transition-all duration-300 relative overflow-hidden"
                      style={{
                        backgroundColor: 'rgba(34, 197, 94, 0.15)',
                        border: '1px solid rgba(34, 197, 94, 0.3)',
                        color: '#22c55e',
                        cursor: 'pointer',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(34, 197, 94, 0.25)'
                        e.currentTarget.style.borderColor = 'rgba(34, 197, 94, 0.5)'
                        e.currentTarget.style.transform = 'scale(1.03)'
                        e.currentTarget.style.boxShadow = '0 0 20px rgba(34, 197, 94, 0.3)'
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(34, 197, 94, 0.15)'
                        e.currentTarget.style.borderColor = 'rgba(34, 197, 94, 0.3)'
                        e.currentTarget.style.transform = 'scale(1)'
                        e.currentTarget.style.boxShadow = 'none'
                      }}
                    >
                      <Play className="h-4 w-4" />
                      Execute
                    </button>

                    <button
                      onClick={() => {}}
                      className="flex items-center justify-center p-3 rounded-xl transition-all duration-300"
                      style={{
                        backgroundColor: 'rgba(0, 0, 0, 0.4)',
                        border: '1px solid #2a2a2a',
                        color: '#6b7280',
                        cursor: 'pointer',
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(236, 72, 153, 0.2)'
                        e.currentTarget.style.borderColor = 'rgba(236, 72, 153, 0.5)'
                        e.currentTarget.style.color = '#ec4899'
                        e.currentTarget.style.transform = 'scale(1.1)'
                        e.currentTarget.style.boxShadow = '0 0 15px rgba(236, 72, 153, 0.3)'
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.4)'
                        e.currentTarget.style.borderColor = '#2a2a2a'
                        e.currentTarget.style.color = '#6b7280'
                        e.currentTarget.style.transform = 'scale(1)'
                        e.currentTarget.style.boxShadow = 'none'
                      }}
                    >
                      <Heart className="h-4 w-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}

        {!loading && currentItems.length === 0 && (
          <div className="flex flex-col items-center justify-center py-24">
            <div 
              className="text-6xl mb-4"
              style={{ opacity: 0.3 }}
            >
              📦
            </div>
            <div 
              className="text-lg font-semibold mb-2"
              style={{ color: '#ffffff' }}
            >
              No {activeCategory.toLowerCase()} found
            </div>
            <div 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              {searchQuery ? 'Try a different search term' : 'Check back later for new content'}
            </div>
          </div>
        )}

        {loadingMore && (
          <div className="flex justify-center py-8">
            <div 
              className="w-12 h-12 rounded-full animate-spin"
              style={{
                border: '3px solid #1a1a1a',
                borderTopColor: '#ffffff',
                boxShadow: '0 0 30px rgba(255, 255, 255, 0.2)',
              }}
            />
          </div>
        )}

        {!loading && !loadingMore && !hasMore && currentItems.length > 0 && (
          <div className="flex justify-center py-8">
            <div 
              className="text-sm"
              style={{ color: '#6b7280' }}
            >
              All {activeCategory.toLowerCase()} loaded
            </div>
          </div>
        )}
      </div>

      {showSuggestModal && (
        <div 
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          style={{ backgroundColor: 'rgba(0, 0, 0, 0.8)' }}
          onClick={() => setShowSuggestModal(false)}
        >
          <div 
            className="rounded-2xl border p-6 max-w-2xl w-full"
            style={{
              backgroundColor: 'rgba(10, 10, 10, 0.95)',
              borderColor: '#1a1a1a',
              backdropFilter: 'blur(20px)',
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-6">
              <h2 
                className="text-2xl font-bold"
                style={{ color: '#ffffff' }}
              >
                Suggest a Script
              </h2>
              <button
                onClick={() => setShowSuggestModal(false)}
                className="p-2 rounded-xl transition-all duration-200"
                style={{
                  backgroundColor: 'rgba(26, 26, 26, 0.8)',
                  border: '1px solid #2a2a2a',
                  color: '#a0a0a0',
                  cursor: 'pointer',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = 'rgba(239, 68, 68, 0.15)'
                  e.currentTarget.style.borderColor = 'rgba(239, 68, 68, 0.4)'
                  e.currentTarget.style.color = '#ef4444'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'rgba(26, 26, 26, 0.8)'
                  e.currentTarget.style.borderColor = '#2a2a2a'
                  e.currentTarget.style.color = '#a0a0a0'
                }}
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            <div className="mb-6">
              <h3 
                className="text-sm font-semibold mb-3"
                style={{ color: '#ffffff' }}
              >
                Script Criteria:
              </h3>
              <div 
                className="space-y-2 text-sm"
                style={{ color: '#6b7280' }}
              >
                <p>Must follow all Terms of Service (ToS).</p>
                <p>Cannot be game-breaking or provide an unfair advantage.</p>
                <p>Must be safe and free of malicious code.</p>
                <p>Should not cause performance issues (lag).</p>
              </div>
            </div>

            <textarea
              value={suggestScript}
              onChange={(e) => setSuggestScript(e.target.value)}
              placeholder="Paste your script here..."
              className="w-full h-64 px-4 py-3 rounded-xl text-sm resize-none transition-all duration-200"
              style={{
                backgroundColor: 'rgba(0, 0, 0, 0.5)',
                border: '1px solid #1a1a1a',
                color: '#ffffff',
                outline: 'none',
                fontFamily: 'monospace',
              }}
              onFocus={(e) => {
                e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.7)'
              }}
              onBlur={(e) => {
                e.currentTarget.style.borderColor = '#1a1a1a'
                e.currentTarget.style.backgroundColor = 'rgba(0, 0, 0, 0.5)'
              }}
            />

            <div className="flex gap-3 mt-6">
              <button
                onClick={() => setShowSuggestModal(false)}
                className="flex-1 px-5 py-3 rounded-xl text-sm font-semibold transition-all duration-200"
                style={{
                  backgroundColor: 'rgba(26, 26, 26, 0.8)',
                  border: '1px solid #2a2a2a',
                  color: '#a0a0a0',
                  cursor: 'pointer',
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.backgroundColor = 'rgba(42, 42, 42, 0.8)'
                  e.currentTarget.style.borderColor = '#3a3a3a'
                  e.currentTarget.style.color = '#ffffff'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.backgroundColor = 'rgba(26, 26, 26, 0.8)'
                  e.currentTarget.style.borderColor = '#2a2a2a'
                  e.currentTarget.style.color = '#a0a0a0'
                }}
              >
                Cancel
              </button>

              <button
                onClick={submitSuggestion}
                disabled={!suggestScript.trim()}
                className="flex-1 px-5 py-3 rounded-xl text-sm font-semibold transition-all duration-200"
                style={{
                  backgroundColor: suggestScript.trim() 
                    ? 'rgba(255, 255, 255, 0.1)' 
                    : 'rgba(26, 26, 26, 0.5)',
                  border: suggestScript.trim() 
                    ? '1px solid rgba(255, 255, 255, 0.2)' 
                    : '1px solid #2a2a2a',
                  color: suggestScript.trim() ? '#ffffff' : '#565656',
                  cursor: suggestScript.trim() ? 'pointer' : 'not-allowed',
                }}
                onMouseEnter={(e) => {
                  if (suggestScript.trim()) {
                    e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.15)'
                    e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.3)'
                  }
                }}
                onMouseLeave={(e) => {
                  if (suggestScript.trim()) {
                    e.currentTarget.style.backgroundColor = 'rgba(255, 255, 255, 0.1)'
                    e.currentTarget.style.borderColor = 'rgba(255, 255, 255, 0.2)'
                  }
                }}
              >
                Submit Suggestion
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
