'use client';

import { useEffect, useState } from 'react';
import { X, Plus, Loader2, CheckCircle2, Upload, Building2, HelpCircle, Layers, Layout, DollarSign, Sparkles, AlertCircle, Calendar } from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';

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

interface AddPropertyModalProps {
  open: boolean;
  onClose: () => void;
  onSuccess: (id: number, slug: string) => void;
}

const INITIAL_FORM = {
  title: '',
  description: '',
  price: '',
  bedrooms: '',
  bathrooms: '',
  area_sqft: '',
  listing_type: 'sale' as 'sale' | 'rent' | 'installment',
  property_type_id: '',
  location_id: '',
  project_id: '',
  completion_status: 'Ready' as 'Ready' | 'Off-Plan',
  furnished: '' as '' | 'unfurnished' | 'semi_furnished' | 'fully_furnished',
  floor_number: '',
  parking_spots: '0',
  rera_permit_number: '',
  payment_plan_available: false,
  down_payment_percent: '',
  amenities: [] as number[],
  // Premium custom inputs:
  floor_level: '',
  furnishing: '' as '' | 'Furnished' | 'Unfurnished' | 'Partly',
  maids_room: false,
  private_pool: false,
  plot_size: '',
  bua: '',
  parking_spaces: '0',
  permit_number: '',
};

