"use client";

import { useEffect, useState } from "react";
import {
  Gift,
  HeartHandshake,
  ListChecks,
  ShieldCheck,
  Ship,
  Sparkles,
  ThumbsUp,
} from "lucide-react";
import { AiImage } from "@/components/AiImage";
import { CruiseCard } from "@/components/CruiseCard";
import { HappyMoments } from "@/components/HappyMoments";
import { ScrollReveal } from "@/components/ScrollReveal";
import { Specialists } from "@/components/Specialists";
import {
  aboutImageUrl,
  defaultAboutSettings,
  fetchPublicAbout,
  type AboutSettings,
} from "@/lib/about-api";
import {
  fetchPublicTours,
  mapPublicTourToCatalog,
  type CatalogTour,
} from "@/lib/tours-api";

const whyIcons = [ThumbsUp, ListChecks, Gift, ShieldCheck, Ship, HeartHandshake];

export function AboutUsView() {
  const [about, setAbout] = useState<AboutSettings>(defaultAboutSettings);
  const [cruises, setCruises] = useState<CatalogTour[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const [aboutRes, toursRes] = await Promise.all([
          fetchPublicAbout(),
          fetchPublicTours({ category: "best-seller", per_page: 4 }),
        ]);
        if (!active) return;
        setAbout({
          ...defaultAboutSettings,
          ...aboutRes.about,
          about_block: {
            ...defaultAboutSettings.about_block,
            ...(aboutRes.about.about_block || {}),
          },
          love_block: {
            ...defaultAboutSettings.love_block,
            ...(aboutRes.about.love_block || {}),
          },
          mission: {
            ...defaultAboutSettings.mission,
            ...(aboutRes.about.mission || {}),
          },
          why: {
            ...defaultAboutSettings.why,
            ...(aboutRes.about.why || {}),
            items: aboutRes.about.why?.items?.length
              ? aboutRes.about.why.items
              : defaultAboutSettings.why.items,
          },
          steps: {
            ...defaultAboutSettings.steps,
            ...(aboutRes.about.steps || {}),
            items: aboutRes.about.steps?.items?.length
              ? aboutRes.about.steps.items
              : defaultAboutSettings.steps.items,
          },
          memory: {
            ...defaultAboutSettings.memory,
            ...(aboutRes.about.memory || {}),
          },
          reviews: {
            ...defaultAboutSettings.reviews,
            ...(aboutRes.about.reviews || {}),
            items: aboutRes.about.reviews?.items?.length
              ? aboutRes.about.reviews.items
              : defaultAboutSettings.reviews.items,
          },
          gallery: {
            ...defaultAboutSettings.gallery,
            ...(aboutRes.about.gallery || {}),
            images: aboutRes.about.gallery?.images?.length
              ? aboutRes.about.gallery.images
              : defaultAboutSettings.gallery.images,
          },
        });
        setCruises((toursRes.data || []).map(mapPublicTourToCatalog));
      } catch {
        if (!active) return;
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  const whyItems = about.why?.items || [];
  const stepItems = about.steps?.items || [];
  const reviewItems = about.reviews?.items || [];
  const galleryImages = about.gallery?.images?.filter(Boolean) || [];

  if (loading) {
    return (
      <div className="grid min-h-[40vh] place-items-center text-sm text-muted">
        Loading about page…
      </div>
    );
  }

  return (
    <>
      <section className="relative overflow-hidden bg-white text-center">
        <div className="mx-auto w-[min(1100px,calc(100%-2rem))] py-12 sm:py-16">
          <ScrollReveal>
            <h1 className="font-[family-name:var(--font-display)] text-[clamp(1.75rem,5vw,3.25rem)] font-bold tracking-[0.04em] text-accent uppercase">
              {about.hero_title}
            </h1>
          </ScrollReveal>
          <ScrollReveal delay={120}>
            <p className="mx-auto mt-4 max-w-xl font-[family-name:var(--font-script)] text-2xl text-brand-deep/70 sm:text-3xl">
              {about.hero_subtitle}
            </p>
          </ScrollReveal>
          <ScrollReveal delay={220} variant="scale" className="mt-10">
            <div className="relative mx-auto overflow-hidden rounded-2xl">
              <AiImage
                src={aboutImageUrl(about.hero_image, "/img/destinationBg32.webp")}
                alt="Ha Long Bay limestone islands"
                className="aspect-[16/9] w-full"
              />
            </div>
          </ScrollReveal>
        </div>
      </section>

      <section className="relative overflow-hidden bg-white pb-6">
        <div className="mx-auto w-[min(1100px,calc(100%-2rem))] space-y-16 py-10 sm:py-14">
          <div className="grid items-center gap-8 lg:grid-cols-[0.95fr_1.05fr] lg:gap-12">
            <ScrollReveal variant="left">
              <div className="relative">
                <div className="overflow-hidden rounded-[1.5rem]">
                  <AiImage
                    src={aboutImageUrl(
                      about.about_block?.image,
                      "/img/image_1863.webp",
                    )}
                    alt="Luxury cruise in Ha Long Bay"
                    className="aspect-[4/5] w-full sm:aspect-[5/6]"
                  />
                </div>
                {about.about_block?.badge ? (
                  <div className="absolute -top-4 -right-2 grid h-28 w-28 place-items-center rounded-full bg-[#e8845a] p-3 text-center shadow-lg sm:-right-6 sm:h-32 sm:w-32">
                    <p className="text-[10px] leading-tight font-bold tracking-wide text-white uppercase sm:text-[11px]">
                      {about.about_block.badge}
                    </p>
                  </div>
                ) : null}
              </div>
            </ScrollReveal>
            <ScrollReveal variant="right" delay={120}>
              <div className="lg:pl-4">
                <h2 className="font-[family-name:var(--font-script)] text-5xl text-[#e8845a] sm:text-6xl">
                  {about.about_block?.title || "About us"}
                </h2>
                {(about.about_block?.paragraphs || []).map((p) => (
                  <p
                    key={p}
                    className="mt-4 text-sm leading-relaxed text-muted first:mt-5 sm:text-[15px]"
                  >
                    {p}
                  </p>
                ))}
              </div>
            </ScrollReveal>
          </div>

          <div className="grid items-center gap-8 lg:grid-cols-[1.05fr_0.95fr] lg:gap-12">
            <ScrollReveal variant="left" className="order-2 lg:order-1">
              <div className="lg:pr-4">
                <h2 className="font-[family-name:var(--font-script)] text-5xl text-[#e8845a] sm:text-6xl">
                  {about.love_block?.title || "We love what we do!"}
                </h2>
                {(about.love_block?.paragraphs || []).map((p) => (
                  <p
                    key={p}
                    className="mt-4 text-sm leading-relaxed text-muted first:mt-5 sm:text-[15px]"
                  >
                    {p}
                  </p>
                ))}
              </div>
            </ScrollReveal>
            <ScrollReveal variant="right" delay={120} className="order-1 lg:order-2">
              <div className="overflow-hidden rounded-[1.5rem]">
                <AiImage
                  src={aboutImageUrl(about.love_block?.image, "/img/image_1864.webp")}
                  alt="Cruise experience Ha Long Bay"
                  className="aspect-[4/5] w-full sm:aspect-[5/6]"
                />
              </div>
            </ScrollReveal>
          </div>
        </div>
      </section>

      <section className="bg-[#f5f8fa] py-14 sm:py-16">
        <div className="mx-auto w-[min(900px,calc(100%-2rem))] text-center">
          <ScrollReveal variant="scale">
            <div className="mx-auto overflow-hidden rounded-2xl shadow-[0_12px_36px_rgba(13,58,77,0.1)]">
              <AiImage
                src={aboutImageUrl(about.mission?.image, "/img/destinationBg32.webp")}
                alt="Ha Long Bay cruise fleet"
                className="aspect-[16/9] w-full"
              />
            </div>
          </ScrollReveal>
          <ScrollReveal delay={120}>
            <h2 className="mt-10 font-[family-name:var(--font-display)] text-3xl font-semibold text-brand-deep">
              {about.mission?.title || "Our mission"}
            </h2>
            <p className="mx-auto mt-4 max-w-2xl text-base leading-relaxed text-muted sm:text-lg">
              {about.mission?.text}
            </p>
          </ScrollReveal>
        </div>
      </section>

      <section className="bg-white py-14 sm:py-16">
        <div className="mx-auto w-[min(1100px,calc(100%-2rem))]">
          <ScrollReveal>
            <h2 className="mb-10 text-center font-[family-name:var(--font-display)] text-3xl font-semibold text-brand-deep sm:text-4xl">
              {about.why?.title || "Why choose us?"}
            </h2>
          </ScrollReveal>

          <div className="grid gap-4 md:grid-cols-3">
            {whyItems.slice(0, 3).map((item, i) => {
              const Icon = whyIcons[i]!;
              return (
                <ScrollReveal key={item.title} delay={i * 100}>
                  <article className="h-full rounded-2xl border border-[var(--line)] bg-white p-6 shadow-[0_8px_24px_rgba(13,58,77,0.05)]">
                    <span className="grid h-10 w-10 place-items-center rounded-full bg-[#e8845a]/12 text-[#e8845a]">
                      <Icon className="h-5 w-5" strokeWidth={2} />
                    </span>
                    <h3 className="mt-4 text-lg font-bold text-brand-deep">{item.title}</h3>
                    <p className="mt-2 text-sm leading-relaxed text-muted">{item.text}</p>
                  </article>
                </ScrollReveal>
              );
            })}
          </div>

          <div className="mt-4 grid gap-4 md:grid-cols-[1fr_1.2fr_1fr]">
            <ScrollReveal variant="left" delay={40}>
              <div className="overflow-hidden rounded-2xl">
                <AiImage
                  src={aboutImageUrl(about.why?.left_image, "/img/image_1863.webp")}
                  alt="Ha Long Bay scenery"
                  className="aspect-[4/5] h-full w-full min-h-[220px]"
                />
              </div>
            </ScrollReveal>
            <ScrollReveal variant="scale" delay={120}>
              <div className="grid place-items-center rounded-2xl border border-[var(--line)] bg-[#f5f8fa] px-6 py-10 text-center">
                <img
                  src="/img/logo.png"
                  alt="VNSAILS"
                  className="mx-auto h-16 w-auto object-contain"
                />
                <p className="mt-4 text-sm text-muted">
                  {about.why?.center_text || "Trusted local experts for Ha Long Bay cruises"}
                </p>
              </div>
            </ScrollReveal>
            <ScrollReveal variant="right" delay={200}>
              <div className="overflow-hidden rounded-2xl">
                <AiImage
                  src={aboutImageUrl(about.why?.right_image, "/img/image_1864.webp")}
                  alt="Cruise deck view"
                  className="aspect-[4/5] h-full w-full min-h-[220px]"
                />
              </div>
            </ScrollReveal>
          </div>

          <div className="mt-4 grid gap-4 md:grid-cols-3">
            {whyItems.slice(3).map((item, i) => {
              const Icon = whyIcons[i + 3] || Sparkles;
              return (
                <ScrollReveal key={item.title} delay={i * 100}>
                  <article className="h-full rounded-2xl border border-[var(--line)] bg-white p-6 shadow-[0_8px_24px_rgba(13,58,77,0.05)]">
                    <span className="grid h-10 w-10 place-items-center rounded-full bg-accent/10 text-accent">
                      <Icon className="h-5 w-5" strokeWidth={2} />
                    </span>
                    <h3 className="mt-4 text-lg font-bold text-brand-deep">{item.title}</h3>
                    <p className="mt-2 text-sm leading-relaxed text-muted">{item.text}</p>
                  </article>
                </ScrollReveal>
              );
            })}
          </div>
        </div>
      </section>

      <section className="bg-[#f5f8fa] py-14 sm:py-16">
        <div className="mx-auto w-[min(1100px,calc(100%-2rem))]">
          <ScrollReveal>
            <h2 className="max-w-2xl font-[family-name:var(--font-display)] text-3xl font-semibold text-brand-deep sm:text-4xl">
              {about.steps?.title}
            </h2>
          </ScrollReveal>
          <div className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {stepItems.map((item, i) => (
              <ScrollReveal key={`${item.step}-${item.title}`} delay={i * 90}>
                <article className="h-full rounded-2xl border border-[var(--line)] bg-white p-5 shadow-[0_8px_24px_rgba(13,58,77,0.05)]">
                  <p className="text-xs font-bold tracking-widest text-[#e8845a] uppercase">
                    Step {String(item.step).replace(/^0/, "")}
                  </p>
                  <h3 className="mt-2 text-lg font-bold text-brand-deep">{item.title}</h3>
                  <p className="mt-2 text-sm leading-relaxed text-muted">{item.text}</p>
                </article>
              </ScrollReveal>
            ))}
          </div>
          <ScrollReveal delay={120}>
            {about.steps?.footer ? (
              <p className="mt-8 max-w-3xl text-sm text-muted sm:text-base">
                {about.steps.footer}
              </p>
            ) : null}
            <a href="/#contact" className="btn-accent mt-6 inline-flex px-6 py-3 text-sm">
              {about.steps?.cta || "Contact Now"}
            </a>
          </ScrollReveal>
        </div>
      </section>

      <ScrollReveal variant="fade">
        <div className="bg-white pt-14">
          <Specialists />
        </div>
      </ScrollReveal>

      <section className="relative overflow-hidden bg-white py-14 sm:py-16">
        <div className="relative mx-auto grid w-[min(1100px,calc(100%-2rem))] items-center gap-10 lg:grid-cols-2">
          <ScrollReveal variant="left">
            <div>
              <h2 className="font-[family-name:var(--font-script)] text-[clamp(2.4rem,5vw,3.6rem)] leading-tight text-[#e8845a]">
                {about.memory?.title}
              </h2>
              {(about.memory?.paragraphs || []).map((p) => (
                <p
                  key={p}
                  className="mt-4 text-sm leading-relaxed text-muted first:mt-6 sm:text-[15px]"
                >
                  {p}
                </p>
              ))}
              <a href="/#contact" className="btn-accent mt-7 inline-flex px-6 py-3 text-sm">
                {about.memory?.cta || "Chat with us"}
              </a>
            </div>
          </ScrollReveal>
          <ScrollReveal variant="right" delay={140}>
            <div className="overflow-hidden rounded-[1.5rem]">
              <AiImage
                src={aboutImageUrl(about.memory?.image, "/img/image_1863.webp")}
                alt="VNSAILS travel team"
                className="aspect-[5/4] w-full"
              />
            </div>
          </ScrollReveal>
        </div>
      </section>

      <section className="bg-[#f5f8fa] py-14 sm:py-16">
        <div className="mx-auto w-[min(1100px,calc(100%-2rem))]">
          <ScrollReveal>
            <h2 className="text-center font-[family-name:var(--font-display)] text-3xl font-semibold text-brand-deep">
              {about.reviews?.title || "Customer reviews"}
            </h2>
          </ScrollReveal>
          <div className="mt-10 flex gap-4 overflow-x-auto pb-2 snap-x snap-mandatory">
            {reviewItems.map((review, i) => (
              <ScrollReveal key={`${review.name}-${i}`} delay={i * 80} className="shrink-0">
                <article className="w-[min(320px,80vw)] snap-start rounded-2xl border border-[var(--line)] bg-white p-5 shadow-[0_8px_24px_rgba(13,58,77,0.05)]">
                  <div className="mb-3 flex gap-0.5 text-[#e8845a]">
                    {Array.from({ length: 5 }).map((_, j) => (
                      <Sparkles
                        key={j}
                        className="h-3.5 w-3.5"
                        fill="currentColor"
                        strokeWidth={0}
                      />
                    ))}
                  </div>
                  <p className="text-sm leading-relaxed text-muted">
                    &ldquo;{review.text}&rdquo;
                  </p>
                  <p className="mt-4 text-sm font-bold text-brand-deep">{review.name}</p>
                </article>
              </ScrollReveal>
            ))}
          </div>
        </div>
      </section>

      <section className="bg-white py-14 sm:py-16">
        <div className="mx-auto w-[min(1100px,calc(100%-2rem))]">
          <ScrollReveal>
            <div className="mb-8 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
              <h2 className="font-[family-name:var(--font-display)] text-3xl font-semibold text-brand-deep">
                {about.top_cruises_title || "Our Top 5 Cruises"}
              </h2>
              <a
                href="/cruise-tours?category=best-seller"
                className="inline-flex items-center gap-2 text-sm font-semibold text-accent hover:text-accent-hover"
              >
                See All
              </a>
            </div>
          </ScrollReveal>
          <div className="grid gap-5 sm:grid-cols-2 xl:grid-cols-4">
            {cruises.map((cruise, i) => (
              <ScrollReveal key={cruise.id} delay={i * 90}>
                <CruiseCard cruise={cruise} />
              </ScrollReveal>
            ))}
          </div>
        </div>
      </section>

      {galleryImages.length > 0 ? (
        <ScrollReveal variant="fade">
          <HappyMoments
            images={galleryImages.map((src) => aboutImageUrl(src, src))}
            title={about.gallery?.title || "Happy moments"}
          />
        </ScrollReveal>
      ) : null}
    </>
  );
}
