import { getDictionary, Locale } from "./dictionaries";
import prisma from "@/lib/prisma";
import { buildMeta } from "@/lib/metadata";
import type { Metadata } from "next";

import HeroSection from "@/components/home/HeroSection";
import FeaturesStrip from "@/components/home/FeaturesStrip";
import AboutSection from "@/components/home/AboutSection";
import ActivitiesGrid from "@/components/home/ActivitiesGrid";
import EventsPreview from "@/components/home/EventsPreview";
import InstagramFeed from "@/components/home/InstagramFeed";
import TestimonialsSection from "@/components/home/TestimonialsSection";
import CtaBand from "@/components/home/CtaBand";
import RoomsSection from "@/components/home/RoomsSection";

export const revalidate = 3600;

const defaultFeatures = [
  { icon: "Wind", label: "Kitesurf", sub: "Eğitimleri" },
  { icon: "Anchor", label: "Yoga Wellness", sub: "Platform" },
  { icon: "Utensils", label: "Restoran & Bar", sub: "Ege Mutfağı" },
  { icon: "BedDouble", label: "Butik Odalar", sub: "3 Tip Konaklama" },
  { icon: "Sun", label: "Sunset DJ Party", sub: "Etkinlikler" },
];

const testimonials = [
  {
    text: "Çok atmosferik bir yer. Harika ortam, uçurtma ve rüzgar. Kahve fena değil ama biraz pahalı.",
    name: "Elena Gerasimova",
    from: "Google Yorumları",
  },
  {
    text: "Ortama, plaja ve kitesurf yapanları izlemeye bayıldım. Takılacak bir sürü harika yer, iyi yemek ve iyi müzik var. Kitesurf'e uğramadan Akyaka'ya gelmiş sayılmazsınız.",
    name: "Dhyani Love",
    from: "Google Yorumları",
  },
  {
    text: "Harika bir kitesurf plajı. Öğleden sonraları istikrarlı termal rüzgarlar ve yumuşak kum. Çoğu sörfçü (Eylül-Ekim) dalış kıyafeti giyiyor ama ben şortla bile rahattım. Sadece plaja girmek için ödeme yapmanıza gerek yok, yalnızca sörf yapacaksanız ödüyorsunuz.",
    name: "Shebastian Reyes",
    from: "Google Yorumları",
  },
];

const testimonialsEn = [
  {
    text: "Very atmospheric place. Cool man, kite and wind. Coffee not bad, but expensive.",
    name: "Elena Gerasimova",
    from: "Google Reviews",
  },
  {
    text: "Loved the vibes love the beach and watching kite surfers. Lots of cool places to hang out, good food and good music. You cannot come to Akyaka without coming to kite surfing.",
    name: "Dhyani Love",
    from: "Google Reviews",
  },
  {
    text: "Great kite beach. Steady thermal afternoon winds and soft sand. Most kiters wear a wetsuit (Sep - Oct) but I was fine with just board shorts. You don't have to pay just to go to the beach, only if you plan to kite.",
    name: "Shebastian Reyes",
    from: "Google Reviews",
  },
];

export async function generateMetadata(
  { params }: { params: Promise<{ lang: string }> }
): Promise<Metadata> {
  const { lang } = await params;
  return buildMeta(lang, "", {
    title: "Kite Beach Akyaka | Kitesurf & Butik Otel",
    description: "Nehrin huzuru, denizin enerjisi — tek bir noktada. Akyaka'nın kalbinde kitesurf ve butik otel deneyimi.",
  }, {
    title: "Kite Beach Akyaka | Kitesurf & Boutique Hotel",
    description: "Tranquility of the river, energy of the sea — in one spot. Kitesurf and boutique hotel experience in the heart of Akyaka.",
  });
}

