import Link from 'next/link'
import { DEFAULT_COMPANY_SLUG, siteFetch } from '@/lib/api'
import {
  formatCurrency,
  resolvePublicHomepageLayout,
  type PublicHomepageLayout,
  type PublicHomepageSectionType,
} from '@rentaldrivego/types'
import { getPublicSiteLanguage } from '@/lib/i18n.server'
import { getPublicSiteDictionary } from '@/lib/i18n'
import type { PublicSitePageSections } from '@rentaldrivego/types'
import { resolvePageSectionsConfig } from '@/lib/pageSections'

interface BrandResponse {
  company: { slug: string; name: string }
  brand: {
    displayName: string
    tagline: string | null
    heroImageUrl: string | null
    publicPhone: string | null
    homePageConfig?: {
      heroTitle?: string | null
      heroDescription?: string | null
      viewOffersLabel?: string | null
      viewPricingLabel?: string | null
      contactCompanyLabel?: string | null
      activeOffersTitle?: string | null
      seeAllOffersLabel?: string | null
      noActiveOffersLabel?: string | null
      publishedVehiclesTitle?: string | null
      viewVehicleLabel?: string | null
      pricingEyebrow?: string | null
      pricingTitle?: string | null
      pricingDescription?: string | null
      showOffers?: boolean | null
      showVehicles?: boolean | null
      showPricing?: boolean | null
      layout?: PublicHomepageLayout | null
    } | null
    menuConfig?: {
      pageSections?: Partial<PublicSitePageSections> | null
    } | null
  } | null
}

interface Vehicle {
  id: string
  make: string
  model: string
  dailyRate: number
  photos: string[]
  category: string
}

interface Offer {
  id: string
  title: string
  discountValue: number
}

type BrandHomePageConfig = NonNullable<BrandResponse['brand']>['homePageConfig']

const pricingPlans = [
  {
    name: 'Starter',
    price: 'MAD 499',
    cadence: '/month',
  },
  {
    name: 'Growth',
    price: 'MAD 999',
    cadence: '/month',
    highlighted: true,
  },
  {
    name: 'Pro',
    price: 'Custom',
    cadence: '',
  },
]

function resolveText(value: string | null | undefined, fallback: string) {
  return value && value.trim() ? value : fallback
}

function resolveVisible(value: boolean | null | undefined) {
  return value ?? true
}

function resolveHomepageSectionVisibility(
  type: PublicHomepageSectionType,
  pageSections: PublicSitePageSections,
  homeConfig: BrandHomePageConfig | null | undefined,
) {
  if (!pageSections.home[type]) return false
  if (type === 'hero') return true
  if (type === 'offers') return resolveVisible(homeConfig?.showOffers)
  if (type === 'vehicles') return resolveVisible(homeConfig?.showVehicles)
  return resolveVisible(homeConfig?.showPricing)
}

