'use client';

import { useEffect, useState, useRef } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import {
  BedDouble, Bath, Maximize2, MapPin, ShieldCheck,
  CheckCircle2, ChevronLeft, ChevronRight, ArrowRight,
} from 'lucide-react';

// ─── Types ────────────────────────────────────────────────────
interface PropertyCard {
  id: number;
  title: string;
  slug: string;
  price: number;
  listing_type: string;
  completion_status: string;
  bedrooms: number | null;
  bathrooms: number | null;
  area_sqft: number | null;
  images_json: string | null;
  location_name: string;
  property_type: string;
  rera_verified_at: string | null;
  rera_permit_number?: string | null;
  is_featured: number;
}

interface PropertyType {
  id: number;
  name: string;
  display_name: string;
  category: string;
}

interface CategoryCount {
  id: number;
  display_name: string;
  name: string;
  count: number;
}

// ─── Helpers ──────────────────────────────────────────────────
const PLACEHOLDER = 'https://images.unsplash.com/photo-1512917774080-9991f1c4c750?w=800&q=75';

function getFirstImage(json: string | null): string {
  try {
    if (!json) return PLACEHOLDER;
    const arr = typeof json === 'string' ? JSON.parse(json) : json;
    if (Array.isArray(arr) && arr.length > 0) return arr[0]?.url ?? arr[0] ?? PLACEHOLDER;
  } catch { /* empty */ }
  return PLACEHOLDER;
}

const CATEGORY_IMAGES: Record<string, string> = {
  apartment:  'https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?w=600&q=75',
  villa:      'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=600&q=75',
  penthouse:  'https://images.unsplash.com/photo-1564013799919-ab600027ffc6?w=600&q=75',
  townhouse:  'https://images.unsplash.com/photo-1600607687939-ce8a6c25118c?w=600&q=75',
  studio:     'https://images.unsplash.com/photo-1600566753086-00f18fb6b3ea?w=600&q=75',
  office:     'https://images.unsplash.com/photo-1497366216548-37526070297c?w=600&q=75',
  retail:     'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=600&q=75',
  land:       'https://images.unsplash.com/photo-1500382017468-9049fed747ef?w=600&q=75',
  building:   'https://images.unsplash.com/photo-1486325212027-8081e485255e?w=600&q=75',
  warehouse:  'https://images.unsplash.com/photo-1586528116311-ad8dd3c8310d?w=600&q=75',
};

// ─── Sliding Banner ───────────────────────────────────────────
const SLIDES = [
  {
    headline: 'Buy Your Dream Home in Dubai',
    sub: 'Explore thousands of verified properties for sale across all communities.',
    cta: 'Browse for Sale',
    href: '/listings?listing_type=sale',
    gradient: 'from-[#0d1c32] via-[#1a3050] to-[#0d1c32]',
    accent: '#C5A880',
  },
  {
    headline: 'Premium Rentals Available Now',
    sub: 'Find your perfect rental — from studios to luxury villas across Dubai.',
    cta: 'Browse for Rent',
    href: '/listings?listing_type=rent',
    gradient: 'from-[#1a1a2e] via-[#16213e] to-[#0f3460]',
    accent: '#fedeb2',
  },
  {
    headline: 'Verified RERA Properties',
    sub: 'Every listing is RERA-certified and DLD-registered for your peace of mind.',
    cta: 'View Verified',
    href: '/listings?verified=1',
    gradient: 'from-[#0d2818] via-[#1a4a2e] to-[#0d2818]',
    accent: '#10B981',
  },
];

