'use client';

import { useEffect, useState } from 'react';
import { X, Plus, Loader2, CheckCircle2, Upload, Building2, Home as HomeIcon, Briefcase, Landmark } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

interface FilterMeta {
  locations:     { id: number; name: string }[];
  propertyTypes: { id: number; display_name: string; name: string }[];
  projects:      { id: number; name: string }[];
  amenities:     { id: number; name: string; category: string }[];
}

interface AdminAddPropertyModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

const INITIAL_FORM = {
  title: '',
  description: '',
  price: '',
  area_sqft: '',
  listing_type: 'sale' as 'sale' | 'rent',
  location_id: '',
  project_id: '',
  completion_status: 'ready' as 'off_plan' | 'under_construction' | 'ready',
  rera_permit_number: '',
  amenities: [] as number[],
  // Conditional fields
  bedrooms: '',
  bathrooms: '',
  kitchen_type: 'open' as 'open' | 'closed',
  has_balcony: false,
  conference_rooms: '',
  parking_spots: '0',
  it_server_room: false,
  office_furnished: 'shell_core' as 'shell_core' | 'fully_furnished',
  plot_area_sqft: '',
  garden_size_sqft: '',
  has_pool: false,
};

type ListingTypeOption = 'Villa' | 'Home' | 'Office' | 'Apartment';

