"use client";

import React, { useState, useMemo, useEffect, Suspense } from "react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import {
  Building2,
  Home,
  MapPin,
  DollarSign,
  Bed,
  Bath,
  Layers,
  Camera,
  User,
  Phone,
  Mail,
  CheckCircle2,
  ShieldCheck,
  Sparkles,
  ArrowRight,
  ArrowLeft,
  Eye,
  FileText,
  HelpCircle,
  Clock,
  UserCheck,
  KeyRound,
  AlertCircle,
  Loader2
} from "lucide-react";
import { SRI_LANKA_LOCATIONS } from "@/data/portalData";
import { fetchPublicAgents, submitSellListing, PublicAgentItem } from "@/services/propertyService";
import { useAuth } from "@/context/AuthContext";

function SellPropertyContent() {
  const searchParams = useSearchParams();
  const initialAgentParam = searchParams.get("agent");
  const { user, isLoggedIn } = useAuth();

  const [agentsList, setAgentsList] = useState<PublicAgentItem[]>([]);
  const [selectedAgentId, setSelectedAgentId] = useState<string | number>("");
  const [currentStep, setCurrentStep] = useState(1);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [submittedResponseData, setSubmittedResponseData] = useState<any>(null);

  // Form State
  const [formData, setFormData] = useState({
    listingIntent: "sale" as "sale" | "rent",
    category: "House",
    propertyTitle: "",
    city: "Colombo",
    address: "",
    perches: "",
    sqft: "",
    askingPriceLKR: "",
    monthlyRentLKR: "",
    depositMonths: "6",
    bedrooms: "3",
    bathrooms: "2",
    titleStatus: "Clear Title (Deed Available)",
    hasSwimmingPool: false,
    hasGarden: true,
    hasThreePhasePower: true,
    description: "",
    request360Tour: true,
    sellerName: "",
    sellerPhone: "",
    sellerWhatsapp: "",
    sellerEmail: ""
  });

  // Fetch live agents on load
  useEffect(() => {
    async function loadAgents() {
      try {
        const fetched = await fetchPublicAgents();
        if (fetched && fetched.length > 0) {
          setAgentsList(fetched);

          if (initialAgentParam) {
            const cleanParam = initialAgentParam.toLowerCase();
            const matched = fetched.find(
              (a) =>
                a.slug?.toLowerCase() === cleanParam ||
                String(a.id) === cleanParam ||
                a.name.toLowerCase().includes(cleanParam)
            );
            if (matched) {
              setSelectedAgentId(matched.id);
              return;
            }
          }

          // Default to first agent
          setSelectedAgentId(fetched[0].id);
        }
      } catch (err) {
        console.error("Could not fetch agents:", err);
      }
    }

    loadAgents();
  }, [initialAgentParam]);

  // Pre-fill user profile if logged in
  useEffect(() => {
    if (isLoggedIn && user) {
      setFormData((prev) => ({
        ...prev,
        sellerName: prev.sellerName || user.name || "",
        sellerEmail: prev.sellerEmail || user.email || "",
        sellerPhone: prev.sellerPhone || (user as any).phone || "",
        sellerWhatsapp: prev.sellerWhatsapp || (user as any).phone || "",
      }));
    }
  }, [isLoggedIn, user]);

  const activeAgent = useMemo<PublicAgentItem | null>(() => {
    if (agentsList.length === 0) return null;
    return agentsList.find((a) => String(a.id) === String(selectedAgentId)) || agentsList[0];
  }, [agentsList, selectedAgentId]);

  const handleInputChange = (field: string, value: any) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  };

  const handleNext = async (e: React.FormEvent) => {
    e.preventDefault();
    setErrorMessage("");

    if (currentStep < 4) {
      setCurrentStep(currentStep + 1);
      window.scrollTo({ top: 120, behavior: "smooth" });
    } else {
      // Final step: Submit directly to Backend API
      setIsSubmitting(true);
      try {
        let numericPrice: number | undefined = undefined;
        let numericRent: number | undefined = undefined;

        if (formData.listingIntent === "sale" && formData.askingPriceLKR) {
          // If user entered e.g. 28.5 (Million), convert to full LKR or accept numeric
          const val = parseFloat(formData.askingPriceLKR);
          numericPrice = val < 10000 ? val * 1000000 : val;
        } else if (formData.listingIntent === "rent" && formData.monthlyRentLKR) {
          numericRent = parseFloat(formData.monthlyRentLKR);
        }

        const payload = {
          listing_intent: formData.listingIntent,
          category: formData.category,
          property_title: formData.propertyTitle,
          city: formData.city,
          address: formData.address,
          perches: formData.perches ? parseFloat(formData.perches) : undefined,
          sqft: formData.sqft ? parseFloat(formData.sqft) : undefined,
          asking_price: numericPrice,
          monthly_rent: numericRent,
          deposit_months: formData.depositMonths,
          bedrooms: parseInt(formData.bedrooms) || 0,
          bathrooms: parseInt(formData.bathrooms) || 0,
          title_status: formData.titleStatus,
          has_swimming_pool: formData.hasSwimmingPool,
          has_garden: formData.hasGarden,
          has_three_phase_power: formData.hasThreePhasePower,
          description: formData.description,
          request_360_tour: formData.request360Tour,
          agent_id: activeAgent?.id,
          agent_slug: activeAgent?.slug,
          seller_name: formData.sellerName,
          seller_phone: formData.sellerPhone,
          seller_whatsapp: formData.sellerWhatsapp || formData.sellerPhone,
          seller_email: formData.sellerEmail,
        };

        const authToken = typeof window !== "undefined" ? localStorage.getItem("customer_token") : null;
        const result = await submitSellListing(payload, authToken);
        if (result.success) {
          setSubmittedResponseData(result.data);
          setIsSubmitted(true);
          window.scrollTo({ top: 100, behavior: "smooth" });
        } else {
          setErrorMessage(result.message || "Submission failed. Please check your details and try again.");
        }
      } catch (err: any) {
        setErrorMessage(err.message || "An unexpected error occurred. Please try again.");
      } finally {
        setIsSubmitting(false);
      }
    }
  };

  const handleBack = () => {
    if (currentStep > 1) {
      setCurrentStep(currentStep - 1);
      window.scrollTo({ top: 120, behavior: "smooth" });
    }
  };

  const displayedAgent = submittedResponseData?.agent || activeAgent;

  return (
    <div className="min-h-screen py-10 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

      {/* Header */}
      <div className="text-center max-w-3xl mx-auto space-y-4 mb-12">
        <h1 className="text-3xl sm:text-4xl md:text-5xl font-extrabold text-white tracking-tight font-display-lg">
          List Your Property for <span className="text-[#FFE259]">Sale or Rent</span>
        </h1>
        <p className="text-slate-300 text-sm sm:text-base leading-relaxed">
          Every listing on DreamHomes is represented directly by an appointed professional agent who conducts legal screening, creates 360° VR media, and presents your property to pre-qualified buyers and tenants.
        </p>
      </div>

      {isSubmitted ? (
        /* Submission Success Card */
        <div className="max-w-2xl mx-auto bg-[#0e0e10] rounded-3xl border border-[#FFE259]/30 text-white p-10 shadow-2xl text-center space-y-6 animate-in fade-in zoom-in-95 duration-300">
          <div className="w-20 h-20 rounded-full bg-[#18181b] border-2 border-[#FFE259] text-[#FFE259] flex items-center justify-center mx-auto text-3xl font-bold shadow-lg shadow-[#FFE259]/20">
            <CheckCircle2 className="w-10 h-10" />
          </div>

          <div className="space-y-2">
            <span className="px-3.5 py-1 rounded-full text-xs font-extrabold bg-[#0A0A0A] text-[#FFE259] border border-[#FFA726]/40">
              Listing Connected &amp; Routed Directly to Agent
            </span>
            <h2 className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight font-display-lg">
              Thank You, <span className="text-[#FFE259]">{formData.sellerName || "Valued Property Owner"}</span>!
            </h2>
            <p className="text-xs sm:text-sm text-slate-300 max-w-md mx-auto leading-relaxed">
              Your property in <strong className="text-white">{formData.city}</strong> for <strong className="text-[#FFE259]">{formData.listingIntent === "sale" ? "Sale" : "Rent"}</strong> has been registered and assigned directly to <strong className="text-white">{displayedAgent?.name || "our Senior Broker"}</strong>.
            </p>
          </div>

          {/* Assigned Agent Confirmation Card */}
          {displayedAgent && (
            <div className="p-5 bg-[#18181b] rounded-2xl border border-[#FFE259]/30 text-slate-300 text-left space-y-3 shadow-md">
              <div className="flex items-center gap-3">
                <img
                  src={displayedAgent.avatar || "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=400&q=80"}
                  alt={displayedAgent.name}
                  className="w-12 h-12 rounded-full object-cover border-2 border-[#FFE259]/60 shadow-md"
                />
                <div>
                  <h4 className="text-lg font-bold text-white font-display-lg">{displayedAgent.name}</h4>
                  <p className="text-xs text-[#FFE259] font-semibold">{displayedAgent.role || "Certified Agent"}</p>
                  <p className="text-[10px] text-slate-400">{displayedAgent.division || displayedAgent.department || "DreamHomes Realty"}</p>
                </div>
              </div>

              <div className="pt-2 border-t border-zinc-800 grid grid-cols-2 gap-2 text-xs">
                <div>
                  <span className="text-slate-400 block text-[11px]">Direct Hotline:</span>
                  <strong className="text-[#FFE259]">{displayedAgent.phone || "+94 11 234 5678"}</strong>
                </div>
                <div>
                  <span className="text-slate-400 block text-[11px]">Direct WhatsApp:</span>
                  <strong className="text-[#FFE259]">{displayedAgent.whatsapp || displayedAgent.phone || "Active"}</strong>
                </div>
              </div>
            </div>
          )}

          <div className="pt-4 flex flex-wrap justify-center gap-3">
            <Link
              href="/properties"
              className="bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs px-6 py-3 rounded-full shadow-md shadow-[#059669]/20 transition-all cursor-pointer"
            >
              Browse Active Properties
            </Link>
            <button
              onClick={() => {
                setIsSubmitted(false);
                setSubmittedResponseData(null);
                setCurrentStep(1);
              }}
              className="bg-[#18181b] hover:bg-zinc-800 text-[#FFE259] border border-[#FFE259]/30 font-bold text-xs px-6 py-3 rounded-full transition-all cursor-pointer"
            >
              Submit Another Property
            </button>
          </div>
        </div>
      ) : (
        /* Main 2-Column Listing Interface */
        <div className="grid grid-cols-1 lg:grid-cols-12 gap-10 items-start">

          {/* Left Column: 4-Step Submission Form (7 Cols) */}
          <div className="lg:col-span-7 bg-[#0e0e10] rounded-3xl border border-[#FFE259]/30 text-white p-6 sm:p-8 shadow-2xl space-y-6">

            {/* Step Progress Indicator */}
            <div className="flex items-center justify-between border-b border-zinc-800 pb-4">
              {[
                { step: 1, label: "Type & Location" },
                { step: 2, label: "Specs & Pricing" },
                { step: 3, label: "Media & Details" },
                { step: 4, label: "Contact Info" }
              ].map((s) => (
                <div key={s.step} className="flex items-center gap-2">
                  <div
                    className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-extrabold transition-colors ${
                      currentStep === s.step
                        ? "bg-[#FFE259] text-black ring-2 ring-[#FFE259]/50"
                        : currentStep > s.step
                        ? "bg-[#059669] text-white"
                        : "bg-zinc-800 text-slate-400"
                    }`}
                  >
                    {currentStep > s.step ? <CheckCircle2 className="w-4 h-4" /> : s.step}
                  </div>
                  <span
                    className={`hidden sm:inline text-xs font-bold ${
                      currentStep === s.step ? "text-white" : "text-slate-500"
                    }`}
                  >
                    {s.label}
                  </span>
                </div>
              ))}
            </div>

            {/* Error Message Banner */}
            {errorMessage && (
              <div className="p-4 rounded-2xl bg-rose-950/80 border border-rose-500/50 text-rose-300 text-xs font-bold flex items-center gap-2.5 animate-in fade-in">
                <AlertCircle className="w-5 h-5 text-rose-400 shrink-0" />
                <span>{errorMessage}</span>
              </div>
            )}

            {/* Customer Logged In Notice */}
            {isLoggedIn && user && (
              <div className="p-3 bg-[#18181b] rounded-xl border border-zinc-700 text-xs flex items-center justify-between text-slate-300">
                <span className="flex items-center gap-1.5">
                  <UserCheck className="w-4 h-4 text-[#FFE259]" /> Logged in as: <strong className="text-white">{user.name}</strong> ({user.email})
                </span>
                <span className="text-[10px] bg-[#0A0A0A] text-[#FFE259] border border-[#FFA726]/40 px-2 py-0.5 rounded-full font-bold">
                  Verified Customer
                </span>
              </div>
            )}

            <form onSubmit={handleNext} className="space-y-6">

              {/* STEP 1: Type & Location */}
              {currentStep === 1 && (
                <div className="space-y-5 animate-in fade-in duration-200">
                  
                  {/* Intent Selection: Sale vs Rent */}
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-2">
                      I Want To *
                    </label>
                    <div className="grid grid-cols-2 gap-3">
                      <button
                        type="button"
                        onClick={() => handleInputChange("listingIntent", "sale")}
                        className={`py-3.5 px-4 rounded-2xl border text-xs sm:text-sm font-extrabold flex items-center justify-center gap-2 transition-all cursor-pointer ${
                          formData.listingIntent === "sale"
                            ? "bg-[#FFE259] text-black border-[#FFE259] shadow-lg shadow-[#FFE259]/20"
                            : "bg-[#18181b] border-zinc-700 text-slate-300 hover:border-zinc-500"
                        }`}
                      >
                        <Home className="w-4 h-4" />
                        <span>Sell My Property</span>
                      </button>

                      <button
                        type="button"
                        onClick={() => handleInputChange("listingIntent", "rent")}
                        className={`py-3.5 px-4 rounded-2xl border text-xs sm:text-sm font-extrabold flex items-center justify-center gap-2 transition-all cursor-pointer ${
                          formData.listingIntent === "rent"
                            ? "bg-[#FFE259] text-black border-[#FFE259] shadow-lg shadow-[#FFE259]/20"
                            : "bg-[#18181b] border-zinc-700 text-slate-300 hover:border-zinc-500"
                        }`}
                      >
                        <KeyRound className="w-4 h-4" />
                        <span>Rent Out Property</span>
                      </button>
                    </div>
                  </div>

                  {/* Property Category */}
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                      Property Category *
                    </label>
                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
                      {["House", "Villa", "Apartment", "Land", "Bungalow", "Commercial", "Penthouse", "Estate"].map((cat) => (
                        <button
                          key={cat}
                          type="button"
                          onClick={() => handleInputChange("category", cat)}
                          className={`py-2.5 px-3 rounded-xl border text-xs font-bold transition-all cursor-pointer ${
                            formData.category === cat
                              ? "bg-[#18181b] border-[#FFE259] text-[#FFE259]"
                              : "bg-[#121214] border-zinc-700 text-slate-400 hover:text-white"
                          }`}
                        >
                          {cat}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Property Title */}
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                      Listing Title / Headline *
                    </label>
                    <input
                      type="text"
                      required
                      placeholder="e.g. Modern 3-Storey Luxury Villa with Swimming Pool"
                      value={formData.propertyTitle}
                      onChange={(e) => handleInputChange("propertyTitle", e.target.value)}
                      className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                    />
                  </div>

                  {/* City & Address */}
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        City / Prime Area *
                      </label>
                      <select
                        value={formData.city}
                        onChange={(e) => handleInputChange("city", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-3 py-3 text-xs sm:text-sm font-semibold text-white focus:outline-none cursor-pointer"
                      >
                        {SRI_LANKA_LOCATIONS.map((loc) => (
                          <option key={loc} value={loc}>{loc}</option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Street Address / Landmark
                      </label>
                      <input
                        type="text"
                        placeholder="e.g. Temple Road, off Pannipitiya Rd"
                        value={formData.address}
                        onChange={(e) => handleInputChange("address", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                      />
                    </div>
                  </div>

                </div>
              )}

              {/* STEP 2: Specs & Pricing */}
              {currentStep === 2 && (
                <div className="space-y-4 animate-in fade-in duration-200">
                  
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Land Extent (Perches)
                      </label>
                      <input
                        type="number"
                        step="0.5"
                        placeholder="e.g. 12.5"
                        value={formData.perches}
                        onChange={(e) => handleInputChange("perches", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Floor Area (SqFt)
                      </label>
                      <input
                        type="number"
                        placeholder="e.g. 3200"
                        value={formData.sqft}
                        onChange={(e) => handleInputChange("sqft", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                      />
                    </div>
                  </div>

                  {formData.listingIntent === "sale" ? (
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Expected Asking Sale Price (in Million LKR) *
                      </label>
                      <div className="relative">
                        <input
                          type="number"
                          required
                          step="0.5"
                          placeholder="e.g. 28.5 (Meaning LKR 28,500,000)"
                          value={formData.askingPriceLKR}
                          onChange={(e) => handleInputChange("askingPriceLKR", e.target.value)}
                          className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl pl-12 pr-4 py-3 text-sm font-bold text-white focus:outline-none transition-colors"
                        />
                        <span className="absolute left-3.5 top-3.5 text-xs font-extrabold text-[#FFE259]">LKR</span>
                      </div>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div>
                        <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                          Monthly Rent (in LKR) *
                        </label>
                        <div className="relative">
                          <input
                            type="number"
                            required
                            step="1000"
                            placeholder="e.g. 150000"
                            value={formData.monthlyRentLKR}
                            onChange={(e) => handleInputChange("monthlyRentLKR", e.target.value)}
                            className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl pl-12 pr-4 py-3 text-sm font-bold text-white focus:outline-none transition-colors"
                          />
                          <span className="absolute left-3.5 top-3.5 text-xs font-extrabold text-[#FFE259]">LKR</span>
                        </div>
                      </div>
                      <div>
                        <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                          Security Deposit (Months)
                        </label>
                        <select
                          value={formData.depositMonths}
                          onChange={(e) => handleInputChange("depositMonths", e.target.value)}
                          className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-3 py-3 text-sm font-bold text-white focus:outline-none cursor-pointer"
                        >
                          <option value="3">3 Months Deposit</option>
                          <option value="6">6 Months Deposit</option>
                          <option value="12">1 Year Advance</option>
                        </select>
                      </div>
                    </div>
                  )}

                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Bedrooms
                      </label>
                      <select
                        value={formData.bedrooms}
                        onChange={(e) => handleInputChange("bedrooms", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-3 py-3 text-xs sm:text-sm font-semibold text-white focus:outline-none cursor-pointer"
                      >
                        {[1, 2, 3, 4, 5, 6, "7+"].map((b) => (
                          <option key={b} value={b}>{b} Bedrooms</option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Bathrooms
                      </label>
                      <select
                        value={formData.bathrooms}
                        onChange={(e) => handleInputChange("bathrooms", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-3 py-3 text-xs sm:text-sm font-semibold text-white focus:outline-none cursor-pointer"
                      >
                        {[1, 2, 3, 4, 5, "6+"].map((b) => (
                          <option key={b} value={b}>{b} Bathrooms</option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                      Title Deed Status *
                    </label>
                    <select
                      value={formData.titleStatus}
                      onChange={(e) => handleInputChange("titleStatus", e.target.value)}
                      className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-3 py-3 text-xs sm:text-sm font-semibold text-white focus:outline-none cursor-pointer"
                    >
                      <option value="Clear Title (Deed Available)">Clear Title (Deed in Owner Possession &amp; 30-Yr Extract Available)</option>
                      <option value="Bank Mortgaged">Bank Mortgaged (Active Loan Clearance Required)</option>
                      <option value="Bimsaviya 1st Class">Bimsaviya Title (Title Registration First Class)</option>
                      <option value="Inheritance / Pending Probate">Inherited Estate / Pending Court Clearance</option>
                    </select>
                  </div>

                  <div className="pt-2">
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-2">
                      Key Highlights
                    </label>
                    <div className="grid grid-cols-3 gap-2">
                      <label className="flex items-center gap-2 p-3 rounded-xl bg-[#18181b] border border-zinc-700 text-xs font-semibold text-slate-200 cursor-pointer hover:border-[#FFE259]/40">
                        <input
                          type="checkbox"
                          checked={formData.hasSwimmingPool}
                          onChange={(e) => handleInputChange("hasSwimmingPool", e.target.checked)}
                          className="accent-[#FFE259]"
                        />
                        <span>Swimming Pool</span>
                      </label>
                      <label className="flex items-center gap-2 p-3 rounded-xl bg-[#18181b] border border-zinc-700 text-xs font-semibold text-slate-200 cursor-pointer hover:border-[#FFE259]/40">
                        <input
                          type="checkbox"
                          checked={formData.hasGarden}
                          onChange={(e) => handleInputChange("hasGarden", e.target.checked)}
                          className="accent-[#FFE259]"
                        />
                        <span>Private Garden</span>
                      </label>
                      <label className="flex items-center gap-2 p-3 rounded-xl bg-[#18181b] border border-zinc-700 text-xs font-semibold text-slate-200 cursor-pointer hover:border-[#FFE259]/40">
                        <input
                          type="checkbox"
                          checked={formData.hasThreePhasePower}
                          onChange={(e) => handleInputChange("hasThreePhasePower", e.target.checked)}
                          className="accent-[#FFE259]"
                        />
                        <span>3-Phase Electricity</span>
                      </label>
                    </div>
                  </div>
                </div>
              )}

              {/* STEP 3: Media & Details */}
              {currentStep === 3 && (
                <div className="space-y-4 animate-in fade-in duration-200">
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                      Property Description &amp; Special Features
                    </label>
                    <textarea
                      rows={4}
                      placeholder="Describe the layout, neighborhood, road width (e.g. 20ft carpeted road), proximity to highways, supermarket, schools, etc."
                      value={formData.description}
                      onChange={(e) => handleInputChange("description", e.target.value)}
                      className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                    />
                  </div>

                  {/* Upload Info Card */}
                  <div className="border-2 border-dashed border-[#FFE259]/40 hover:border-[#FFE259] rounded-2xl p-6 text-center space-y-2 cursor-pointer transition-colors bg-[#18181b]">
                    <Camera className="w-8 h-8 text-[#FFE259] mx-auto" />
                    <span className="text-xs font-bold text-white block">
                      Photos &amp; Document Review
                    </span>
                    <p className="text-[11px] text-slate-400">
                      Our appointed agent will schedule a visit to take professional architectural photos, or you can WhatsApp images directly to {activeAgent?.name || "your agent"}.
                    </p>
                  </div>

                  <div className="p-4 bg-[#18181b] rounded-2xl border border-[#FFE259]/30 flex items-center justify-between">
                    <div className="space-y-0.5">
                      <span className="text-xs font-extrabold text-[#FFE259] flex items-center gap-1.5">
                        <Eye className="w-4 h-4" /> Complimentary 360° VR &amp; Drone Shoot
                      </span>
                      <p className="text-[11px] text-slate-400">
                        Qualifying luxury properties receive a professional 360 virtual tour and 4K drone cinematography at zero upfront cost.
                      </p>
                    </div>
                    <input
                      type="checkbox"
                      checked={formData.request360Tour}
                      onChange={(e) => handleInputChange("request360Tour", e.target.checked)}
                      className="w-5 h-5 accent-[#FFE259]"
                    />
                  </div>
                </div>
              )}

              {/* STEP 4: Owner Contact */}
              {currentStep === 4 && (
                <div className="space-y-4 animate-in fade-in duration-200">
                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                      Owner / Landlord Full Name *
                    </label>
                    <input
                      type="text"
                      required
                      placeholder="e.g. Mr. K. Silva"
                      value={formData.sellerName}
                      onChange={(e) => handleInputChange("sellerName", e.target.value)}
                      className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                    />
                  </div>

                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        Phone Number *
                      </label>
                      <input
                        type="tel"
                        required
                        placeholder="077 123 4567"
                        value={formData.sellerPhone}
                        onChange={(e) => handleInputChange("sellerPhone", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                        WhatsApp Number
                      </label>
                      <input
                        type="tel"
                        placeholder="+94 77 123 4567"
                        value={formData.sellerWhatsapp}
                        onChange={(e) => handleInputChange("sellerWhatsapp", e.target.value)}
                        className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-xs font-bold uppercase tracking-wider text-slate-300 mb-1.5">
                      Email Address *
                    </label>
                    <input
                      type="email"
                      required
                      placeholder="owner@example.com"
                      value={formData.sellerEmail}
                      onChange={(e) => handleInputChange("sellerEmail", e.target.value)}
                      className="w-full bg-[#121214] border border-zinc-700 focus:border-[#FFE259] rounded-xl px-4 py-3 text-xs sm:text-sm text-white focus:outline-none transition-colors"
                    />
                  </div>

                  {/* Summary of Chosen Agent */}
                  {activeAgent && (
                    <div className="p-3.5 bg-[#18181b] rounded-xl border border-zinc-700 text-xs flex items-center justify-between">
                      <div>
                        <span className="text-slate-400 block text-[11px]">Assigned Specialist:</span>
                        <strong className="text-[#FFE259] font-extrabold">{activeAgent.name}</strong>
                      </div>
                      <span className="text-slate-400 font-semibold">{activeAgent.division || "Broker"}</span>
                    </div>
                  )}
                </div>
              )}

              {/* Form Navigation Buttons */}
              <div className="pt-4 border-t border-zinc-800 flex items-center justify-between gap-4">
                {currentStep > 1 ? (
                  <button
                    type="button"
                    disabled={isSubmitting}
                    onClick={handleBack}
                    className="px-6 py-3 rounded-full border border-zinc-700 hover:bg-zinc-800 text-slate-300 font-bold text-xs flex items-center gap-1.5 transition-colors cursor-pointer disabled:opacity-50"
                  >
                    <ArrowLeft className="w-4 h-4" />
                    <span>Back</span>
                  </button>
                ) : (
                  <div />
                )}

                <button
                  type="submit"
                  disabled={isSubmitting}
                  className="bg-[#059669] hover:bg-[#047857] text-white font-extrabold text-xs sm:text-sm px-8 py-3.5 rounded-full shadow-lg shadow-[#059669]/30 transition-all flex items-center gap-2 cursor-pointer ml-auto disabled:opacity-50"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="w-4 h-4 animate-spin" />
                      <span>Submitting to Agent...</span>
                    </>
                  ) : (
                    <>
                      <span>
                        {currentStep === 4
                          ? `Submit Property for ${formData.listingIntent === "sale" ? "Sale" : "Rent"} to ${activeAgent?.name || "Agent"}`
                          : "Continue to Next Step"}
                      </span>
                      <ArrowRight className="w-4 h-4" />
                    </>
                  )}
                </button>
              </div>

            </form>

          </div>

          {/* Right Column: Appointed Agent Profile & Seller Guarantee (5 Cols) */}
          <div className="lg:col-span-5 space-y-6">

            {/* Appointed Agent Representation Box */}
            {activeAgent && (
              <div className="bg-[#0e0e10] rounded-3xl border border-[#FFE259]/30 text-white p-6 shadow-2xl space-y-4">
                <div className="flex items-center justify-between">
                  <span className="text-xs uppercase tracking-wider font-extrabold text-[#FFE259]">
                    Your Appointed Real Estate Agent
                  </span>
                  <span className="w-2.5 h-2.5 rounded-full bg-[#FFE259] animate-pulse" />
                </div>

                <div className="flex items-center gap-4">
                  <img
                    src={activeAgent.avatar || "https://images.unsplash.com/photo-1560250097-0b93528c311a?auto=format&fit=crop&w=400&q=80"}
                    alt={activeAgent.name}
                    className="w-16 h-16 rounded-full object-cover border-2 border-[#FFE259]/60 shadow-md"
                  />
                  <div className="flex-1 min-w-0">
                    <h4 className="text-lg font-bold text-white font-display-lg truncate">{activeAgent.name}</h4>
                    <p className="text-xs text-[#FFE259] font-semibold">{activeAgent.role || "Real Estate Agent"}</p>
                    <p className="text-[11px] text-slate-400 mt-0.5 truncate">{activeAgent.division || activeAgent.department || "DreamHomes Realty"}</p>
                  </div>
                </div>

                {/* Agent Selector Dropdown if multiple agents available */}
                {agentsList.length > 1 && (
                  <div className="space-y-1">
                    <label className="text-[11px] font-bold text-slate-400 block uppercase">
                      Select Preferred Agent:
                    </label>
                    <select
                      value={selectedAgentId}
                      onChange={(e) => setSelectedAgentId(e.target.value)}
                      className="w-full bg-[#18181b] border border-zinc-700 text-xs text-white rounded-xl px-3 py-2 font-semibold focus:border-[#FFE259] focus:outline-none cursor-pointer"
                    >
                      {agentsList.map((ag) => (
                        <option key={ag.id} value={ag.id}>
                          {ag.name} ({ag.territory || ag.division || "Agent"})
                        </option>
                      ))}
                    </select>
                  </div>
                )}

                {activeAgent.bio && (
                  <p className="text-xs text-slate-300 leading-relaxed bg-[#18181b] p-3 rounded-xl border border-zinc-800 line-clamp-3">
                    {activeAgent.bio}
                  </p>
                )}

                <div className="pt-1 text-xs">
                  <div className="py-2.5 px-3 rounded-xl bg-[#18181b] text-[#FFE259] border border-[#FFE259]/30 font-bold flex items-center justify-center gap-2 text-center">
                    <CheckCircle2 className="w-4 h-4 text-[#FFE259] shrink-0" />
                    <span>Assigned Representative for this Listing</span>
                  </div>
                </div>
              </div>
            )}

            {/* Seller & Landlord Guarantees */}
            <div className="bg-[#0e0e10] text-white rounded-3xl p-6 sm:p-8 shadow-2xl border border-[#FFE259]/30 space-y-6">
              <div className="space-y-2">
                <span className="text-xs uppercase tracking-wider font-extrabold text-[#FFE259] block">
                  Exclusive Owner &amp; Landlord Advantages
                </span>
                <h3 className="text-xl sm:text-2xl font-extrabold font-display-lg">
                  Maximize Your Sale or Rental Value with <span className="text-[#FFE259]">Zero Friction</span>
                </h3>
              </div>

              <div className="space-y-4 text-xs">
                <div className="flex items-start gap-3">
                  <div className="p-2.5 rounded-xl bg-[#18181b] border border-[#FFE259]/40 text-[#FFE259] shrink-0 mt-0.5">
                    <ShieldCheck className="w-4 h-4 text-[#FFE259]" />
                  </div>
                  <div>
                    <h4 className="font-bold text-sm text-white">Pre-Screened Cash Buyers &amp; Verified Tenants</h4>
                    <p className="text-slate-300 mt-0.5 leading-relaxed">
                      We filter out non-serious inquiries, ensuring only verified local buyers, overseas diaspora, and vetted corporate tenants inspect your property.
                    </p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <div className="p-2.5 rounded-xl bg-[#18181b] border border-[#FFE259]/40 text-[#FFE259] shrink-0 mt-0.5">
                    <Eye className="w-4 h-4 text-[#FFE259]" />
                  </div>
                  <div>
                    <h4 className="font-bold text-sm text-white">State-of-the-Art 360° VR Production</h4>
                    <p className="text-slate-300 mt-0.5 leading-relaxed">
                      Immersive virtual walkthroughs enable foreign investors in London, Melbourne, and Dubai to inspect and submit offers remotely.
                    </p>
                  </div>
                </div>

                <div className="flex items-start gap-3">
                  <div className="p-2.5 rounded-xl bg-[#18181b] border border-[#FFE259]/40 text-[#FFE259] shrink-0 mt-0.5">
                    <FileText className="w-4 h-4 text-[#FFE259]" />
                  </div>
                  <div>
                    <h4 className="font-bold text-sm text-white">In-House Legal Advisory &amp; Tenancy Conveyancing</h4>
                    <p className="text-slate-300 mt-0.5 leading-relaxed">
                      Our legal team drafts Sales &amp; Purchase Agreements (SPA), standard and corporate lease contracts, and facilitates deed screening.
                    </p>
                  </div>
                </div>
              </div>

              <div className="p-4 bg-[#18181b] border border-zinc-800 rounded-2xl text-xs space-y-1.5 text-slate-300">
                <div className="flex justify-between">
                  <span>Upfront Listing Fee:</span>
                  <strong className="text-[#FFE259] font-extrabold">LKR 0 (Free to List)</strong>
                </div>
                <div className="flex justify-between">
                  <span>Average Time to Close:</span>
                  <strong className="text-white font-extrabold">30–45 Days</strong>
                </div>
              </div>
            </div>

          </div>

        </div>
      )}

    </div>
  );
}

export default function SellPropertyPage() {
  return (
    <Suspense fallback={<div className="p-12 text-center text-slate-500">Loading Seller Portal...</div>}>
      <SellPropertyContent />
    </Suspense>
  );
}