function SlidingBanner() {
  const [current, setCurrent] = useState(0);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const startTimer = () => {
    timerRef.current = setInterval(() => {
      setCurrent((c) => (c + 1) % SLIDES.length);
    }, 4000);
  };

  useEffect(() => {
    startTimer();
    return () => { if (timerRef.current) clearInterval(timerRef.current); };
  }, []);

  const goTo = (i: number) => {
    if (timerRef.current) clearInterval(timerRef.current);
    setCurrent(i);
    startTimer();
  };

  const slide = SLIDES[current];

  return (
    <section className="relative overflow-hidden h-72 sm:h-80">
      <AnimatePresence mode="wait">
        <motion.div
          key={current}
          initial={{ opacity: 0, x: 60 }}
          animate={{ opacity: 1, x: 0, transition: { duration: 0.5, ease: 'easeOut' } }}
          exit={{ opacity: 0, x: -60, transition: { duration: 0.35 } }}
          className={`absolute inset-0 bg-gradient-to-r ${slide.gradient} flex items-center justify-center`}
        >
          <div className="text-center px-6 max-w-2xl mx-auto">
            <motion.h2
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0, transition: { delay: 0.1, duration: 0.4 } }}
              className="font-serif text-3xl sm:text-4xl font-bold text-white mb-3 leading-tight"
            >
              {slide.headline}
            </motion.h2>
            <motion.p
              initial={{ opacity: 0, y: 16 }}
              animate={{ opacity: 1, y: 0, transition: { delay: 0.2, duration: 0.4 } }}
              className="text-white/70 text-sm mb-6 leading-relaxed"
            >
              {slide.sub}
            </motion.p>
            <motion.div
              initial={{ opacity: 0, y: 12 }}
              animate={{ opacity: 1, y: 0, transition: { delay: 0.3, duration: 0.4 } }}
            >
              <Link
                href={slide.href}
                className="inline-flex items-center gap-2 px-7 py-3 font-bold text-xs uppercase tracking-widest rounded-lg transition-all"
                style={{ backgroundColor: slide.accent, color: '#0d1c32' }}
              >
                {slide.cta} <ArrowRight className="w-3.5 h-3.5" />
              </Link>
            </motion.div>
          </div>
        </motion.div>
      </AnimatePresence>

      {/* Arrows */}
      <button
        onClick={() => goTo((current - 1 + SLIDES.length) % SLIDES.length)}
        className="absolute left-4 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full bg-white/10 backdrop-blur-sm text-white flex items-center justify-center hover:bg-white/20 transition-colors z-10"
      >
        <ChevronLeft className="w-5 h-5" />
      </button>
      <button
        onClick={() => goTo((current + 1) % SLIDES.length)}
        className="absolute right-4 top-1/2 -translate-y-1/2 w-9 h-9 rounded-full bg-white/10 backdrop-blur-sm text-white flex items-center justify-center hover:bg-white/20 transition-colors z-10"
      >
        <ChevronRight className="w-5 h-5" />
      </button>

      {/* Dots */}
      <div className="absolute bottom-5 left-1/2 -translate-x-1/2 flex gap-2 z-10">
        {SLIDES.map((_, i) => (
          <button
            key={i}
            onClick={() => goTo(i)}
            className={`rounded-full transition-all duration-300 ${i === current ? 'w-6 h-2 bg-white' : 'w-2 h-2 bg-white/40'}`}
          />
        ))}
      </div>
    </section>
  );
}

// ─── Property Card ────────────────────────────────────────────
function PropCard({ p }: { p: PropertyCard }) {
  const router = useRouter();
  const isVerified = !!(p.rera_verified_at || p.rera_permit_number);

  return (
    <button
      onClick={() => router.push(`/listings/${p.slug}`)}
      className="group bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-xl transition-all duration-300 text-left w-full hover:-translate-y-1"
    >
      <div className="relative h-52 overflow-hidden bg-gray-100">
        <Image
          src={getFirstImage(p.images_json)}
          alt={p.title}
          fill
          sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
          className="object-cover group-hover:scale-105 transition-transform duration-700"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent" />

        {/* Badges */}
        <div className="absolute top-3 left-3 flex gap-1.5 z-10 flex-wrap">
          <span className={`text-[9px] font-bold px-2 py-1 rounded uppercase tracking-wider ${
            p.listing_type === 'rent' ? 'bg-purple-500 text-white' : 'bg-[#0d1c32] text-white'
          }`}>
            {p.listing_type === 'rent' ? 'Rent' : 'Sale'}
          </span>
          {isVerified && (
            <span className="flex items-center gap-1 text-[9px] font-bold px-2 py-1 rounded bg-emerald-500 text-white uppercase tracking-wider">
              <ShieldCheck className="w-2.5 h-2.5" /> RERA
            </span>
          )}
        </div>

        <div className="absolute bottom-3 left-3 right-3 z-10">
          <p className="font-serif text-lg font-bold text-white">
            AED {Number(p.price).toLocaleString('en-AE')}
          </p>
        </div>
      </div>

      <div className="p-4">
        <p className="text-[10px] font-bold text-[#C5A880] uppercase tracking-widest mb-1 flex items-center gap-1">
          <MapPin className="w-3 h-3" /> {p.location_name}
        </p>
        <h3 className="font-bold text-[#0d1c32] text-sm leading-snug mb-3 group-hover:text-[#C5A880] transition-colors line-clamp-2">
          {p.title}
        </h3>
        <div className="flex items-center gap-3 text-[10px] text-gray-400 border-t border-gray-50 pt-3">
          {p.bedrooms != null && <span className="flex items-center gap-1"><BedDouble className="w-3 h-3" /> {p.bedrooms} BR</span>}
          {p.bathrooms != null && <span className="flex items-center gap-1"><Bath className="w-3 h-3" /> {p.bathrooms} BA</span>}
          {p.area_sqft && <span className="flex items-center gap-1"><Maximize2 className="w-3 h-3" /> {Number(p.area_sqft).toLocaleString()} sqft</span>}
        </div>
      </div>
    </button>
  );
}