export function AdminAddPropertyModal({ open, onClose, onSuccess }: AdminAddPropertyModalProps) {
  const [selectedChoice, setSelectedChoice] = useState<ListingTypeOption | null>(null);
  const [form, setForm]       = useState({ ...INITIAL_FORM });
  const [meta, setMeta]       = useState<FilterMeta | null>(null);
  const [step, setStep]       = useState(1); // 1 = type grid selection, 2 = fields, 3 = amenities & submit
  const [saving, setSaving]   = useState(false);
  const [error, setError]     = useState('');
  const [success, setSuccess] = useState(false);
  const [customAmenities, setCustomAmenities] = useState<string[]>([]);
  const [customInputText, setCustomInputText] = useState('');
  const [uploadedImages, setUploadedImages] = useState<string[]>([]);
  const [uploading, setUploading] = useState(false);

  // Load filter metadata
  useEffect(() => {
    if (open && !meta) {
      fetch('/api/meta/filters')
        .then((r) => r.json())
        .then((d) => { if (d.success) setMeta(d.data); })
        .catch(() => {});
    }
  }, [open, meta]);

  // Reset states when opened
  useEffect(() => {
    if (open) {
      setSelectedChoice(null);
      setForm({ ...INITIAL_FORM });
      setStep(1);
      setError('');
      setSuccess(false);
      setCustomAmenities([]);
      setCustomInputText('');
      setUploadedImages([]);
      setUploading(false);
    }
  }, [open]);

  // Close on Escape key press
  useEffect(() => {
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); };
    if (open) window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [open, onClose]);

  const set = (field: keyof typeof INITIAL_FORM, value: any) =>
    setForm((prev) => ({ ...prev, [field]: value }));

  const toggleAmenity = (id: number) =>
    setForm((prev) => ({
      ...prev,
      amenities: prev.amenities.includes(id)
        ? prev.amenities.filter((a) => a !== id)
        : [...prev.amenities, id],
    }));

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setUploading(true);
    setError('');

    try {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        const formData = new FormData();
        formData.append('file', file);

        const res = await fetch('/api/upload', {
          method: 'POST',
          body: formData,
        });

        const data = await res.json();
        if (data.success) {
          setUploadedImages((prev) => [...prev, data.url]);
        } else {
          setError(data.error || 'Failed to upload image');
        }
      }
    } catch (err: any) {
      setError('Error uploading files.');
    } finally {
      setUploading(false);
    }
  };

  const removeImage = (index: number) => {
    setUploadedImages((prev) => prev.filter((_, i) => i !== index));
  };

  const removeCustomAmenity = (name: string) => {
    setCustomAmenities((prev) => prev.filter((n) => n !== name));
  };

  const handleSubmit = async () => {
    setError('');
    setSaving(true);

    try {
      if (!selectedChoice) {
        throw new Error('Please select what you are listing first.');
      }

      // Map dynamic selected choice to properties type
      const typeNameMap: Record<ListingTypeOption, string> = {
        Apartment: 'apartment',
        Villa: 'villa',
        Office: 'office',
        Home: 'townhouse',
      };
      const dbTypeName = typeNameMap[selectedChoice];
      const propertyType = meta?.propertyTypes.find((pt) => pt.name === dbTypeName);

      if (!propertyType) {
        throw new Error(`Property type "${selectedChoice}" not initialized in database metadata.`);
      }

      // Build custom formatted description appending the conditional values
      let finalDescription = form.description;
      let finalFurnishedValue: string | null = null;
      let finalParkingSpots = 0;
      let finalBedrooms: number | null = null;
      let finalBathrooms: number | null = null;
      let finalPlotArea: number | null = null;

      if (selectedChoice === 'Home' || selectedChoice === 'Apartment') {
        finalBedrooms = form.bedrooms ? parseInt(form.bedrooms, 10) : null;
        finalBathrooms = form.bathrooms ? parseFloat(form.bathrooms) : null;
        finalDescription += `\n\n[Specs & Details]\n- Kitchen Type: ${form.kitchen_type === 'open' ? 'Open Kitchen' : 'Closed Kitchen'}\n- Balcony: ${form.has_balcony ? 'Yes' : 'No'}`;
      } else if (selectedChoice === 'Office') {
        finalParkingSpots = form.parking_spots ? parseInt(form.parking_spots, 10) : 0;
        finalFurnishedValue = form.office_furnished === 'fully_furnished' ? 'fully_furnished' : 'unfurnished';
        finalDescription += `\n\n[Commercial Specs]\n- Conference Rooms: ${form.conference_rooms || 'None'}\n- IT/Server Room Infrastructure: ${form.it_server_room ? 'Available' : 'Not Available'}\n- Fitout Status: ${form.office_furnished === 'fully_furnished' ? 'Fully Furnished' : 'Shell & Core'}`;
      } else if (selectedChoice === 'Villa') {
        finalBedrooms = form.bedrooms ? parseInt(form.bedrooms, 10) : null;
        finalBathrooms = form.bathrooms ? parseFloat(form.bathrooms) : null;
        finalPlotArea = form.plot_area_sqft ? parseFloat(form.plot_area_sqft) : null;
        finalDescription += `\n\n[Luxury Specs]\n- Plot Area: ${form.plot_area_sqft ? `${Number(form.plot_area_sqft).toLocaleString()} Sq. Ft.` : '—'}\n- Private Garden Size: ${form.garden_size_sqft ? `${Number(form.garden_size_sqft).toLocaleString()} Sq. Ft.` : 'No Garden'}\n- Private Swimming Pool: ${form.has_pool ? 'Yes' : 'No'}`;
      }

      const payload = {
        title: form.title,
        description: finalDescription,
        price: parseFloat(form.price),
        bedrooms: finalBedrooms,
        bathrooms: finalBathrooms,
        area_sqft: form.area_sqft ? parseFloat(form.area_sqft) : null,
        listing_type: form.listing_type,
        property_type_id: propertyType.id,
        location_id: parseInt(form.location_id, 10),
        project_id: form.project_id ? parseInt(form.project_id, 10) : null,
        completion_status: form.completion_status,
        furnished: finalFurnishedValue,
        rera_permit_number: form.rera_permit_number || null,
        amenities_json: [...form.amenities, ...customAmenities],
        images_json: uploadedImages,
        parking_spots: finalParkingSpots,
        plot_area_sqft: finalPlotArea,
      };

      const res = await fetch('/api/properties', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        setError(data.error || 'Failed to publish new property listing.');
        return;
      }

      setSuccess(true);
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1500);
    } catch (e: any) {
      setError(e.message || 'An unexpected connection error occurred.');
    } finally {
      setSaving(false);
    }
  };

  const inputCls = 'w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm text-[#0d1c32] focus:outline-none focus:border-[#C5A880] transition-colors bg-white';
  const labelCls = 'block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5';

  return (
    <AnimatePresence>
      {open && (
        <>
          {/* Backdrop overlay */}
          <motion.div
            initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
            onClick={onClose}
            className="fixed inset-0 z-50 bg-[#0d1c32]/60 backdrop-blur-sm"
          />

          {/* Modal card container */}
          <motion.div
            initial={{ opacity: 0, scale: 0.95, y: 24 }}
            animate={{ opacity: 1, scale: 1, y: 0, transition: { type: 'spring', stiffness: 300, damping: 28 } }}
            exit={{ opacity: 0, scale: 0.97, y: 12, transition: { duration: 0.15 } }}
            className="fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none"
          >
            <div
              onClick={(e) => e.stopPropagation()}
              className="pointer-events-auto bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col"
            >
              {/* Header section */}
              <div className="bg-[#0d1c32] px-6 py-4 flex items-center justify-between shrink-0">
                <div>
                  <h2 className="font-serif text-lg font-bold text-white">Add New Property (Admin Portal)</h2>
                  <p className="text-[10px] text-[#C5A880] uppercase tracking-widest mt-0.5 font-semibold">
                    Step {step} of 3 — {step === 1 ? 'Select Category' : step === 2 ? 'Details & Specs' : 'Amenities & Confirm'}
                  </p>
                </div>
                <button onClick={onClose} className="text-white/50 hover:text-white transition-colors">
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Progress Bar indicator */}
              <div className="flex h-1 shrink-0">
                {[1, 2, 3].map((s) => (
                  <div
                    key={s}
                    className={`flex-1 transition-colors duration-300 ${s <= step ? 'bg-[#C5A880]' : 'bg-gray-100'}`}
                  />
                ))}
              </div>

              {/* Modal scrollable body */}
              <div className="flex-grow overflow-y-auto p-6">
                {success ? (
                  <div className="flex flex-col items-center justify-center py-16 gap-3">
                    <CheckCircle2 className="w-12 h-12 text-emerald-500" />
                    <p className="font-bold text-[#0d1c32] text-lg">Property Published!</p>
                    <p className="text-sm text-gray-400">The listing has been created and verified instantly.</p>
                  </div>
                ) : (
                  <>
                    {error && (
                      <div className="mb-4 p-3 bg-red-50 border border-red-100 rounded-lg text-red-600 text-xs font-semibold">
                        {error}
                      </div>
                    )}

                    {/* ── STEP 1: Selection Grid ── */}
                    {step === 1 && (
                      <div className="space-y-6">
                        <div className="text-center py-2">
                          <h3 className="font-serif text-xl font-bold text-[#0d1c32]">What are you listing?</h3>
                          <p className="text-xs text-gray-400 mt-1">Choose a category to display custom real estate details</p>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                          {([
                            { type: 'Apartment', desc: 'Suites, flats, or penthouses', icon: Landmark },
                            { type: 'Villa',     desc: 'Private houses with private yards', icon: Building2 },
                            { type: 'Office',    desc: 'Commercial corporate spaces', icon: Briefcase },
                            { type: 'Home',      desc: 'Townhouses or semi-detached layouts', icon: HomeIcon },
                          ] as { type: ListingTypeOption; desc: string; icon: any }[]).map((opt) => {
                            const Icon = opt.icon;
                            const isSelected = selectedChoice === opt.type;
                            return (
                              <button
                                key={opt.type}
                                type="button"
                                onClick={() => setSelectedChoice(opt.type)}
                                className={`p-5 rounded-xl border text-left flex items-start gap-4 transition-all duration-200
                                  ${isSelected
                                    ? 'bg-[#0d1c32]/5 border-[#C5A880] ring-1 ring-[#C5A880]/30 shadow-md'
                                    : 'bg-white border-gray-100 hover:border-gray-300 hover:bg-gray-50/50'
                                  }`}
                              >
                                <span className={`p-3 rounded-lg ${isSelected ? 'bg-[#0d1c32] text-white' : 'bg-gray-50 text-gray-500'}`}>
                                  <Icon className="w-5 h-5" />
                                </span>
                                <div>
                                  <p className="font-bold text-[#0d1c32] text-sm">{opt.type}</p>
                                  <p className="text-[10px] text-gray-400 mt-1 font-medium">{opt.desc}</p>
                                </div>
                              </button>
                            );
                          })}
                        </div>
                      </div>
                    )}

                    {/* ── STEP 2: General & Custom Fields ── */}
                    {step === 2 && (
                      <div className="space-y-5">
                        <div className="bg-[#0d1c32]/5 rounded-xl p-3 border border-[#0d1c32]/10 mb-4 flex items-center justify-between">
                          <p className="text-xs text-[#0d1c32] font-bold">Category: <span className="text-[#C5A880] font-serif text-sm">{selectedChoice}</span></p>
                          <button onClick={() => setStep(1)} className="text-[9px] font-bold text-gray-500 uppercase tracking-wider hover:underline">Change Category</button>
                        </div>

                        {/* Common Fields */}
                        <div className="grid grid-cols-2 gap-4">
                          <div className="col-span-2">
                            <label className={labelCls}>Property Title *</label>
                            <input
                              type="text"
                              value={form.title}
                              onChange={(e) => set('title', e.target.value)}
                              placeholder="e.g. Ultra Luxury Villa at Palm Jumeirah"
                              className={inputCls}
                            />
                          </div>

                          <div className="col-span-2">
                            <label className={labelCls}>Description</label>
                            <textarea
                              value={form.description}
                              onChange={(e) => set('description', e.target.value)}
                              rows={3}
                              placeholder="Enter premium description details..."
                              className={`${inputCls} resize-none`}
                            />
                          </div>

                          <div>
                            <label className={labelCls}>Price (AED) *</label>
                            <input
                              type="number"
                              value={form.price}
                              onChange={(e) => set('price', e.target.value)}
                              placeholder="e.g. 5000000"
                              min="0"
                              className={inputCls}
                            />
                          </div>

                          <div>
                            <label className={labelCls}>Listing Type *</label>
                            <select
                              value={form.listing_type}
                              onChange={(e) => set('listing_type', e.target.value as 'sale' | 'rent')}
                              className={inputCls}
                            >
                              <option value="sale">For Sale</option>
                              <option value="rent">For Rent</option>
                            </select>
                          </div>

                          <div>
                            <label className={labelCls}>Location Area *</label>
                            <select
                              value={form.location_id}
                              onChange={(e) => set('location_id', e.target.value)}
                              className={inputCls}
                            >
                              <option value="">Select Community...</option>
                              {meta?.locations.map((loc) => (
                                <option key={loc.id} value={loc.id}>{loc.name}</option>
                              ))}
                            </select>
                          </div>

                          <div>
                            <label className={labelCls}>Project (Optional)</label>
                            <select
                              value={form.project_id}
                              onChange={(e) => set('project_id', e.target.value)}
                              className={inputCls}
                            >
                              <option value="">Standalone Community</option>
                              {meta?.projects.map((proj) => (
                                <option key={proj.id} value={proj.id}>{proj.name}</option>
                              ))}
                            </select>
                          </div>

                          <div>
                            <label className={labelCls}>Completion Status *</label>
                            <select
                              value={form.completion_status}
                              onChange={(e) => set('completion_status', e.target.value as typeof form.completion_status)}
                              className={inputCls}
                            >
                              <option value="ready">Ready to Move</option>
                              <option value="off_plan">Off-Plan</option>
                              <option value="under_construction">Under Construction</option>
                            </select>
                          </div>

                          <div>
                            <label className={labelCls}>RERA Permit Number</label>
                            <input
                              type="text"
                              value={form.rera_permit_number}
                              onChange={(e) => set('rera_permit_number', e.target.value)}
                              placeholder="e.g. 7123984022"
                              className={inputCls}
                            />
                          </div>

                          <div>
                            <label className={labelCls}>Size (Sq. Ft.)</label>
                            <input
                              type="number"
                              value={form.area_sqft}
                              onChange={(e) => set('area_sqft', e.target.value)}
                              placeholder="e.g. 2400"
                              min="0"
                              className={inputCls}
                            />
                          </div>
                        </div>

                        {/* CONDITIONAL SPECIFIC FIELDS */}
                        <hr className="border-gray-100 my-4" />
                        <h4 className="text-[10px] font-bold text-[#C5A880] uppercase tracking-wider mb-2 font-serif">Category Specific Options</h4>

                        {/* 1. Apartment or Home */}
                        {(selectedChoice === 'Apartment' || selectedChoice === 'Home') && (
                          <div className="grid grid-cols-2 gap-4 bg-gray-50 p-4 rounded-xl border border-gray-100">
                            <div>
                              <label className={labelCls}>Number of Bedrooms</label>
                              <input
                                type="number"
                                value={form.bedrooms}
                                onChange={(e) => set('bedrooms', e.target.value)}
                                placeholder="3"
                                min="0"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Number of Bathrooms</label>
                              <input
                                type="number"
                                value={form.bathrooms}
                                onChange={(e) => set('bathrooms', e.target.value)}
                                placeholder="3.5"
                                min="0"
                                step="0.5"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Kitchen Type</label>
                              <select
                                value={form.kitchen_type}
                                onChange={(e) => set('kitchen_type', e.target.value as 'open' | 'closed')}
                                className={inputCls}
                              >
                                <option value="open">Open Concept</option>
                                <option value="closed">Closed Layout</option>
                              </select>
                            </div>
                            <div className="flex flex-col justify-end pb-1.5">
                              <label htmlFor="has_balcony" className="flex items-center gap-2 cursor-pointer select-none">
                                <input
                                  type="checkbox"
                                  id="has_balcony"
                                  checked={form.has_balcony}
                                  onChange={(e) => set('has_balcony', e.target.checked)}
                                  className="w-4 h-4 accent-[#C5A880]"
                                />
                                <span className="text-xs font-semibold text-[#0d1c32]">Has Balcony / Terrace</span>
                              </label>
                            </div>
                          </div>
                        )}

                        {/* 2. Office (Commercial) */}
                        {selectedChoice === 'Office' && (
                          <div className="grid grid-cols-2 gap-4 bg-gray-50 p-4 rounded-xl border border-gray-100">
                            <div>
                              <label className={labelCls}>Conference Rooms</label>
                              <input
                                type="number"
                                value={form.conference_rooms}
                                onChange={(e) => set('conference_rooms', e.target.value)}
                                placeholder="e.g. 2"
                                min="0"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Available Parking Slots</label>
                              <input
                                type="number"
                                value={form.parking_spots}
                                onChange={(e) => set('parking_spots', e.target.value)}
                                placeholder="3"
                                min="0"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Furnished Status</label>
                              <select
                                value={form.office_furnished}
                                onChange={(e) => set('office_furnished', e.target.value as any)}
                                className={inputCls}
                              >
                                <option value="shell_core">Shell & Core</option>
                                <option value="fully_furnished">Fully Furnished</option>
                              </select>
                            </div>
                            <div className="flex flex-col justify-end pb-1.5">
                              <label htmlFor="it_server_room" className="flex items-center gap-2 cursor-pointer select-none">
                                <input
                                  type="checkbox"
                                  id="it_server_room"
                                  checked={form.it_server_room}
                                  onChange={(e) => set('it_server_room', e.target.checked)}
                                  className="w-4 h-4 accent-[#C5A880]"
                                />
                                <span className="text-xs font-semibold text-[#0d1c32]">Dedicated IT/Server Room</span>
                              </label>
                            </div>
                          </div>
                        )}

                        {/* 3. Villa (Luxury) */}
                        {selectedChoice === 'Villa' && (
                          <div className="grid grid-cols-2 gap-4 bg-gray-50 p-4 rounded-xl border border-gray-100">
                            <div>
                              <label className={labelCls}>Plot Area (Sq. Ft.)</label>
                              <input
                                type="number"
                                value={form.plot_area_sqft}
                                onChange={(e) => set('plot_area_sqft', e.target.value)}
                                placeholder="e.g. 8000"
                                min="0"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Private Garden Size (Sq. Ft.)</label>
                              <input
                                type="number"
                                value={form.garden_size_sqft}
                                onChange={(e) => set('garden_size_sqft', e.target.value)}
                                placeholder="e.g. 1500"
                                min="0"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Number of Bedrooms</label>
                              <input
                                type="number"
                                value={form.bedrooms}
                                onChange={(e) => set('bedrooms', e.target.value)}
                                placeholder="5"
                                min="0"
                                className={inputCls}
                              />
                            </div>
                            <div>
                              <label className={labelCls}>Number of Bathrooms</label>
                              <input
                                type="number"
                                value={form.bathrooms}
                                onChange={(e) => set('bathrooms', e.target.value)}
                                placeholder="5.5"
                                min="0"
                                step="0.5"
                                className={inputCls}
                              />
                            </div>
                            <div className="col-span-2 py-1">
                              <label htmlFor="has_pool" className="flex items-center gap-2 cursor-pointer select-none">
                                <input
                                  type="checkbox"
                                  id="has_pool"
                                  checked={form.has_pool}
                                  onChange={(e) => set('has_pool', e.target.checked)}
                                  className="w-4 h-4 accent-[#C5A880]"
                                />
                                <span className="text-xs font-semibold text-[#0d1c32]">Private Swimming Pool Included</span>
                              </label>
                            </div>
                          </div>
                        )}
                      </div>
                    )}

                    {/* ── STEP 3: Amenities Selection ── */}
                    {step === 3 && (
                      <div className="space-y-5">
                        <p className="text-xs text-gray-500 font-medium">Select all listing amenities applicable for this property community:</p>
                        {meta && Object.entries(
                          meta.amenities.reduce((acc, am) => {
                            if (!acc[am.category]) acc[am.category] = [];
                            acc[am.category].push(am);
                            return acc;
                          }, {} as Record<string, typeof meta.amenities>)
                        ).map(([catName, list]) => (
                          <div key={catName}>
                            <p className="text-[9px] font-bold text-gray-400 uppercase tracking-widest mb-2 font-serif capitalize">
                              {catName}
                            </p>
                            <div className="flex flex-wrap gap-2">
                              {list.map((am) => (
                                <button
                                  key={am.id}
                                  type="button"
                                  onClick={() => toggleAmenity(am.id)}
                                  className={`px-3 py-1.5 rounded-full text-[10px] font-semibold border transition-all ${
                                    form.amenities.includes(am.id)
                                      ? 'bg-[#0d1c32] text-white border-[#0d1c32]'
                                      : 'bg-white text-gray-500 border-gray-200 hover:border-[#C5A880]'
                                  }`}
                                >
                                  {am.name}
                                </button>
                              ))}
                            </div>
                          </div>
                        ))}

                        {/* Custom Amenities Input */}
                        <div className="pt-3 border-t border-gray-100">
                          <label className={labelCls}>Add Custom Amenities/Features</label>
                          <div className="flex gap-2">
                            <input
                              type="text"
                              value={customInputText}
                              onChange={(e) => setCustomInputText(e.target.value)}
                              placeholder="e.g. WiFi, Dedicated Parking, Private Elevator"
                              className={`${inputCls} flex-grow`}
                              onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                  e.preventDefault();
                                  const val = customInputText.trim();
                                  if (val && !customAmenities.includes(val)) {
                                    setCustomAmenities((prev) => [...prev, val]);
                                    setCustomInputText('');
                                  }
                                }
                              }}
                            />
                            <button
                              type="button"
                              onClick={() => {
                                const val = customInputText.trim();
                                if (val && !customAmenities.includes(val)) {
                                  setCustomAmenities((prev) => [...prev, val]);
                                  setCustomInputText('');
                                }
                              }}
                              className="px-4 bg-[#0d1c32] hover:bg-[#C5A880] text-white hover:text-[#0d1c32] rounded-lg text-[10px] font-bold uppercase transition-colors shrink-0"
                            >
                              Add
                            </button>
                          </div>
                          
                          {/* Custom Amenity Tags */}
                          {customAmenities.length > 0 && (
                            <div className="flex flex-wrap gap-1.5 mt-2">
                              {customAmenities.map((name) => (
                                <span
                                  key={name}
                                  className="flex items-center gap-1 px-2.5 py-1 bg-amber-50 border border-amber-200 text-amber-900 rounded-full text-[9px] font-bold"
                                >
                                  {name}
                                  <button
                                    type="button"
                                    onClick={() => removeCustomAmenity(name)}
                                    className="text-amber-600 hover:text-amber-900 transition-colors"
                                  >
                                    <X className="w-2.5 h-2.5" />
                                  </button>
                                </span>
                              ))}
                            </div>
                          )}
                        </div>

                        {/* Image Upload UI */}
                        <div className="mt-4">
                          <label className={labelCls}>Property Media Upload</label>
                          
                          {/* Thumbnail Grid */}
                          {uploadedImages.length > 0 && (
                            <div className="grid grid-cols-4 gap-2 mb-3">
                              {uploadedImages.map((url, idx) => (
                                <div key={idx} className="relative aspect-video rounded-lg overflow-hidden border border-gray-100 group">
                                  <img src={url} alt={`Upload ${idx}`} className="w-full h-full object-cover" />
                                  <button
                                    type="button"
                                    onClick={() => removeImage(idx)}
                                    className="absolute top-1 right-1 p-1 bg-red-600 text-white rounded-full opacity-0 group-hover:opacity-100 transition-opacity"
                                  >
                                    <X className="w-2.5 h-2.5" />
                                  </button>
                                </div>
                              ))}
                            </div>
                          )}

                          <label className="border-2 border-dashed border-gray-200 rounded-xl p-5 text-center bg-gray-50/50 hover:border-[#C5A880] transition-colors cursor-pointer flex flex-col items-center justify-center">
                            <input
                              type="file"
                              multiple
                              accept="image/*"
                              onChange={handleImageUpload}
                              className="hidden"
                              disabled={uploading}
                            />
                            {uploading ? (
                              <>
                                <Loader2 className="w-5 h-5 text-[#C5A880] animate-spin mb-1.5" />
                                <p className="text-xs text-gray-500 font-semibold">Uploading images...</p>
                              </>
                            ) : (
                              <>
                                <Upload className="w-5 h-5 text-gray-400 mb-1.5" />
                                <p className="text-xs text-gray-500 font-semibold">Image Attachment Portal</p>
                                <p className="text-[9px] text-gray-400 mt-0.5">Click to choose image attachments (saves natively)</p>
                              </>
                            )}
                          </label>
                        </div>
                      </div>
                    )}
                  </>
                )}
              </div>

              {/* Action Buttons footer */}
              {!success && (
                <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-between shrink-0 bg-gray-50">
                  <button
                    onClick={() => step > 1 ? setStep(step - 1) : onClose()}
                    className="px-4 py-2 text-xs font-bold text-gray-500 uppercase tracking-wider hover:text-[#0d1c32] transition-colors"
                  >
                    {step > 1 ? '← Back' : 'Cancel'}
                  </button>

                  {step === 1 ? (
                    <button
                      onClick={() => {
                        if (!selectedChoice) {
                          setError('Please select a property category type.');
                          return;
                        }
                        setError('');
                        setStep(2);
                      }}
                      className="px-6 py-2 bg-[#0d1c32] text-white text-xs font-bold uppercase tracking-wider rounded-lg hover:bg-[#C5A880] hover:text-[#0d1c32] transition-all"
                    >
                      Next Step →
                    </button>
                  ) : step === 2 ? (
                    <button
                      onClick={() => {
                        if (!form.title || !form.price || !form.location_id || !form.completion_status) {
                          setError('Please fill in all mandatory fields: Title, Price, Location Area, Status.');
                          return;
                        }
                        setError('');
                        setStep(3);
                      }}
                      className="px-6 py-2 bg-[#0d1c32] text-white text-xs font-bold uppercase tracking-wider rounded-lg hover:bg-[#C5A880] hover:text-[#0d1c32] transition-all"
                    >
                      Next Step →
                    </button>
                  ) : (
                    <button
                      onClick={handleSubmit}
                      disabled={saving}
                      className="flex items-center gap-2 px-6 py-2 bg-[#C5A880] text-[#0d1c32] text-xs font-bold uppercase tracking-wider rounded-lg hover:bg-[#b89c74] transition-all disabled:opacity-50"
                    >
                      {saving ? (
                        <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Saving...</>
                      ) : (
                        <><Plus className="w-3.5 h-3.5" /> Publish Listing</>
                      )}
                    </button>
                  )}
                </div>
              )}
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
