'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 (Array.isArray(c.members) && c.members.length > 0) {
              const teamData = c as unknown as AboutTeamContent;
              for (const member of teamData.members) {
                member.imageUrl = await resolveImageUrl(member.imageUrl);
              }
              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>
              </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">
                    Our core principles guide every interaction, ensuring you feel confident and supported at every step.
                  </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.members.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">
                  <h2 className="font-fractul font-bold text-[30px] text-[#00293d] mb-3">
                    {team.title}
                  </h2>
                  <p className="font-serif text-[14px] text-[#00293d] max-w-[471px] mx-auto">
                    {team.subtitle}
                  </p>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-6 max-w-4xl mx-auto">
                  {team.members.map((member, index) => (
                    <TeamCard key={index} member={member} />
                  ))}
                </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-4xl mx-auto">
          {[1, 2, 3].map((i) => (
            <div key={i} className="border border-[#00293d]/10 rounded-[15px] p-4 flex flex-col items-center gap-3">
              <div className="shimmer-loading w-full h-[211px] rounded-[15px]" />
              <div className="shimmer-loading h-[14px] w-[80px] rounded-lg" />
              <div className="shimmer-loading h-[12px] w-[100px] 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({ member }: { member: AboutTeamContent['members'][number] }) {
  const [imgStatus, setImgStatus] = useState<'loading' | 'loaded' | 'error'>(
    member.imageUrl ? 'loading' : 'error'
  );

  useEffect(() => {
    setImgStatus(member.imageUrl ? 'loading' : 'error');
  }, [member.imageUrl]);

  return (
    <div className="border border-[#00293d]/10 rounded-[15px] p-4 text-center">
      <div className="w-full h-[211px] rounded-[15px] overflow-hidden mb-4 border border-[#00293d]/10 bg-gray-50">
        {imgStatus === 'loading' && (
          <div className="w-full h-full shimmer-loading rounded-[15px]" />
        )}
        {member.imageUrl && imgStatus !== 'error' && (
          /* eslint-disable-next-line @next/next/no-img-element */
          <img
            ref={(el) => { if (el?.complete) setImgStatus(el.naturalWidth > 0 ? 'loaded' : 'error'); }}
            src={member.imageUrl}
            alt={member.name}
            className={`w-full h-full object-cover transition-opacity duration-300 ${imgStatus === 'loaded' ? 'opacity-100' : 'opacity-0'}`}
            onLoad={() => setImgStatus('loaded')}
            onError={() => setImgStatus('error')}
          />
        )}
      </div>
      <h3 className="font-fractul font-bold text-[14px] text-black">
        {member.name}
      </h3>
      <p className="font-fractul font-light text-[14px] text-black">
        {member.role}
      </p>
    </div>
  );
}