// ─── Main HomeSections export ─────────────────────────────────
export function HomeSections() {
  const router = useRouter();

  const [propertyTypes,  setPropertyTypes]  = useState<PropertyType[]>([]);
  const [activeTypeId,   setActiveTypeId]   = useState<number | null>(null);
  const [featured,       setFeatured]       = useState<PropertyCard[]>([]);
  const [verified,       setVerified]       = useState<PropertyCard[]>([]);
  const [categories,     setCategories]     = useState<CategoryCount[]>([]);
  const [loadingFeatured, setLoadingFeatured] = useState(true);
  const [loadingVerified, setLoadingVerified] = useState(true);

  // Load property types for tabs
  useEffect(() => {
    fetch('/api/meta/filters')
      .then((r) => r.json())
      .then((d) => {
        if (d.success) setPropertyTypes(d.data.propertyTypes ?? []);
      })
      .catch(() => {});
  }, []);

  // Load category counts
  useEffect(() => {
    fetch('/api/meta/categories')
      .then((r) => r.json())
      .then((d) => { if (d.success) setCategories(d.data); })
      .catch(() => {});
  }, []);

  // Load featured properties (re-fetch when active tab changes)
  useEffect(() => {
    setLoadingFeatured(true);
    const qs = new URLSearchParams({ is_featured: '1', limit: '6' });
    if (activeTypeId) qs.set('property_type_id', String(activeTypeId));
    fetch(`/api/properties?${qs}`)
      .then((r) => r.json())
      .then((d) => { if (d.success) setFeatured(d.data); })
      .catch(() => {})
      .finally(() => setLoadingFeatured(false));
  }, [activeTypeId]);

  // Load verified properties once
  useEffect(() => {
    setLoadingVerified(true);
    fetch('/api/properties?verified=1&limit=3')
      .then((r) => r.json())
      .then((d) => { if (d.success) setVerified(d.data); })
      .catch(() => {})
      .finally(() => setLoadingVerified(false));
  }, []);

  return (
    <>
      {/* ── B: Category Tabs + Featured Grid ── */}
      <section className="py-16 px-6 lg:px-20 bg-[#f7f9fb]">
        <div className="max-w-7xl mx-auto">
          {/* Section header */}
          <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 mb-8">
            <div>
              <span className="text-[10px] font-bold text-[#C5A880] uppercase tracking-[0.22em] mb-2 block">
                Curated Selection
              </span>
              <h2 className="font-serif text-3xl md:text-4xl font-bold text-[#0d1c32]">
                Featured Properties
              </h2>
            </div>
            <Link
              href="/listings"
              className="group flex items-center gap-2 text-[11px] font-bold text-[#0d1c32] border-b border-[#0d1c32] pb-0.5 hover:text-[#C5A880] hover:border-[#C5A880] transition-all whitespace-nowrap"
            >
              VIEW ALL <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
            </Link>
          </div>

          {/* Category pill tabs */}
          {propertyTypes.length > 0 && (
            <div className="flex gap-2 overflow-x-auto pb-2 mb-8 scrollbar-hide">
              <button
                onClick={() => setActiveTypeId(null)}
                className={`shrink-0 px-4 py-2 rounded-full text-xs font-bold uppercase tracking-wider transition-all ${
                  activeTypeId === null
                    ? 'bg-[#0d1c32] text-white shadow-md'
                    : 'bg-white text-gray-500 border border-gray-200 hover:border-[#C5A880]'
                }`}
              >
                All
              </button>
              {propertyTypes.map((pt) => (
                <motion.button
                  key={pt.id}
                  onClick={() => setActiveTypeId(pt.id === activeTypeId ? null : pt.id)}
                  className={`shrink-0 px-4 py-2 rounded-full text-xs font-bold uppercase tracking-wider transition-all ${
                    activeTypeId === pt.id
                      ? 'bg-[#C5A880] text-[#0d1c32] shadow-md'
                      : 'bg-white text-gray-500 border border-gray-200 hover:border-[#C5A880]'
                  }`}
                  whileTap={{ scale: 0.96 }}
                >
                  {pt.display_name}
                </motion.button>
              ))}
            </div>
          )}

          {/* Featured grid */}
          {loadingFeatured ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {Array.from({ length: 6 }).map((_, i) => (
                <div key={i} className="bg-white rounded-xl overflow-hidden shadow-sm animate-pulse">
                  <div className="h-52 bg-gray-200" />
                  <div className="p-4 space-y-3">
                    <div className="h-4 bg-gray-200 rounded w-3/4" />
                    <div className="h-3 bg-gray-200 rounded w-1/2" />
                  </div>
                </div>
              ))}
            </div>
          ) : featured.length === 0 ? (
            <div className="text-center py-16">
              <p className="text-gray-400 text-sm">No featured properties yet. Add some via the admin panel.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {featured.map((p) => <PropCard key={p.id} p={p} />)}
            </div>
          )}

          <div className="text-center mt-10">
            <Link
              href={activeTypeId ? `/listings?property_type_id=${activeTypeId}` : '/listings'}
              className="inline-flex items-center gap-2 px-8 py-3.5 bg-[#0d1c32] text-white text-xs font-bold uppercase tracking-widest hover:bg-[#C5A880] hover:text-[#0d1c32] transition-all"
            >
              View All Properties <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </section>

      {/* ── C: Verified Properties ── */}
      <section className="py-16 px-6 lg:px-20 bg-white">
        <div className="max-w-7xl mx-auto">
          <div className="flex flex-col sm:flex-row sm:items-end justify-between gap-4 mb-8">
            <div>
              <span className="text-[10px] font-bold text-emerald-600 uppercase tracking-[0.22em] mb-2 block flex items-center gap-1.5">
                <ShieldCheck className="w-3.5 h-3.5" /> RERA Certified
              </span>
              <h2 className="font-serif text-3xl md:text-4xl font-bold text-[#0d1c32]">
                Verified Properties
              </h2>
            </div>
            <Link
              href="/listings?verified=1"
              className="group flex items-center gap-2 text-[11px] font-bold text-[#0d1c32] border-b border-[#0d1c32] pb-0.5 hover:text-[#C5A880] hover:border-[#C5A880] transition-all whitespace-nowrap"
            >
              VIEW ALL VERIFIED <ArrowRight className="w-3.5 h-3.5 group-hover:translate-x-1 transition-transform" />
            </Link>
          </div>

          {loadingVerified ? (
            <div className="flex gap-6 overflow-x-auto pb-2">
              {Array.from({ length: 3 }).map((_, i) => (
                <div key={i} className="min-w-[300px] bg-gray-100 rounded-xl h-72 animate-pulse shrink-0" />
              ))}
            </div>
          ) : verified.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-gray-400 text-sm">No verified properties yet.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6 overflow-x-auto">
              {verified.map((p) => (
                <div key={p.id} className="relative">
                  <PropCard p={p} />
                  <div className="absolute top-3 right-3 z-20">
                    <span className="flex items-center gap-1 text-[9px] font-bold px-2 py-1 rounded bg-[#C5A880] text-[#0d1c32] uppercase tracking-wider shadow">
                      <CheckCircle2 className="w-2.5 h-2.5" /> RERA Verified
                    </span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* ── D: Categories Showcase (Bento Grid) ── */}
      {categories.length > 0 && (
        <section className="py-16 px-6 lg:px-20 bg-[#f7f9fb]">
          <div className="max-w-7xl mx-auto">
            <div className="text-center mb-10">
              <span className="text-[10px] font-bold text-[#C5A880] uppercase tracking-[0.22em] mb-2 block">
                Browse by Type
              </span>
              <h2 className="font-serif text-3xl md:text-4xl font-bold text-[#0d1c32]">
                Property Categories
              </h2>
            </div>

            <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
              {categories.slice(0, 8).map((cat) => (
                <button
                  key={cat.id}
                  onClick={() => router.push(`/listings?property_type_id=${cat.id}`)}
                  className="group relative overflow-hidden rounded-xl aspect-[4/3] bg-gray-200 hover:shadow-xl transition-all duration-300"
                >
                  <Image
                    src={CATEGORY_IMAGES[cat.name] ?? PLACEHOLDER}
                    alt={cat.display_name}
                    fill
                    sizes="(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 25vw"
                    className="object-cover group-hover:scale-110 transition-transform duration-700"
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/20 to-transparent" />
                  <div className="absolute bottom-0 left-0 right-0 p-4 text-left">
                    <p className="font-serif font-bold text-white text-base leading-tight">
                      {cat.display_name}
                    </p>
                    <p className="text-white/70 text-[10px] mt-0.5 font-semibold uppercase tracking-wider">
                      {cat.count} {cat.count === 1 ? 'listing' : 'listings'}
                    </p>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* ── E: Sliding Banner ── */}
      <SlidingBanner />

      {/* ── Trust strip ── */}
      <section className="py-10 px-6 lg:px-20 bg-white border-t border-gray-100">
        <div className="max-w-7xl mx-auto flex flex-wrap items-center justify-center gap-8">
          {['RERA Verified', 'DLD Registered', 'Title Deed Secured', 'Agent BRN Certified'].map((b) => (
            <div key={b} className="flex items-center gap-2 text-[11px] font-semibold text-[#725b38]">
              <CheckCircle2 className="w-4 h-4 text-emerald-500" />
              {b}
            </div>
          ))}
        </div>
      </section>
    </>
  );
}
