'use client';

import { useState, useEffect } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useSession } from 'next-auth/react';
import { CommonHeader } from '@/components/layout/CommonHeader';
import { Footer } from '@/components/layout/Footer';
import { cmsService, resolveImageUrl } from '@/services/cms.service';
import type {
  AboutHeroContent,
  AboutStatsContent,
  AboutFeaturesContent,
  AboutTeamContent,
  AboutCtaContent,
} from '@/types/cms';

// ---------------------------------------------------------------------------
// Page component
// ---------------------------------------------------------------------------

export default function AboutPage() {
  const { data: session } = useSession();
  const isAgent = (session?.user as any)?.role === 'AGENT';

  const [loading, setLoading] = useState(true);
  const [hero, setHero] = useState<AboutHeroContent | null>(null);
  const [stats, setStats] = useState<AboutStatsContent | null>(null);
  const [features, setFeatures] = useState<AboutFeaturesContent | null>(null);
  const [team, setTeam] = useState<AboutTeamContent | null>(null);
  const [cta, setCta] = useState<AboutCtaContent | null>(null);

  useEffect(() => {
    cmsService.getPageContent('about').then(async (sections) => {
      for (const s of sections) {
        const c = s.content as Record<string, unknown>;
        switch (s.sectionKey) {
          case 'hero':
            if (c.headline || c.description) {
              const heroData = c as unknown as AboutHeroContent;
              heroData.bannerImageUrl = await resolveImageUrl(heroData.bannerImageUrl);
              setHero(heroData);
            }
            break;
          case 'stats':
            if (Array.isArray(c.stats) && c.stats.length > 0) setStats(c as unknown as AboutStatsContent);
            break;
          case 'features':
            if (c.badge || (Array.isArray(c.features) && c.features.length > 0)) {
              const featData = c as unknown as AboutFeaturesContent;
              for (const feat of featData.features) {
                feat.iconPath = await resolveImageUrl(feat.iconPath);
              }
              setFeatures(featData);
            }
            break;
          case 'team':
            if (c.title || c.subtitle || c.intro || (Array.isArray(c.cards) && c.cards.length > 0)) {
              const teamData = c as unknown as AboutTeamContent;
              if (Array.isArray(teamData.cards)) {
                for (const card of teamData.cards) {
                  card.iconPath = await resolveImageUrl(card.iconPath);
                }
              } else {
                teamData.cards = [];
              }
              setTeam(teamData);
            }
            break;
          case 'cta':
            if (c.title || c.description) setCta(c as unknown as AboutCtaContent);
            break;
        }
      }
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  return (
    <div className="min-h-screen bg-white flex flex-col">
      {/* Header */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6 w-full">
        <CommonHeader />
      </div>

      {/* Main Content */}
      <main className="flex-1 w-full">
        {loading ? (
          <AboutSkeleton />
        ) : (
          <>
            {/* Hero Section */}
            {hero && (
              <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8">
                <div className="text-center">
                  {hero.badge && (
                    <div className="inline-flex items-center gap-2 px-4 py-2 border border-[#00293d]/20 rounded-full mb-6">
                      <Image
                        src="/assets/icons/verified-badge-orange.svg"
                        alt=""
                        width={19}
                        height={19}
                      />
                      <span className="font-fractul font-medium text-[14px] text-[#00293d]">
                        {hero.badge}
                      </span>
                    </div>
                  )}
                  <h1 className="font-fractul font-bold text-[30px] text-[#00293d] leading-tight mb-6">
                    {hero.headline}
                  </h1>
                  <p className="font-serif text-[14px] text-[#00293d] leading-relaxed mb-8 max-w-[600px] mx-auto">
                    {hero.description}
                  </p>
                  <Link
                    href={isAgent ? '/agent/dashboard' : '/user/profiles'}
                    className="inline-flex items-center justify-center px-6 h-[46px] border border-[#00293d] rounded-[15px] font-fractul font-bold text-[16px] text-[#00293d] hover:bg-gray-50 transition-colors"
                  >
                    {isAgent ? 'Go to Dashboard' : (hero.ctaButtonText || 'Find Your Agent')}
                  </Link>
                </div>
              </section>
            )}

            {/* Hero Image */}
            {hero?.bannerImageUrl && (
              <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8">
                <div className="relative rounded-[15px] overflow-hidden h-[411px]">
                  <SmartImage
                    src={hero.bannerImageUrl}
                    alt="City buildings"
                    className="w-full h-full object-cover"
                    shimmerClassName="rounded-[15px]"
                  />
                  {hero.bannerOverlayText && (
                    <div className="absolute bottom-6 left-6 lg:bottom-10 lg:left-10">
                      <h2 className="font-fractul font-medium text-[20px] text-[#00293d]">
                        {hero.bannerOverlayText}
                      </h2>
                    </div>
                  )}
                </div>
                {/* Founder Story */}
                <div className="max-w-3xl mx-auto space-y-6 mt-10">
                  <p className="font-serif text-[15px] text-[#00293d] leading-relaxed">
                    Before entering real estate, I spent a decade as a mental health counselor. When I became a Realtor, I was shocked and saddened by how much mistrust existed in the industry—consumers didn&apos;t feel protected and didn&apos;t even trust their own agent, and agents were encouraged to be high-pressure salespeople instead of professional service-providers. I felt so misaligned with the identity of being a real estate agent that I couldn&apos;t even maintain eye-contact when I introduced myself and told people what I did. My go-to line became, &ldquo;I am a counselor, and I do real estate&rdquo;.
                  </p>
                  <p className="font-serif text-[15px] text-[#00293d] leading-relaxed">
                    That all changed after meeting a young Air Force client named Joe, who taught me the meaning of partnership in real estate. Together, we built a relationship that spanned 12 deals, dozens of referrals, and multiple repeat clients. The honesty and trust built from that relationship became the beginning of what I now call the Tree of Joe. That initial partnership grew to over 100 closings in 10 years, all grown through integrity, trust, and relationships. That experience gave me a passion and purpose in real estate. I could once again proudly call myself a service-provider.
                  </p>
                  <p className="font-serif text-[15px] text-[#00293d] leading-relaxed font-semibold">
                    RE-Quest is built on that belief.
                  </p>
                </div>
              </section>
            )}

            {/* Stats Section */}
            {stats && stats.stats.length > 0 && (
              <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <div className="border-t border-b border-[#00293d]/10 py-6">
                  <div className="flex items-center justify-center gap-16 lg:gap-32">
                    {stats.stats.map((stat, index) => (
                      <div key={index} className="text-center">
                        <p className="font-fractul font-medium text-[14px] text-[#e58625]">
                          {stat.value}
                        </p>
                        <p className="font-serif text-[14px] text-[#00293d]">
                          {stat.label}
                        </p>
                      </div>
                    ))}
                  </div>
                </div>
              </section>
            )}

            {/* Why Choose Us Section */}
            {features && features.features.length > 0 && (
              <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 lg:py-20">
                <div className="text-center mb-12">
                  {features.badge && (
                    <h2 className="font-fractul font-bold text-[30px] text-[#00293d] mb-3">
                      {features.badge}
                    </h2>
                  )}
                  <p className="font-serif text-[14px] text-[#00293d] max-w-[518px] mx-auto">
                    Your quest for the perfect home depends on your team
                  </p>
                  <p className="font-serif text-[14px] text-[#00293d] max-w-[600px] mx-auto mt-4">
                    Buying or selling a home is a deeply personal and intense undertaking, both financially and emotionally. You deserve better than algorithms and ads. You deserve the option to assemble a professional team to serve you. RE-Quest provides:
                  </p>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                  {features.features.map((feature, index) => (
                    <FeatureCard key={index} feature={feature} />
                  ))}
                </div>
              </section>
            )}

            {/* Team Section */}
            {team && (team.title || team.subtitle || team.intro || team.cards.length > 0) && (
              <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 lg:pb-20">
                <div className="text-center mb-12">
                  {team.title && (
                    <h2 className="font-fractul font-bold text-[30px] text-[#00293d] mb-3">
                      {team.title}
                    </h2>
                  )}
                  {team.subtitle && (
                    <p className="font-serif text-[14px] text-[#00293d] max-w-[471px] mx-auto">
                      {team.subtitle}
                    </p>
                  )}
                  {team.intro && (
                    <p className="font-serif text-[14px] text-[#00293d] max-w-[600px] mx-auto mt-4 whitespace-pre-line">
                      {team.intro}
                    </p>
                  )}
                </div>
                {team.cards.length > 0 && (
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-5xl mx-auto items-stretch">
                    {team.cards.map((card, index) => (
                      <TeamCard key={index} card={card} />
                    ))}
                  </div>
                )}
              </section>
            )}

            {/* Divider */}
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
              <div className="border-t border-[#00293d]/10" />
            </div>

            {/* CTA Section */}
            <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
              <div className="flex flex-col lg:flex-row items-center justify-between gap-8">
                <div className="lg:max-w-[400px]">
                  <h2 className="font-fractul font-bold text-[30px] text-[#00293d] mb-3">
                    {isAgent ? 'Manage your profile' : (cta?.title || 'Ready to find a agent')}
                  </h2>
                  <p className="font-serif font-bold text-[14px] text-[#00293d] mb-6">
                    {isAgent
                      ? 'Keep your profile updated and connect with potential clients.'
                      : (cta?.description || 'Search and connect with verified real estate agents who match your needs, location, and goals.')}
                  </p>
                  <div className="flex items-center gap-4">
                    <Link
                      href={isAgent ? '/agent/dashboard' : '/user/profiles'}
                      className="inline-flex items-center justify-center px-6 h-[46px] bg-[#e58625] rounded-[15px] font-fractul font-bold text-[16px] text-[#00293d] hover:bg-[#d47720] transition-colors"
                    >
                      {isAgent ? 'Go to Dashboard' : (cta?.buttonText || 'Find Agents Now')}
                    </Link>
                    <Link
                      href="/contact"
                      className="inline-flex items-center justify-center px-6 h-[46px] border border-[#00293d] rounded-[15px] font-fractul font-bold text-[16px] text-[#00293d] hover:bg-gray-50 transition-colors"
                    >
                      Get Help
                    </Link>
                  </div>
                </div>
                <div className="w-[200px] lg:w-[280px]">
                  <Image
                    src="/assets/images/agent-illustration.png"
                    alt="Find an agent"
                    width={280}
                    height={241}
                    className="w-full h-auto"
                  />
                </div>
              </div>
            </section>
          </>
        )}
      </main>

      {/* Footer */}
      <Footer />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Full page skeleton while CMS loads
// ---------------------------------------------------------------------------

function AboutSkeleton() {
  return (
    <div className="animate-fade-in">
      {/* Hero skeleton */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8">
        <div className="flex flex-col items-center gap-4">
          <div className="shimmer-loading h-[36px] w-[160px] rounded-full" />
          <div className="shimmer-loading h-[36px] w-[350px] rounded-lg" />
          <div className="shimmer-loading h-[16px] w-[500px] max-w-full rounded-lg" />
          <div className="shimmer-loading h-[16px] w-[400px] max-w-full rounded-lg" />
          <div className="shimmer-loading h-[46px] w-[180px] rounded-[15px] mt-2" />
        </div>
      </section>

      {/* Banner skeleton */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-8">
        <div className="shimmer-loading h-[411px] w-full rounded-[15px]" />
      </section>

      {/* Stats skeleton */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="border-t border-b border-[#00293d]/10 py-6">
          <div className="flex items-center justify-center gap-16 lg:gap-32">
            <div className="flex flex-col items-center gap-2">
              <div className="shimmer-loading h-[16px] w-[60px] rounded-lg" />
              <div className="shimmer-loading h-[14px] w-[100px] rounded-lg" />
            </div>
            <div className="flex flex-col items-center gap-2">
              <div className="shimmer-loading h-[16px] w-[50px] rounded-lg" />
              <div className="shimmer-loading h-[14px] w-[130px] rounded-lg" />
            </div>
          </div>
        </div>
      </section>

      {/* Features skeleton */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16 lg:py-20">
        <div className="flex flex-col items-center gap-3 mb-12">
          <div className="shimmer-loading h-[36px] w-[220px] rounded-lg" />
          <div className="shimmer-loading h-[14px] w-[400px] max-w-full rounded-lg" />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {[1, 2, 3].map((i) => (
            <div key={i} className="border border-[#00293d]/10 rounded-[15px] p-6 flex flex-col items-center gap-3">
              <div className="shimmer-loading w-[35px] h-[35px] rounded-full" />
              <div className="shimmer-loading h-[14px] w-[120px] rounded-lg" />
              <div className="shimmer-loading h-[12px] w-full rounded-lg" />
              <div className="shimmer-loading h-[12px] w-[90%] rounded-lg" />
              <div className="shimmer-loading h-[12px] w-[80%] rounded-lg" />
            </div>
          ))}
        </div>
      </section>

      {/* Team skeleton */}
      <section className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pb-16 lg:pb-20">
        <div className="flex flex-col items-center gap-3 mb-12">
          <div className="shimmer-loading h-[36px] w-[350px] max-w-full rounded-lg" />
          <div className="shimmer-loading h-[14px] w-[400px] max-w-full rounded-lg" />
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-5xl mx-auto">
          {[1, 2, 3].map((i) => (
            <div key={i} className="border border-[#00293d]/10 rounded-[15px] p-6 flex flex-col items-center gap-3">
              <div className="shimmer-loading w-[36px] h-[36px] rounded-full" />
              <div className="shimmer-loading h-[16px] w-[140px] rounded-lg" />
              <div className="shimmer-loading h-[12px] w-full rounded-lg" />
              <div className="shimmer-loading h-[12px] w-[90%] rounded-lg" />
              <div className="shimmer-loading h-[12px] w-[80%] rounded-lg" />
            </div>
          ))}
        </div>
      </section>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Smart image — shimmer while loading, hidden on error
// ---------------------------------------------------------------------------

function SmartImage({
  src,
  alt,
  className,
  shimmerClassName,
}: {
  src: string | undefined | null;
  alt: string;
  className?: string;
  shimmerClassName?: string;
}) {
  const [status, setStatus] = useState<'loading' | 'loaded' | 'error'>(src ? 'loading' : 'error');

  useEffect(() => {
    setStatus(src ? 'loading' : 'error');
  }, [src]);

  if (!src || status === 'error') return null;

  return (
    <div className="relative w-full h-full">
      {status === 'loading' && (
        <div className={`absolute inset-0 shimmer-loading ${shimmerClassName || ''}`} />
      )}
      {/* eslint-disable-next-line @next/next/no-img-element */}
      <img
        ref={(el) => { if (el?.complete) setStatus(el.naturalWidth > 0 ? 'loaded' : 'error'); }}
        src={src}
        alt={alt}
        className={`${className || ''} transition-opacity duration-300 ${status === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
        onLoad={() => setStatus('loaded')}
        onError={() => setStatus('error')}
      />
    </div>
  );
}

// ---------------------------------------------------------------------------
// Feature card — shimmer icon while loading
// ---------------------------------------------------------------------------

function FeatureCard({ feature }: { feature: AboutFeaturesContent['features'][number] }) {
  const [iconStatus, setIconStatus] = useState<'loading' | 'loaded' | 'error'>(
    feature.iconPath ? 'loading' : 'error'
  );

  useEffect(() => {
    setIconStatus(feature.iconPath ? 'loading' : 'error');
  }, [feature.iconPath]);

  return (
    <div className="border border-[#00293d]/10 rounded-[15px] p-6 text-center">
      <div className="flex items-center justify-center mb-4 h-[35px]">
        <div className="relative w-[35px] h-[35px]">
          {iconStatus === 'loading' && (
            <div className="absolute inset-0 rounded-full shimmer-loading" />
          )}
          {feature.iconPath && iconStatus !== 'error' && (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img
              ref={(el) => { if (el?.complete) setIconStatus(el.naturalWidth > 0 ? 'loaded' : 'error'); }}
              src={feature.iconPath}
              alt=""
              className={`w-[35px] h-[35px] object-contain transition-opacity duration-300 ${iconStatus === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
              onLoad={() => setIconStatus('loaded')}
              onError={() => setIconStatus('error')}
            />
          )}
        </div>
      </div>
      <h3 className="font-fractul font-bold text-[14px] text-[#00293d] mb-3">
        {feature.title}
      </h3>
      <p className="font-serif text-[14px] text-[#00293d] leading-relaxed">
        {feature.description}
      </p>
    </div>
  );
}

// ---------------------------------------------------------------------------
// Team card — shimmer image while loading
// ---------------------------------------------------------------------------

function TeamCard({ card }: { card: AboutTeamContent['cards'][number] }) {
  const [iconStatus, setIconStatus] = useState<'loading' | 'loaded' | 'error'>(
    card.iconPath ? 'loading' : 'error'
  );

  useEffect(() => {
    setIconStatus(card.iconPath ? 'loading' : 'error');
  }, [card.iconPath]);

  return (
    <div className="border border-[#00293d]/10 rounded-[15px] p-6 text-center h-full flex flex-col">
      <div className="flex items-center justify-center mb-4 h-[36px]">
        <div className="relative w-[36px] h-[36px]">
          {iconStatus === 'loading' && (
            <div className="absolute inset-0 rounded-full shimmer-loading" />
          )}
          {card.iconPath && iconStatus !== 'error' && (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img
              ref={(el) => { if (el?.complete) setIconStatus(el.naturalWidth > 0 ? 'loaded' : 'error'); }}
              src={card.iconPath}
              alt=""
              className={`w-[36px] h-[36px] object-contain transition-opacity duration-300 ${iconStatus === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
              onLoad={() => setIconStatus('loaded')}
              onError={() => setIconStatus('error')}
            />
          )}
        </div>
      </div>
      <h3 className="font-fractul font-bold text-[16px] text-[#00293d] mb-3">
        {card.title}
      </h3>
      <p className="font-serif text-[14px] text-[#00293d] leading-relaxed">
        {card.description}
      </p>
    </div>
  );
}