async function getInstagramData() {
  if (!process.env.RAPIDAPI_KEY) {
    return [];
  }

  const url = 'https://instagram120.p.rapidapi.com/api/instagram/posts';
  const options = {
    method: 'POST',
    headers: {
      'x-rapidapi-key': process.env.RAPIDAPI_KEY,
      'x-rapidapi-host': 'instagram120.p.rapidapi.com',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: 'kitebeachakyaka',
      maxId: ''
    }),
    next: { revalidate: 86400 }
  };

  try {
    const res = await fetch(url, options);
    if (!res.ok) {
      console.warn('Instagram API error or missing limits. Status:', res.status);
      return [];
    }
    const data = await res.json();
    return data.result?.edges?.slice(0, 4).map((edge: any) => edge.node) || [];
  } catch (err) {
    console.warn("Instagram fetch error:", err);
    return [];
  }
}

export default async function Home({ params }: { params: Promise<{ lang: string }> }) {
  const { lang } = await params;
  const dict = await getDictionary(lang as Locale);

  const [heroDb, activities, events, dbFeatures, aboutDb, instagramPosts] = await Promise.all([
    prisma.heroSection.findUnique({ where: { lang } }),
    prisma.activity.findMany({ where: { lang }, orderBy: { order: "asc" } }),
    prisma.event.findMany({ where: { lang }, orderBy: { date: "asc" } }),
    prisma.feature.findMany({ where: { lang }, orderBy: { order: "asc" } }),
    prisma.aboutSection.findUnique({ where: { lang } }),
    getInstagramData(),
  ]);

  const displayTestimonials = lang === "en" ? testimonialsEn : testimonials;

  const heroData = heroDb || {
    location: dict.home.location,
    welcome: dict.home.welcome,
    title: dict.home.title,
    subtitle: dict.home.subtitle,
    bookNow: dict.home.bookNow,
    exploreActivities: dict.home.exploreActivities,
    scroll: dict.home.scroll,
  };

  const aboutData = aboutDb || {
    badge: lang === "en" ? "Our Story" : "Hikayemiz",
    titleLine1: lang === "en" ? "In the" : "Doğanın",
    titleLine2: lang === "en" ? "Heart of Nature" : "Kalbinde",
    titleHighlight: lang === "en" ? "A Special Escape" : "Özel Bir Kaçış",
    description1: lang === "en"
      ? "Located right on the banks of the Azmak River flowing into the crystal waters of the Gulf of Gokova, we are in a unique location where the wind never ceases."
      : "Gökova Körfezi'nin kristal sularına dökülen Azmak Nehri'nin hemen kıyısında, rüzgarın hiç eksik olmadığı eşsiz bir konumda yer alıyoruz.",
    description2: lang === "en"
      ? "Kite Beach Akyaka offers a unique living space that integrates the passion for kitesurfing with nature, comfort, and local flavors."
      : "Kite Beach Akyaka; kitesurf tutkusunu doğayla, konforla ve yerel lezzetlerle bütünleştiren benzersiz bir yaşam alanı sunar.",
    image: "https://images.unsplash.com/photo-1544551763-46a013bb70d5?q=80&w=2940&auto=format&fit=crop",
    statsGuestCount: "500+",
    statsGuestLabel: lang === "en" ? "Happy Guests" : "Mutlu Misafir",
    statsYearCount: "10+",
    statsYearLabel: lang === "en" ? "Years Experience" : "Yıl Deneyim",
    badgeIkoTitle: "Kitesurf",
    badgeIkoLabel: lang === "en" ? "School" : "Okulu"
  };

  const displayFeatures = dbFeatures.length > 0 ? dbFeatures : defaultFeatures;

  return (
    <div className="flex flex-col min-h-screen">
      <HeroSection heroData={heroData} lang={lang} />
      <FeaturesStrip features={displayFeatures} />
      <AboutSection aboutData={aboutData} lang={lang} />
      <RoomsSection lang={lang} />
      <ActivitiesGrid activities={activities} lang={lang} />
      <EventsPreview events={events} lang={lang} />
      <InstagramFeed instagramPosts={instagramPosts} lang={lang} />
      <TestimonialsSection testimonials={displayTestimonials} lang={lang} />
      <CtaBand lang={lang} />
    </div>
  );
}
