'use client';

import { useEffect, useState } from 'react';
import { getTranslation, Language, useLanguage } from '@/lib/i18n';
import Link from 'next/link';
import { SearchWidget } from '@/components/SearchWidget';
import { Zap, Heart, Shield, Clock, ArrowRight, Train, MapPin, Calendar } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/lib/api-client';
import { Station } from '@/types';

const styles = `
  .hero-section {
    position: relative;
    overflow: hidden;
    background: linear-gradient(to bottom right, rgb(20, 113, 76), transparent);
    padding: 80px 20px;
    text-align: center;
    color: #111827;
  }
  
  .dark .hero-section {
    background: linear-gradient(to bottom right, rgb(20, 113, 76), transparent);
    color: #f3f4f6;
  }
  
  .hero-content {
    max-width: 100%;
    margin: 0 auto;
    padding: 0 20px;
  }
  
  .hero-heading {
    font-size: clamp(1rem, 3vw, 2.75rem);
    font-weight: 700;
    margin-bottom: 24px;
    color: #ffffff;
    line-height: 1.2;
  }
  
  .dark .hero-heading {
    color: #ffffff;
  }
  
  .hero-subheading {
    font-size: clamp(1rem, 3vw, 1.5rem);
    color: #4b5563;
    margin-bottom: 32px;
  }
  
  .dark .hero-subheading {
    color: #9ca3af;
  }
  
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    padding: 32px 16px;
    border-top: 1px solid #e5e7eb;
    border-bottom: 1px solid #e5e7eb;
    margin-top: 48px;
  }
  
  .dark .stats-grid {
    border-top-color: #374151;
    border-bottom-color: #374151;
  }
  
  .stat-item {
    text-align: center;
  }
  
  .stat-number {
    font-size: 2rem;
    font-weight: 700;
    color: rgb(20, 113, 76);
  }
  
  .stat-label {
    font-size: 0.875rem;
    color: #6b7280;
  }
  
  .dark .stat-label {
    color: #9ca3af;
  }
  
  .features-section {
    padding: 80px 20px;
    background-color: #ffffff;
  }
  
  .dark .features-section {
    background-color: #111827;
  }
  
  .section-title {
    text-align: center;
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 40px;
    color: #111827;
  }
  
  .dark .section-title {
    color: #f3f4f6;
  }
  
  .features-grid {
    max-width: 72rem;
    margin: 0 auto;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 24px;
  }
  
  .feature-card {
    background-color: white;
    border: 2px solid #f3f4f6;
    border-radius: 18px;
    padding: 24px;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    text-align: left;
  }
  
  .dark .feature-card {
    background-color: #1f2937;
    border-color: #374151;
  }
  
  .feature-card:hover {
    border-color: rgb(20, 113, 76);
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    transform: translateY(-8px);
  }
  
  .feature-icon-bg {
    width: 48px;
    height: 48px;
    background-color: rgb(20, 113, 76);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16px;
  }
  
  .feature-title {
    font-weight: 700;
    color: #111827;
    margin-bottom: 8px;
    font-size: 1.125rem;
  }
  
  .dark .feature-title {
    color: #f3f4f6;
  }
  
  .feature-desc {
    font-size: 0.875rem;
    color: #6b7280;
  }
  
  .dark .feature-desc {
    color: #9ca3af;
  }
  
  .cta-section {
    padding: 80px 20px;
    background: #f3f4f6;
    text-align: center;
  }
  
  .dark .cta-section {
    background: #111827;
  }
  
  .cta-content {
    max-width: 42rem;
    margin: 0 auto;
  }
  
  .cta-title {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 24px;
    color: #111827;
  }
  
  .dark .cta-title {
    color: white;
  }
  
  .cta-text {
    font-size: 1.125rem;
    color: #4b5563;
    margin-bottom: 32px;
  }
  
  .dark .cta-text {
    color: #e0e7ff;
  }
  
  .cta-button {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 16px 32px;
    background-color: white;
    color: rgb(20 113 76 / var(--tw-bg-opacity, 1));
    font-weight: 700;
    border-radius: 12px;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
    text-decoration: none;
  }
  
  .cta-button:hover {
    background-color: #f0f9ff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.15);
    transform: scale(1.05);
  }
  
  @media (max-width: 640px) {
    .stats-grid {
      grid-template-columns: 1fr;
    }
  }
  
  @keyframes bounce {
    0%, 100% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(-10px);
    }
  }
  
  .bounce {
    animation: bounce 2s infinite;
  }
  
  .bounce:nth-child(2) {
    animation-delay: 0.2s;
  }
  
  .bounce:nth-child(3) {
    animation-delay: 0.4s;
  }
  
  .search-widget-transparent {
    background-color: rgba(255, 255, 255, 0.95) !important;
    backdrop-filter: blur(10px);
    border-color: rgba(255, 255, 255, 0.2) !important;
  }
  
  .dark .search-widget-transparent {
    background-color: rgba(31, 41, 55, 0.95) !important;
    border-color: rgba(55, 65, 81, 0.2) !important;
  }
`;