export function AddPropertyModal({ open, onClose, onSuccess }: AddPropertyModalProps) {
  const [form, setForm]       = useState({ ...INITIAL_FORM });
  const [meta, setMeta]       = useState<FilterMeta | null>(null);
  const [step, setStep]       = useState(1); // 1=basics category choice, 2=details, 3=amenities & submit
  const [saving, setSaving]   = useState(false);
  const [error, setError]     = useState('');
  const [limitError, setLimitError] = useState('');
  const [checkingLimits, setCheckingLimits] = useState(false);
  const [success, setSuccess] = useState(false);
  const [selectedTypeCategory, setSelectedTypeCategory] = useState<string>('');
  const [uploadedImages, setUploadedImages] = useState<string[]>([]);
  const [uploading, setUploading] = useState(false);

  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));
  };

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

  // Reset on open
  useEffect(() => {
    if (open) {
      setForm({ ...INITIAL_FORM });
      setStep(1);
      setError('');
      setLimitError('');
      setSuccess(false);
      setSelectedTypeCategory('');
      setUploadedImages([]);
      setUploading(false);
    }
  }, [open]);

  // Close on Escape
  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 validateLimitsAndNext = async () => {
    if (!form.property_type_id || !form.listing_type) {
      setError('Please select both a property type category and a listing term.');
      return;
    }
    setError('');
    setLimitError('');
    setCheckingLimits(true);

    try {
      const res = await fetch('/api/properties/check-limits');
      const data = await res.json();
      
      if (!res.ok || !data.success) {
        setError(data.error || 'Failed to check listing limits.');
        return;
      }

      if (data.limitReached) {
        setLimitError(data.error || 'You have reached your active listing limit. Please upgrade.');
      } else {
        setStep(2);
      }
    } catch (err: any) {
      setError('Network error while validating active listing limits.');
    } finally {
      setCheckingLimits(false);
    }
  };

  const handleSubmit = async () => {
    setError('');
    setSaving(true);
    try {
      const payload = {
        ...form,
        price:            parseFloat(form.price),
        bedrooms:         form.bedrooms         ? parseInt(form.bedrooms, 10)         : null,
        bathrooms:        form.bathrooms        ? parseFloat(form.bathrooms)          : null,
        area_sqft:        form.area_sqft        ? parseFloat(form.area_sqft)          : null,
        property_type_id: parseInt(form.property_type_id, 10),
        location_id:      parseInt(form.location_id, 10),
        project_id:       form.project_id       ? parseInt(form.project_id, 10)       : null,
        floor_number:     form.floor_number     ? parseInt(form.floor_number, 10)     : null,
        parking_spots:    parseInt(form.parking_spots, 10),
        down_payment_percent: form.down_payment_percent ? parseFloat(form.down_payment_percent) : null,
        amenities_json:   form.amenities,
        images_json:      uploadedImages,
        furnished:        form.furnished || null,
        // Premium custom fields
        floor_level:      form.floor_level || null,
        furnishing:       form.furnishing || null,
        maids_room:       form.maids_room ? 1 : 0,
        private_pool:     form.private_pool ? 1 : 0,
        plot_size:        form.plot_size ? parseInt(form.plot_size, 10) : null,
        bua:              form.bua ? parseInt(form.bua, 10) : null,
        parking_spaces:   parseInt(form.parking_spaces || '0', 10),
        permit_number:    form.permit_number || null,
      };

      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 create property');
        return;
      }

      setSuccess(true);
      setTimeout(() => {
        onSuccess(data.data.id, data.data.slug);
        onClose();
      }, 1500);
    } catch (e: any) {
      setError(e.message || 'Network error');
    } finally {
      setSaving(false);
    }
  };

  const inputCls = 'w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm text-black font-semibold 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 */}
          <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 */}
          <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 */}
              <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</h2>
                  <p className="text-[10px] text-[#C5A880] uppercase tracking-widest mt-0.5">
                    Step {step} of 3 — {step === 1 ? 'Structural Selection' : step === 2 ? 'Listing Details' : 'Amenities & Submit'}
                  </p>
                </div>
                <button onClick={onClose} className="text-white/50 hover:text-white transition-colors">
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Step progress */}
              <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>

              {/* Body */}
              <div className="flex-grow overflow-y-auto p-6">
                {success ? (
                  <div className="flex flex-col items-center justify-center py-12 gap-3">
                    <CheckCircle2 className="w-12 h-12 text-emerald-500" />
                    <p className="font-bold text-[#0d1c32] text-lg">Property Listed!</p>
                    <p className="text-sm text-gray-400">Redirecting to your dashboard...</p>
                  </div>
                ) : (
                  <>
                    {error && (
                      <div className="mb-4 p-3 bg-red-50 border border-red-100 rounded-lg text-red-600 text-xs">
                        {error}
                      </div>
                    )}

                    {/* ── STEP 1: Structural Questionnaire ── */}
                    {step === 1 && (
                      <div className="space-y-6">
                        {limitError ? (
                          <div className="p-5 bg-red-50 border border-red-100 rounded-xl flex flex-col gap-3 animate-fade-in">
                            <div className="flex items-start gap-3">
                              <AlertCircle className="w-5 h-5 text-red-600 shrink-0 mt-0.5" />
                              <div>
                                <h4 className="font-serif font-bold text-red-900 text-sm">Listing Limit Restrained</h4>
                                <p className="text-xs text-red-700/80 mt-1 leading-normal">
                                  {limitError}
                                </p>
                              </div>
                            </div>
                            <div className="flex gap-2 justify-end mt-2">
                              <a
                                href="/pricing"
                                onClick={onClose}
                                className="px-4 py-2 bg-[#0d1c32] text-white text-[10px] font-bold uppercase tracking-wider rounded-lg hover:bg-[#C5A880] hover:text-[#0d1c32] transition-all"
                              >
                                Upgrade Package
                              </a>
                            </div>
                          </div>
                        ) : (
                          <>
                            {/* Property Type Category selection cards */}
                            <div className="space-y-3">
                              <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Property Type Category *</p>
                              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                {[
                                  { id: 'Apartment', dbId: '1', label: 'Apartment', desc: 'Flat, Studio, Penthouse', icon: <Layers className="w-5 h-5" /> },
                                  { id: 'Villa', dbId: '2', label: 'Villa', desc: 'Villa, Townhouse, Compound', icon: <Building2 className="w-5 h-5" /> },
                                  { id: 'Commercial', dbId: '10', label: 'Commercial', desc: 'Retail, Building, Warehouse', icon: <Layout className="w-5 h-5" /> },
                                  { id: 'Office', dbId: '6', label: 'Office', desc: 'Office Space, Workspace', icon: <HelpCircle className="w-5 h-5" /> },
                                ].map((item) => (
                                  <button
                                    key={item.id}
                                    type="button"
                                    onClick={() => {
                                      set('property_type_id', item.dbId);
                                      setSelectedTypeCategory(item.id);
                                    }}
                                    className={`p-4 rounded-xl border text-left transition-all flex flex-col justify-between min-h-[100px] ${
                                      form.property_type_id === item.dbId
                                        ? 'border-[#C5A880] bg-[#C5A880]/5 text-[#0d1c32] shadow-sm'
                                        : 'border-gray-200 bg-white text-gray-500 hover:border-[#C5A880] hover:text-[#0d1c32]'
                                    }`}
                                  >
                                    <div className={`p-1.5 rounded-lg shrink-0 w-fit ${form.property_type_id === item.dbId ? 'bg-[#0d1c32] text-white' : 'bg-gray-50 text-gray-400'}`}>
                                      {item.icon}
                                    </div>
                                    <div className="mt-2">
                                      <p className="text-xs font-bold uppercase tracking-wider text-black">{item.label}</p>
                                      <p className="text-[10px] text-gray-400 mt-0.5 leading-none">{item.desc}</p>
                                    </div>
                                  </button>
                                ))}
                              </div>
                            </div>

                            {/* Listing Type selection cards */}
                            <div className="space-y-3 mt-6">
                              <p className="text-xs font-bold text-gray-400 uppercase tracking-wider">Listing Term *</p>
                              <div className="grid grid-cols-3 gap-3">
                                {[
                                  { id: 'sale', label: 'For Sale', desc: 'Immediate purchase', icon: <DollarSign className="w-4 h-4" /> },
                                  { id: 'rent', label: 'For Rent', desc: 'Monthly or yearly lease', icon: <Calendar className="w-4 h-4" /> },
                                  { id: 'installment', label: 'Installment', desc: 'Flexible payment plan', icon: <Sparkles className="w-4 h-4" /> },
                                ].map((item) => (
                                  <button
                                    key={item.id}
                                    type="button"
                                    onClick={() => set('listing_type', item.id as any)}
                                    className={`p-4 rounded-xl border text-left transition-all flex flex-col justify-between min-h-[90px] ${
                                      form.listing_type === item.id
                                        ? 'border-[#C5A880] bg-[#C5A880]/5 text-[#0d1c32] shadow-sm'
                                        : 'border-gray-200 bg-white text-gray-500 hover:border-[#C5A880] hover:text-[#0d1c32]'
                                    }`}
                                  >
                                    <div className={`p-1.5 rounded-lg shrink-0 w-fit ${form.listing_type === item.id ? 'bg-[#0d1c32] text-white' : 'bg-gray-50 text-gray-400'}`}>
                                      {item.icon}
                                    </div>
                                    <div className="mt-2">
                                      <p className="text-xs font-bold uppercase tracking-wider text-black">{item.label}</p>
                                      <p className="text-[9px] text-gray-400 mt-0.5 leading-none">{item.desc}</p>
                                    </div>
                                  </button>
                                ))}
                              </div>
                            </div>
                          </>
                        )}
                      </div>
                    )}

                    {/* ── STEP 2: Listing Details (Dynamic Rendering) ── */}
                    {step === 2 && (
                      <div className="space-y-4">
                        {/* Basic Specs */}
                        <div>
                          <label className={labelCls}>Property Title *</label>
                          <input
                            type="text"
                            value={form.title}
                            onChange={(e) => set('title', e.target.value)}
                            placeholder="e.g. Luxury 3BR Villa in Palm Jumeirah"
                            className={inputCls}
                          />
                        </div>

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

                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <label className={labelCls}>Price (AED) *</label>
                            <input
                              type="number"
                              value={form.price}
                              onChange={(e) => set('price', e.target.value)}
                              placeholder="2500000"
                              min="0"
                              className={inputCls}
                            />
                          </div>
                          <div>
                            <label className={labelCls}>Location *</label>
                            <select
                              value={form.location_id}
                              onChange={(e) => set('location_id', e.target.value)}
                              className={inputCls}
                            >
                              <option value="" className="text-gray-300">Select location...</option>
                              {meta?.locations.map((l) => (
                                <option key={l.id} value={l.id} className="text-black">{l.name}</option>
                              ))}
                            </select>
                          </div>
                        </div>

                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <label className={labelCls}>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}>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}>Area (sqft)</label>
                            <input
                              type="number"
                              value={form.area_sqft}
                              onChange={(e) => set('area_sqft', e.target.value)}
                              placeholder="1500"
                              min="0"
                              className={inputCls}
                            />
                          </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <label className={labelCls}>Completion Status *</label>
                            <select
                              value={form.completion_status}
                              onChange={(e) => set('completion_status', e.target.value as any)}
                              className={inputCls}
                            >
                              <option value="Ready" className="text-black">Ready</option>
                              <option value="Off-Plan" className="text-black">Off-Plan</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="" className="text-gray-300">Standalone / No project</option>
                              {meta?.projects.map((p) => (
                                <option key={p.id} value={p.id} className="text-black">{p.name}</option>
                              ))}
                            </select>
                          </div>
                        </div>

                        {/* DYNAMIC LAYOUT GRID 1: VILLA EXCLUSIVES */}
                        {selectedTypeCategory === 'Villa' && (
                          <div className="p-4 bg-amber-50/50 border border-amber-100 rounded-xl space-y-4">
                            <h3 className="text-xs font-bold text-amber-800 uppercase tracking-wider">Villa Specifications</h3>
                            <div className="grid grid-cols-2 gap-4">
                              <div>
                                <label className={labelCls}>Plot Size (sqft)</label>
                                <input
                                  type="number"
                                  value={form.plot_size}
                                  onChange={(e) => set('plot_size', e.target.value)}
                                  placeholder="e.g. 6000"
                                  className={inputCls}
                                />
                              </div>
                              <div>
                                <label className={labelCls}>BUA (Built-up Area, sqft)</label>
                                <input
                                  type="number"
                                  value={form.bua}
                                  onChange={(e) => set('bua', e.target.value)}
                                  placeholder="e.g. 4500"
                                  className={inputCls}
                                />
                              </div>
                            </div>
                            <div className="grid grid-cols-1 gap-4">
                              <div>
                                <label className={labelCls}>Parking Spaces</label>
                                <input
                                  type="number"
                                  value={form.parking_spaces}
                                  onChange={(e) => set('parking_spaces', e.target.value)}
                                  placeholder="e.g. 2"
                                  min="0"
                                  className={inputCls}
                                />
                              </div>
                            </div>
                            <div className="flex gap-6 mt-2">
                              <label className="flex items-center gap-2 text-xs font-bold text-[#0d1c32] cursor-pointer">
                                <input
                                  type="checkbox"
                                  checked={form.maids_room}
                                  onChange={(e) => set('maids_room', e.target.checked)}
                                  className="w-4 h-4 rounded border-gray-300 accent-[#C5A880] focus:ring-0"
                                />
                                Maids Room Included
                              </label>
                              <label className="flex items-center gap-2 text-xs font-bold text-[#0d1c32] cursor-pointer">
                                <input
                                  type="checkbox"
                                  checked={form.private_pool}
                                  onChange={(e) => set('private_pool', e.target.checked)}
                                  className="w-4 h-4 rounded border-gray-300 accent-[#C5A880] focus:ring-0"
                                />
                                Private Pool Included
                              </label>
                            </div>
                          </div>
                        )}

                        {/* DYNAMIC LAYOUT GRID 2: APARTMENT EXCLUSIVES */}
                        {selectedTypeCategory === 'Apartment' && (
                          <div className="p-4 bg-blue-50/50 border border-blue-100 rounded-xl space-y-4">
                            <h3 className="text-xs font-bold text-blue-800 uppercase tracking-wider">Apartment Specifications</h3>
                            <div className="grid grid-cols-2 gap-4">
                              <div>
                                <label className={labelCls}>Floor Level</label>
                                <input
                                  type="text"
                                  value={form.floor_level}
                                  onChange={(e) => set('floor_level', e.target.value)}
                                  placeholder="e.g. Ground Floor, Penthouse, High Floor"
                                  className={inputCls}
                                />
                              </div>
                              <div>
                                <label className={labelCls}>Furnishing Status</label>
                                <select
                                  value={form.furnishing}
                                  onChange={(e) => set('furnishing', e.target.value)}
                                  className={inputCls}
                                >
                                  <option value="" className="text-gray-300">Select option...</option>
                                  <option value="Furnished" className="text-black">Furnished</option>
                                  <option value="Unfurnished" className="text-black">Unfurnished</option>
                                  <option value="Partly" className="text-black">Partly</option>
                                </select>
                              </div>
                            </div>
                            <div>
                              <label className={labelCls}>ADM / RERA Permit Number</label>
                              <input
                                  type="text"
                                  value={form.permit_number}
                                  onChange={(e) => set('permit_number', e.target.value)}
                                  placeholder="e.g. ADM-UNIT-2024-XXX"
                                  className={inputCls}
                                />
                            </div>
                          </div>
                        )}

                        {/* Payment Plan Options */}
                        {form.completion_status === 'Off-Plan' && (
                          <div className="p-4 bg-sky-50 border border-sky-100 rounded-xl space-y-3">
                            <div className="flex items-center gap-2">
                              <input
                                type="checkbox"
                                id="payment_plan"
                                checked={form.payment_plan_available}
                                onChange={(e) => set('payment_plan_available', e.target.checked)}
                                className="w-4 h-4 accent-[#C5A880]"
                              />
                              <label htmlFor="payment_plan" className="text-xs font-semibold text-[#0d1c32]">
                                Payment Plan Available
                              </label>
                            </div>
                            {form.payment_plan_available && (
                              <div>
                                <label className={labelCls}>Down Payment %</label>
                                <input
                                  type="number"
                                  value={form.down_payment_percent}
                                  onChange={(e) => set('down_payment_percent', e.target.value)}
                                  placeholder="20"
                                  min="0"
                                  max="100"
                                  className={inputCls}
                                />
                              </div>
                            )}
                          </div>
                        )}
                      </div>
                    )}

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

              {/* 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={validateLimitsAndNext}
                      disabled={checkingLimits}
                      className="flex items-center gap-2 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 disabled:opacity-50"
                    >
                      {checkingLimits ? (
                        <><Loader2 className="w-3.5 h-3.5 animate-spin" /> Checking limits...</>
                      ) : (
                        <>Next →</>
                      )}
                    </button>
                  ) : step === 2 ? (
                    <button
                      onClick={() => {
                        // Validate step 2 basic required fields
                        if (!form.title || !form.price || !form.location_id) {
                          setError('Please fill in all required fields (Title, Price, Location)');
                          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 →
                    </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>
  );
}
