'use client'

import { useState, useEffect } from 'react';
import { FilamentTableV2 } from '../src/components/FilamentTableV2';
import { SaleCountdown } from '../src/components/SaleCountdown';
import ColorRequestModal from '../src/components/ColorRequestModal';
import { Filament } from '../src/types/filament';
import { filamentService } from '../src/services/api';
import { trackEvent } from '../src/components/MatomoAnalytics';

export default function Home() {
  const [filaments, setFilaments] = useState<Filament[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [darkMode, setDarkMode] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [resetKey, setResetKey] = useState(0);
  const [showColorRequestModal, setShowColorRequestModal] = useState(false);
  // Removed V1/V2 toggle - now only using V2

  // Initialize dark mode from localStorage after mounting
  useEffect(() => {
    setMounted(true);
    const saved = localStorage.getItem('darkMode');
    if (saved) {
      setDarkMode(JSON.parse(saved));
    }
  }, []);

  // Update dark mode
  useEffect(() => {
    if (!mounted) return;
    
    localStorage.setItem('darkMode', JSON.stringify(darkMode));
    if (darkMode) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  }, [darkMode, mounted]);

  const fetchFilaments = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const filamentsData = await filamentService.getAll();
      setFilaments(filamentsData);
    } catch (err: any) {
      console.error('API Error:', err);
      
      // More descriptive error messages
      if (err.code === 'ERR_NETWORK') {
        setError('Network Error - Unable to connect to API');
      } else if (err.response) {
        setError(`Server error: ${err.response.status} - ${err.response.statusText}`);
      } else if (err.request) {
        setError('No response from server - check if API is running');
      } else {
        setError(err.message || 'Greška pri učitavanju filamenata');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchFilaments();
    
    // Auto-refresh data every 30 seconds to stay in sync
    const interval = setInterval(() => {
      fetchFilaments();
    }, 30000);
    
    // Also refresh when window regains focus
    const handleFocus = () => {
      fetchFilaments();
    };
    window.addEventListener('focus', handleFocus);
    
    return () => {
      clearInterval(interval);
      window.removeEventListener('focus', handleFocus);
    };
  }, []);

  const handleLogoClick = () => {
    setResetKey(prev => prev + 1);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-gray-900 transition-colors">
      {/* Full-screen notice overlay - remove after March 8 */}
      <div className="fixed inset-0 z-50 flex items-center justify-center bg-gradient-to-br from-gray-950 via-gray-900 to-gray-950 px-6 overflow-hidden">
        {/* Subtle background glow */}
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-amber-500/5 rounded-full blur-3xl" />

        <div className="relative max-w-xl w-full text-center space-y-10">
          <img
            src="/logo.png"
            alt="Filamenteka"
            className="h-32 sm:h-44 w-auto mx-auto drop-shadow-2xl"
            onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
          />

          <div className="space-y-6">
            <div className="inline-flex items-center gap-2 px-4 py-1.5 bg-amber-500/10 border border-amber-500/20 rounded-full">
              <span className="w-2 h-2 bg-amber-400 rounded-full animate-pulse" />
              <span className="text-amber-400 text-sm font-medium tracking-wide uppercase">Obaveštenje</span>
            </div>

            <h1 className="text-3xl sm:text-4xl font-bold text-white tracking-tight">
              Privremena pauza
            </h1>

            <p className="text-lg sm:text-xl text-gray-400 leading-relaxed max-w-md mx-auto">
              Trenutno primamo porudžbine samo od postojećih kupaca. Redovna prodaja se vraća nakon <span className="text-amber-400 font-semibold">8. marta</span>.
            </p>
          </div>

          <div className="pt-6 border-t border-white/5">
            <p className="text-gray-600 text-sm">Hvala na razumevanju</p>
          </div>
        </div>
      </div>

      <header className="bg-gradient-to-r from-blue-50 to-orange-50 dark:from-gray-800 dark:to-gray-900 shadow-lg transition-all duration-300">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-3 sm:py-4">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-3 sm:gap-0">
            <div className="flex-1 flex flex-col sm:flex-row justify-center items-center gap-1 sm:gap-3 text-sm sm:text-lg">
              <span className="text-blue-700 dark:text-blue-300 font-medium animate-pulse text-center">
                Kupovina po gramu dostupna
              </span>
              <span className="hidden sm:inline text-gray-400 dark:text-gray-600">•</span>
              <span className="text-orange-700 dark:text-orange-300 font-medium animate-pulse text-center">
                Popust za 5+ komada
              </span>
            </div>
            
            <div className="flex-shrink-0">
              {mounted ? (
                <button
                  onClick={() => {
                    setDarkMode(!darkMode);
                    trackEvent('UI', 'Dark Mode Toggle', darkMode ? 'Light' : 'Dark');
                  }}
                  className="p-2 bg-white/50 dark:bg-gray-700/50 backdrop-blur text-gray-800 dark:text-gray-200 rounded-full hover:bg-white/80 dark:hover:bg-gray-600/80 transition-all duration-200 shadow-md"
                  title={darkMode ? 'Svetla tema' : 'Tamna tema'}
                >
                  {darkMode ? '☀️' : '🌙'}
                </button>
              ) : (
                <div className="w-10 h-10" />
              )}
            </div>
          </div>
        </div>
      </header>
      
      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Logo centered above content */}
        <div className="flex justify-center mb-8">
          <button
            onClick={handleLogoClick}
            className="group transition-transform duration-200"
            title="Klikni za reset"
          >
            {/* Using next/image would cause preload, so we use regular img with loading="lazy" */}
            <img 
              src="/logo.png" 
              alt="Filamenteka" 
              loading="lazy"
              decoding="async"
              className="h-36 sm:h-44 md:h-52 w-auto drop-shadow-lg group-hover:drop-shadow-2xl transition-all duration-200"
              onError={(e) => {
                const target = e.currentTarget as HTMLImageElement;
                target.style.display = 'none';
              }}
            />
          </button>
        </div>
        
        {/* Action Buttons */}
        <div className="flex flex-col sm:flex-row justify-center items-center gap-4 mb-8">
          <a 
            href="https://www.kupujemprodajem.com/kompjuteri-desktop/3d-stampaci-i-oprema/originalni-bambu-lab-filamenti-na-stanju/oglas/182256246"
            target="_blank"
            rel="noopener noreferrer"
            onClick={() => trackEvent('External Link', 'Kupujem Prodajem', 'Homepage')}
            className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            Kupi na Kupujem Prodajem
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
            </svg>
          </a>
          
          <a 
            href="tel:+381631031048"
            onClick={() => trackEvent('Contact', 'Phone Call', 'Homepage')}
            className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
            </svg>
            Pozovi +381 63 103 1048
          </a>
          
          <button
            onClick={() => {
              setShowColorRequestModal(true);
              trackEvent('Navigation', 'Request Color', 'Homepage');
            }}
            className="inline-flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white font-semibold rounded-lg shadow-lg hover:shadow-xl transition-all duration-200 transform hover:scale-105"
          >
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
            </svg>
            Zatraži Novu Boju
          </button>
        </div>
        
        <SaleCountdown
          hasActiveSale={filaments.some(f => f.sale_active === true)}
          maxSalePercentage={Math.max(...filaments.filter(f => f.sale_active === true).map(f => f.sale_percentage || 0), 0)}
          saleEndDate={(() => {
            const activeSales = filaments.filter(f => f.sale_active === true && f.sale_end_date);
            if (activeSales.length === 0) return null;
            const latestSale = activeSales.reduce((latest, current) => {
              if (!latest.sale_end_date) return current;
              if (!current.sale_end_date) return latest;
              return new Date(current.sale_end_date) > new Date(latest.sale_end_date) ? current : latest;
            }).sale_end_date;
            return latestSale;
          })()}
        />

        {/* Pricing Information */}
        <div className="mb-6 space-y-4">
          {/* Reusable Spool Price Notice */}
          <div className="p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg">
            <div className="flex items-center justify-center gap-2">
              <svg className="w-5 h-5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span className="text-blue-800 dark:text-blue-200 font-medium">
                Cena višekratne špulne: 499 RSD
              </span>
            </div>
          </div>

          {/* Selling by Grams Notice */}
          <div className="p-4 bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg">
            <div className="flex flex-col items-center gap-3 text-center">
              <div className="flex items-center justify-center gap-2">
                <svg className="w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 6l3 1m0 0l-3 9a5.002 5.002 0 006.001 0M6 7l3 9M6 7l6-2m6 2l3-1m-3 1l-3 9a5.002 5.002 0 006.001 0M18 7l3 9m-3-9l-6-2m0-2v2m0 16V5m0 16H9m3 0h3" />
                </svg>
                <span className="text-green-800 dark:text-green-200 font-semibold">
                  Prodaja filamenta na grame - idealno za testiranje materijala ili manje projekte
                </span>
              </div>
              <div className="flex flex-wrap justify-center gap-4 text-sm">
                <span className="text-green-700 dark:text-green-300 font-medium">50gr - 299 RSD</span>
                <span className="text-gray-400 dark:text-gray-600">•</span>
                <span className="text-green-700 dark:text-green-300 font-medium">100gr - 499 RSD</span>
                <span className="text-gray-400 dark:text-gray-600">•</span>
                <span className="text-green-700 dark:text-green-300 font-medium">200gr - 949 RSD</span>
              </div>
            </div>
          </div>
        </div>

        <FilamentTableV2 
          key={resetKey}
          filaments={filaments} 
        />
      </main>
      
      <footer className="bg-gray-100 dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 mt-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex flex-col justify-center items-center gap-6">
            <div className="text-center">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">Kontakt</h3>
              <a
                href="tel:+381631031048"
                className="inline-flex items-center gap-2 text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 transition-colors"
                onClick={() => trackEvent('Contact', 'Phone Call', 'Footer')}
              >
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                </svg>
                +381 63 103 1048
              </a>
            </div>
          </div>
        </div>
      </footer>
      
      {/* Color Request Modal */}
      <ColorRequestModal 
        isOpen={showColorRequestModal}
        onClose={() => setShowColorRequestModal(false)}
      />
    </div>
  );
}