export default function Home() {
  const [lang, setLang] = useState<Language>('en');
  const { getLang } = useLanguage();
  const t = (key: string) => getTranslation(lang, key);

  useEffect(() => {
    setLang(getLang());
    const handleLanguageChange = (e: any) => setLang(e.detail);
    window.addEventListener('languageChange', handleLanguageChange);
    return () => window.removeEventListener('languageChange', handleLanguageChange);
  }, [getLang]);

  const { data: stations } = useQuery<Station[]>({
    queryKey: ['stations'],
    queryFn: async () => await apiClient.get('/stations') as Station[],
  });

  const getStationByName = (name: string) => {
    if (!stations) return null;
    const exactMatch = stations.find(s => s.name.toLowerCase() === name.toLowerCase());
    if (exactMatch) return exactMatch;
    return stations.find(s => s.name.toLowerCase().includes(name.toLowerCase()));
  };

  const handlePopularRoute = (fromName: string, toName: string) => {
    const origin = getStationByName(fromName);
    const destination = getStationByName(toName);
    
    if (origin && destination) {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    }
  };

  const popularRoutes = [
    { from: 'Sebeta', to: 'Nagad', duration: '12h' },
    { from: 'Sebeta', to: 'Diredawa', duration: '8h' },
    { from: 'Diredawa', to: 'Nagad', duration: '4h' },
  ];

  const features = [
    {
      icon: Heart,
      title: t('home.comfortable'),
      desc: t('home.comfortDesc'),
    },
    {
      icon: Zap,
      title: t('home.affordable'),
      desc: t('home.affordableDesc'),
    },
    {
      icon: Shield,
      title: t('home.safe'),
      desc: t('home.safeDesc'),
    },
    {
      icon: Clock,
      title: t('home.fast'),
      desc: t('home.fastDesc'),
    },
  ];

  const highlights = [
    {
      icon: Train,
      title: 'Modern fleet',
      desc: 'Comfortable trains with modern amenities',
    },
    {
      icon: MapPin,
      title: '21 stations',
      desc: 'Connecting Ethiopia and Djibouti',
    },
    {
      icon: Calendar,
      title: 'Easy booking',
      desc: 'Book tickets in just a few clicks',
    },
  ];

  return (
    <>
      <style>{styles}</style>
      <main>
        {/* Hero Section */}
        <section className="hero-section">
          <div className="hero-content">
            <h1 className="hero-heading">{t('home.hero')}</h1>
            <p className="hero-subheading">{t('home.heroSub')}</p>

            <SearchWidget />

            {/* Highlights */}
            <div className="grid md:grid-cols-3 gap-6 mt-12 max-w-6xl mx-auto">
              {highlights.map((highlight, idx) => {
                const Icon = highlight.icon;
                return (
                  <div key={idx} className="feature-card">
                    <div className="feature-icon-bg">
                      <Icon size={24} color="white" />
                    </div>
                    <h3 className="feature-title">{highlight.title}</h3>
                    <p className="feature-desc">{highlight.desc}</p>
                  </div>
                );
              })}
            </div>
          </div>
        </section>

        {/* Popular Routes Section */}
        <section className="py-16 bg-gray-50 dark:bg-gray-900">
          <div className="max-w-6xl mx-auto px-4">
            <h2 className="section-title">Popular Routes</h2>
            <div className="grid md:grid-cols-3 gap-4">
              {popularRoutes.map((route, idx) => (
                <button
                  key={idx}
                  type="button"
                  onClick={() => handlePopularRoute(route.from, route.to)}
                  className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-xl p-5 hover:border-primary hover:shadow-md transition-all text-left group"
                >
                  <div className="flex items-start justify-between mb-3">
                    <div className="flex-1">
                      <div className="font-semibold text-gray-900 dark:text-gray-100 mb-1">{route.from}</div>
                      <ArrowRight className="w-4 h-4 text-primary my-2" />
                      <div className="font-semibold text-gray-900 dark:text-gray-100">{route.to}</div>
                    </div>
                    <Train className="w-5 h-5 text-primary opacity-0 group-hover:opacity-100 transition-opacity" />
                  </div>
                  <div className="text-sm text-gray-500 dark:text-gray-400">{route.duration} journey</div>
                </button>
              ))}
            </div>
          </div>
        </section>

        {/* Features Section */}
        <section className="features-section">
          <h2 className="section-title">{t('home.features')}</h2>
          <div className="features-grid">
            {features.map((feature, idx) => {
              const Icon = feature.icon;
              return (
                <div key={idx} className="feature-card">
                  <div className="feature-icon-bg">
                    <Icon size={24} color="white" />
                  </div>
                  <h3 className="feature-title">{feature.title}</h3>
                  <p className="feature-desc">{feature.desc}</p>
                </div>
              );
            })}
          </div>
        </section>

        {/* CTA Section */}
        <section className="cta-section">
          <div className="cta-content">
            <h2 className="cta-title">Ready to start your journey?</h2>
            <p className="cta-text">Book your train tickets in just a few minutes and enjoy a comfortable ride.</p>
            <Link href="/booking/search" className="cta-button">
              {t('home.cta')}
              <ArrowRight size={20} />
            </Link>
          </div>
        </section>
      </main>
    </>
  );
}