export default async function PublicHomePage() {
  const slug = DEFAULT_COMPANY_SLUG
  const language = getPublicSiteLanguage()
  const dict = getPublicSiteDictionary(language)
  const localizedPlans = pricingPlans.map((plan) => ({
    ...plan,
    description:
      plan.name === 'Starter'
        ? dict.pricing.plans.starterDescription
        : plan.name === 'Growth'
        ? dict.pricing.plans.growthDescription
        : dict.pricing.plans.proDescription,
    features:
      plan.name === 'Starter'
        ? dict.pricing.plans.starterFeatures
        : plan.name === 'Growth'
        ? dict.pricing.plans.growthFeatures
        : dict.pricing.plans.proFeatures,
  }))
  const [brand, vehicles, offers] = await Promise.all([
    siteFetch<BrandResponse>(`/site/${slug}/brand`).catch(() => null),
    siteFetch<Vehicle[]>(`/site/${slug}/vehicles`).catch(() => []),
    siteFetch<Offer[]>(`/site/${slug}/offers`).catch(() => []),
  ])
  const homeConfig = brand?.brand?.homePageConfig ?? null
  const pageSections = resolvePageSectionsConfig(brand?.brand?.menuConfig)
  const heroTitle = resolveText(homeConfig?.heroTitle, brand?.brand?.tagline ?? dict.home.heroTitleFallback)
  const heroDescription = resolveText(homeConfig?.heroDescription, dict.home.heroDescription)
  const viewOffersLabel = resolveText(homeConfig?.viewOffersLabel, dict.home.viewOffers)
  const viewPricingLabel = resolveText(homeConfig?.viewPricingLabel, dict.home.viewPricing)
  const contactCompanyLabel = resolveText(homeConfig?.contactCompanyLabel, dict.home.contactCompany)
  const activeOffersTitle = resolveText(homeConfig?.activeOffersTitle, dict.home.activeOffers)
  const seeAllOffersLabel = resolveText(homeConfig?.seeAllOffersLabel, dict.home.seeAllOffers)
  const noActiveOffersLabel = resolveText(homeConfig?.noActiveOffersLabel, dict.home.noActiveOffers)
  const publishedVehiclesTitle = resolveText(homeConfig?.publishedVehiclesTitle, dict.home.publishedVehicles)
  const viewVehicleLabel = resolveText(homeConfig?.viewVehicleLabel, dict.home.viewVehicle)
  const pricingEyebrow = resolveText(homeConfig?.pricingEyebrow, dict.pricing.eyebrow)
  const pricingTitle = resolveText(homeConfig?.pricingTitle, dict.pricing.title)
  const pricingDescription = resolveText(homeConfig?.pricingDescription, dict.pricing.description)
  const visibleHomepageTypes = (['hero', 'offers', 'vehicles', 'pricing'] as PublicHomepageSectionType[]).filter((type) =>
    resolveHomepageSectionVisibility(type, pageSections, homeConfig),
  )
  const homepageLayout = resolvePublicHomepageLayout(homeConfig?.layout, visibleHomepageTypes)

  function renderHomepageSection(type: PublicHomepageSectionType) {
    if (type === 'hero') {
      return (
        <section className="grid h-full gap-8 lg:grid-cols-[1.1fr_0.9fr] lg:items-center">
          <div>
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-sky-700">{brand?.brand?.displayName ?? brand?.company.name ?? dict.siteNameFallback}</p>
            <h1 className="mt-5 text-5xl font-black tracking-tight text-slate-900">{heroTitle}</h1>
            <p className="mt-6 text-lg leading-8 text-slate-600">{heroDescription}</p>
            <div className="mt-10 flex flex-wrap gap-4">
              <Link href="/offers" className="rounded-full bg-slate-900 px-6 py-3 text-sm font-semibold text-white">{viewOffersLabel}</Link>
              <Link href="/pricing" className="rounded-full border border-sky-200 bg-sky-50 px-6 py-3 text-sm font-semibold text-sky-800">{viewPricingLabel}</Link>
              <Link href="/contact" className="rounded-full border border-slate-300 px-6 py-3 text-sm font-semibold text-slate-700">{contactCompanyLabel}</Link>
            </div>
          </div>
          <div className="card overflow-hidden bg-slate-100 min-h-80">
            {brand?.brand?.heroImageUrl ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={brand.brand.heroImageUrl} alt={brand.brand.displayName} className="h-full w-full object-cover" />
            ) : (
              <div className="flex h-full items-center justify-center p-8 text-center text-slate-500">{dict.home.heroImageMissing}</div>
            )}
          </div>
        </section>
      )
    }

    if (type === 'offers') {
      return (
        <section className="h-full">
          <div className="flex items-center justify-between">
            <h2 className="text-2xl font-bold text-slate-900">{activeOffersTitle}</h2>
            <Link href="/offers" className="text-sm font-semibold text-sky-700">{seeAllOffersLabel}</Link>
          </div>
          <div className="mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
            {offers.map((offer) => (
              <div key={offer.id} className="card p-5">
                <h3 className="text-lg font-semibold text-slate-900">{offer.title}</h3>
                <p className="mt-3 text-3xl font-black text-sky-700">{offer.discountValue}%</p>
              </div>
            ))}
            {offers.length === 0 && <div className="card p-6 text-sm text-slate-500">{noActiveOffersLabel}</div>}
          </div>
        </section>
      )
    }

    if (type === 'vehicles') {
      return (
        <section className="h-full">
          <div className="flex items-center justify-between">
            <h2 className="text-2xl font-bold text-slate-900">{publishedVehiclesTitle}</h2>
            <p className="text-sm text-slate-500">{dict.home.available(vehicles.length)}</p>
          </div>
          <div className="mt-4 grid gap-5 md:grid-cols-2 xl:grid-cols-3">
            {vehicles.map((vehicle) => (
              <article key={vehicle.id} className="card overflow-hidden">
                <div className="aspect-[16/10] bg-slate-100">
                  {vehicle.photos[0] ? (
                    // eslint-disable-next-line @next/next/no-img-element
                    <img src={vehicle.photos[0]} alt={`${vehicle.make} ${vehicle.model}`} className="h-full w-full object-cover" />
                  ) : null}
                </div>
                <div className="p-5">
                  <h3 className="text-xl font-bold text-slate-900">{vehicle.make} {vehicle.model}</h3>
                  <p className="mt-1 text-sm text-slate-500">{vehicle.category}</p>
                  <div className="mt-4 flex items-end justify-between">
                    <p className="text-xl font-black text-slate-900">{formatCurrency(vehicle.dailyRate, 'MAD')}</p>
                    <Link href={`/vehicles/${vehicle.id}`} className="rounded-full bg-slate-900 px-5 py-2.5 text-sm font-semibold text-white">{viewVehicleLabel}</Link>
                  </div>
                </div>
              </article>
            ))}
          </div>
        </section>
      )
    }

    return (
      <section className="h-full space-y-6">
        <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
          <div>
            <p className="text-sm font-semibold uppercase tracking-[0.18em] text-sky-700">{pricingEyebrow}</p>
            <h2 className="mt-2 text-3xl font-black tracking-tight text-slate-900">{pricingTitle}</h2>
            <p className="mt-3 max-w-3xl text-sm leading-7 text-slate-600">{pricingDescription}</p>
          </div>
          <Link href="/pricing" className="rounded-full border border-slate-300 px-5 py-2.5 text-sm font-semibold text-slate-700">
            {viewPricingLabel}
          </Link>
        </div>

        <div className="grid gap-6 lg:grid-cols-3">
          {localizedPlans.map((plan) => (
            <article
              key={plan.name}
              className={`card p-8 ${plan.highlighted ? 'border-sky-300 shadow-lg shadow-sky-100' : ''}`}
            >
              <div className="flex items-start justify-between gap-4">
                <div>
                  <h3 className="text-2xl font-black text-slate-900">{plan.name}</h3>
                  <p className="mt-3 text-sm leading-6 text-slate-600">{plan.description}</p>
                </div>
                {plan.highlighted ? (
                  <span className="rounded-full bg-sky-100 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-sky-800">
                    {dict.pricing.popular}
                  </span>
                ) : null}
              </div>

              <div className="mt-8 flex items-end gap-2">
                <span className="text-4xl font-black tracking-tight text-slate-900">{plan.price}</span>
                {plan.cadence ? <span className="pb-1 text-sm text-slate-500">{plan.cadence}</span> : null}
              </div>

              <ul className="mt-8 space-y-3">
                {plan.features.map((feature) => (
                  <li key={feature} className="flex gap-3 text-sm text-slate-700">
                    <span className="mt-0.5 inline-flex h-5 w-5 items-center justify-center rounded-full bg-sky-100 text-xs font-bold text-sky-700">+</span>
                    <span>{feature}</span>
                  </li>
                ))}
              </ul>
            </article>
          ))}
        </div>
      </section>
    )
  }

  return (
    <main className="min-h-screen bg-[linear-gradient(180deg,#eff6ff,white_30%)]">
      <div className="shell py-16">
        <div className="grid gap-6 lg:hidden">
          {homepageLayout.items.map((item) => (
            <div key={`mobile-${item.id}`} className="rounded-[1.75rem] border border-slate-200/80 bg-white/92 p-5 shadow-lg shadow-slate-200/60">
              {renderHomepageSection(item.type)}
            </div>
          ))}
        </div>

        <div
          className="relative hidden lg:block"
          style={{ height: `${homepageLayout.items.reduce((max, item) => Math.max(max, item.y + item.h - 1), 1) * 80}px` }}
        >
          {homepageLayout.items.map((item) => (
            <div
              key={item.id}
              className="absolute rounded-[1.75rem] border border-slate-200/80 bg-white/92 p-6 shadow-lg shadow-slate-200/60"
              style={{
                left: `${((item.x - 1) / 12) * 100}%`,
                top: `${(item.y - 1) * 80}px`,
                width: `${(item.w / 12) * 100}%`,
                height: `${item.h * 80}px`,
              }}
            >
              {renderHomepageSection(item.type)}
            </div>
          ))}
        </div>
      </div>
    </main>
  )
}
