import { 
  MobileOptimizedLazyHeroSection, 
  MobileOptimizedLazyOurValues, 
  MobileOptimizedLazyAboutSection, 
  MobileOptimizedLazyCertificationsSection, 
  MobileOptimizedLazyKashminaSection, 
  MobileOptimizedLazyManufacturingSection, 
  MobileOptimizedLazyStatsSection, 
  MobileOptimizedLazyNewsSection,
} from '@/components/MobileOptimizedLazyComponents'
import { Badge } from '@/components/ui/badge'
import { prisma } from '@/lib/prisma'
import ClientPageWrapper from '@/components/sections/ClientPageWrapper'
import ProductsSection from '@/components/sections/ProductsSection'
import { Metadata } from 'next'
import StructuredData, { MultipleStructuredData } from '@/components/StructuredData'
import { generateOrganizationJsonLd, generateProductListJsonLd } from '@/lib/structured-data'

export const metadata: Metadata = {
  title: 'Padmaaja Rasooi - Premium Kashmina Rice & Quality Basmati | Home',
  description: 'Experience the finest quality Kashmina Rice and premium basmati with Padmaaja Rasooi. Authentic Kashmina Steam and Sella rice varieties sourced from certified farms for exceptional taste, aroma and nutrition. Discover our sustainable farming practices.',
  keywords: ['padmaaja rasooi', 'kashmina rice', 'kashmina basmati', 'kashmina steam rice', 'kashmina sella rice', 'premium rice', 'quality rice', 'organic rice', 'basmati rice', 'rice products', 'agriculture', 'quality grains', 'healthy food', 'sustainable farming', 'indian rice', 'authentic basmati'],
  openGraph: {
    title: 'Padmaaja Rasooi - Premium Rice Products & Quality Grains',
    description: 'Experience the finest quality rice with Padmaaja Rasooi. Premium rice varieties sourced from the best farms for exceptional taste and nutrition.',
    type: 'website',
    images: ['/hero-bg.jpg'],
  },
  twitter: {
    card: 'summary_large_image',
    title: 'Padmaaja Rasooi - Premium Rice Products & Quality Grains',
    description: 'Experience the finest quality rice with Padmaaja Rasooi. Premium rice varieties sourced from the best farms.',
    images: ['/hero-bg.jpg'],
  },
  alternates: {
    canonical: '/',
  },
}

async function getProducts() {
  try {
    const products = await prisma.product.findMany({
      where: {
        isActive: true,
        stock: {
          gt: 0
        }
      },
      include: {
        category: true
      },
      orderBy: {
        createdAt: 'desc'
      },
      take: 50 // Increased from 8 to show more products
    })
    return products
  } catch (error) {
    console.error('Failed to fetch products:', error)
    return []
  }
}

async function getCategories() {
  try {
    const categories = await prisma.category.findMany({
      where: {
        isActive: true,
        products: {
          some: {
            isActive: true,
            stock: {
              gt: 0
            }
          }
        }
      },
      orderBy: {
        name: 'asc'
      }
    })
    console.log('Fetched categories:', categories)
    return categories
  } catch (error) {
    console.error('Failed to fetch categories:', error)
    return []
  }
}

export default async function Home() {
  const products = await getProducts()
  const categories = await getCategories()
  
  const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || 'https://padmaajarasooi.com'
  
  // Generate JSON-LD structured data
  const organizationJsonLd = generateOrganizationJsonLd(baseUrl)
  
  const websiteJsonLd = {
    '@context': 'https://schema.org',
    '@type': 'WebSite',
    'name': 'Padmaaja Rasooi',
    'description': 'Premium Kashmina Rice and Quality Basmati Products',
    'url': baseUrl,
    'potentialAction': {
      '@type': 'SearchAction',
      'target': {
        '@type': 'EntryPoint',
        'urlTemplate': `${baseUrl}/products?search={search_term_string}`
      },
      'query-input': 'required name=search_term_string'
    }
  }
  
  // Highlight Kashmina Rice products for SEO
  const kashminaProducts = products.filter(p => 
    p.name.toLowerCase().includes('kashmina') || 
    p.brand?.toLowerCase().includes('kashmina')
  ).slice(0, 10)
  
  const productListJsonLd = kashminaProducts.length > 0 
    ? generateProductListJsonLd(kashminaProducts, baseUrl)
    : null

  return (
    <ClientPageWrapper>
      {/* SEO: Organization & Website Schema */}
      <MultipleStructuredData 
        dataArray={[
          organizationJsonLd,
          websiteJsonLd,
          ...(productListJsonLd ? [productListJsonLd] : [])
        ]}
        idPrefix="homepage"
      />
      
      <main className="min-h-screen bg-white">
        {/* Hero Section */}
        <header>
          <MobileOptimizedLazyHeroSection />
        </header>

        {/* Our Products Section */}
        <ProductsSection products={products} categories={categories} />


        {/* About Section */}
        <MobileOptimizedLazyAboutSection />

        {/* Kashmina Brand Section */}
        <MobileOptimizedLazyKashminaSection />

        {/* Manufacturing Excellence Section */}
        <MobileOptimizedLazyManufacturingSection />

        {/* Statistics & Achievements Section */}
        {/* <MobileOptimizedLazyStatsSection /> */}

        {/* Certifications Section */}
        <MobileOptimizedLazyCertificationsSection />

        {/* News & Updates Section */}
        <MobileOptimizedLazyNewsSection />

        {/* Our Values Section */}
        <MobileOptimizedLazyOurValues />
      </main>
    </ClientPageWrapper>
  )
}
