'use client';

import { useEffect, useState } from 'react';
import { X, Loader2, CheckCircle2 } 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 }[];
}

interface EditPropertyModalProps {
  property: any | null;
  onClose: () => void;
  onSuccess: () => void;
}

export function EditPropertyModal({ property, onClose, onSuccess }: EditPropertyModalProps) {
  const [form, setForm] = useState({
    title: '',
    description: '',
    price: '',
    area_sqft: '',
    listing_type: 'sale' as 'sale' | 'rent' | 'installment',
    location_id: '',
    project_id: '',
    completion_status: 'Ready' as 'Ready' | 'Off-Plan',
    rera_permit_number: '',
    // Premium dynamic fields
    floor_level: '',
    furnishing: 'Unfurnished' as 'Furnished' | 'Unfurnished' | 'Partly',
    maids_room: false,
    private_pool: false,
    plot_size: '',
    bua: '',
    parking_spaces: '0',
    permit_number: '',
  });

  const [meta, setMeta] = useState<FilterMeta | null>(null);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

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

  useEffect(() => {
    if (property) {
      setForm({
        title: property.title ?? '',
        description: property.description ?? '',
        price: property.price?.toString() ?? '',
        area_sqft: property.area_sqft?.toString() ?? '',
        listing_type: (property.listing_type?.toLowerCase() as any) ?? 'sale',
        location_id: property.location_id?.toString() ?? '',
        project_id: property.project_id?.toString() ?? '',
        completion_status: property.completion_status === 'Off-Plan' ? 'Off-Plan' : 'Ready',
        rera_permit_number: property.rera_permit_number ?? '',
        floor_level: property.floor_level ?? '',
        furnishing: property.furnishing ?? 'Unfurnished',
        maids_room: !!property.maids_room,
        private_pool: !!property.private_pool,
        plot_size: property.plot_size?.toString() ?? '',
        bua: property.bua?.toString() ?? '',
        parking_spaces: property.parking_spaces?.toString() ?? '0',
        permit_number: property.permit_number ?? '',
      });
      setError('');
      setSuccess(false);
    }
  }, [property]);

  if (!property) return null;

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setSaving(true);

    try {
      const payload = {
        title: form.title,
        description: form.description,
        price: parseFloat(form.price),
        area_sqft: form.area_sqft ? parseFloat(form.area_sqft) : null,
        listing_type: form.listing_type,
        location_id: parseInt(form.location_id, 10),
        project_id: form.project_id ? parseInt(form.project_id, 10) : null,
        completion_status: form.completion_status,
        rera_permit_number: form.rera_permit_number || null,
        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, 10) || 0,
        permit_number: form.permit_number || null,
      };

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

      const data = await res.json();

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

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

  const inputCls = "w-full p-2.5 border border-gray-200 rounded-lg text-xs font-semibold text-gray-700 bg-gray-50/50 focus:bg-white focus:outline-none focus:border-[#C5A880] transition-all";
  const labelCls = "text-[9px] font-bold text-gray-400 uppercase tracking-wider block mb-1 font-serif";

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
        {/* Backdrop */}
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
          className="absolute inset-0 bg-[#0d1c32]/60 backdrop-blur-sm"
        />

        {/* Modal Window */}
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 15 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 15 }}
          className="relative bg-white w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden flex flex-col max-h-[90vh]"
        >
          {/* Header */}
          <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50/50">
            <div>
              <h3 className="font-serif text-base font-bold text-[#0d1c32]">Edit Property Listing</h3>
              <p className="text-[10px] text-gray-400 font-semibold uppercase tracking-widest mt-0.5">ID: #{property.id} • {property.title}</p>
            </div>
            <button onClick={onClose} className="p-1.5 hover:bg-gray-100 rounded-full transition-colors">
              <X className="w-4 h-4 text-gray-400 hover:text-gray-600" />
            </button>
          </div>

          {/* Form Content */}
          <form onSubmit={handleSubmit} className="p-6 overflow-y-auto space-y-4 flex-grow">
            {success ? (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="text-center py-10 space-y-3"
              >
                <div className="w-12 h-12 bg-emerald-50 text-emerald-500 rounded-full flex items-center justify-center mx-auto">
                  <CheckCircle2 className="w-6 h-6 animate-bounce" />
                </div>
                <h4 className="text-sm font-bold text-[#0d1c32]">Changes Saved Successfully!</h4>
                <p className="text-xs text-gray-400">Your property listing has been updated.</p>
              </motion.div>
            ) : (
              <>
                {error && (
                  <div className="p-3 bg-red-50 border border-red-100 text-red-600 text-xs font-semibold rounded-lg">
                    {error}
                  </div>
                )}

                {/* Grid Fields */}
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={labelCls}>Listing Title *</label>
                    <input type="text" required value={form.title} onChange={(e) => set('title', e.target.value)} className={inputCls} />
                  </div>
                  <div>
                    <label className={labelCls}>Listing Price (AED) *</label>
                    <input type="number" required min="0" value={form.price} onChange={(e) => set('price', e.target.value)} className={inputCls} />
                  </div>
                </div>

                <div className="grid grid-cols-3 gap-4">
                  <div>
                    <label className={labelCls}>Area (Sq. Ft.)</label>
                    <input type="number" min="0" value={form.area_sqft} onChange={(e) => set('area_sqft', e.target.value)} className={inputCls} />
                  </div>
                  <div>
                    <label className={labelCls}>Type *</label>
                    <select value={form.listing_type} onChange={(e) => set('listing_type', e.target.value)} className={inputCls}>
                      <option value="sale">For Sale</option>
                      <option value="rent">For Rent</option>
                      <option value="installment">Installment Plans</option>
                    </select>
                  </div>
                  <div>
                    <label className={labelCls}>Completion Status *</label>
                    <select value={form.completion_status} onChange={(e) => set('completion_status', e.target.value)} className={inputCls}>
                      <option value="Ready">Ready</option>
                      <option value="Off-Plan">Off-Plan</option>
                    </select>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className={labelCls}>Location *</label>
                    <select required value={form.location_id} onChange={(e) => set('location_id', e.target.value)} className={inputCls}>
                      <option value="">Select Location</option>
                      {meta?.locations.map((l) => (
                        <option key={l.id} value={l.id}>{l.name}</option>
                      ))}
                    </select>
                  </div>
                  <div>
                    <label className={labelCls}>Project (Community)</label>
                    <select value={form.project_id} onChange={(e) => set('project_id', e.target.value)} className={inputCls}>
                      <option value="">None (Independent Listing)</option>
                      {meta?.projects.map((p) => (
                        <option key={p.id} value={p.id}>{p.name}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Premium Fields */}
                <div className="pt-4 border-t border-gray-100">
                  <p className="text-[10px] font-bold text-[#C5A880] uppercase tracking-widest mb-3 font-serif">Premium & Technical Specifications</p>
                  
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                    <div>
                      <label className={labelCls}>Floor Level</label>
                      <input type="text" placeholder="e.g. Penthouse, High" value={form.floor_level} onChange={(e) => set('floor_level', e.target.value)} className={inputCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Furnishing</label>
                      <select value={form.furnishing} onChange={(e) => set('furnishing', e.target.value)} className={inputCls}>
                        <option value="Furnished">Furnished</option>
                        <option value="Unfurnished">Unfurnished</option>
                        <option value="Partly">Partly Furnished</option>
                      </select>
                    </div>
                    <div>
                      <label className={labelCls}>Plot Size (Sq. Ft.)</label>
                      <input type="number" min="0" placeholder="e.g. 5000" value={form.plot_size} onChange={(e) => set('plot_size', e.target.value)} className={inputCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Built-up Area (BUA)</label>
                      <input type="number" min="0" placeholder="e.g. 4200" value={form.bua} onChange={(e) => set('bua', e.target.value)} className={inputCls} />
                    </div>
                  </div>

                  <div className="grid grid-cols-3 gap-4 mt-3">
                    <div>
                      <label className={labelCls}>Parking Spaces</label>
                      <input type="number" min="0" value={form.parking_spaces} onChange={(e) => set('parking_spaces', e.target.value)} className={inputCls} />
                    </div>
                    <div>
                      <label className={labelCls}>RERA Permit Number</label>
                      <input type="text" placeholder="RERA Permit" value={form.rera_permit_number} onChange={(e) => set('rera_permit_number', e.target.value)} className={inputCls} />
                    </div>
                    <div>
                      <label className={labelCls}>Developer Permit Code</label>
                      <input type="text" placeholder="e.g. DEV-773" value={form.permit_number} onChange={(e) => set('permit_number', e.target.value)} className={inputCls} />
                    </div>
                  </div>

                  <div className="flex gap-6 mt-4">
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input type="checkbox" checked={form.maids_room} onChange={(e) => set('maids_room', e.target.checked)} className="w-4 h-4 accent-[#0d1c32]" />
                      <span className="text-[10px] font-bold text-gray-500 uppercase tracking-wider">Has Maids Room</span>
                    </label>
                    <label className="flex items-center gap-2.5 cursor-pointer">
                      <input type="checkbox" checked={form.private_pool} onChange={(e) => set('private_pool', e.target.checked)} className="w-4 h-4 accent-[#0d1c32]" />
                      <span className="text-[10px] font-bold text-gray-500 uppercase tracking-wider">Has Private Pool</span>
                    </label>
                  </div>
                </div>

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

                {/* Footer Buttons */}
                <div className="border-t border-gray-150 pt-4 flex justify-end gap-3">
                  <button type="button" onClick={onClose} className="px-4 py-2 border border-gray-250 text-gray-500 font-bold text-[10px] uppercase rounded-lg hover:bg-gray-50">
                    Cancel
                  </button>
                  <button type="submit" disabled={saving} className="px-5 py-2 bg-[#0d1c32] hover:bg-[#C5A880] text-white hover:text-[#0d1c32] font-bold text-[10px] uppercase rounded-lg transition-all flex items-center gap-1.5 disabled:opacity-50">
                    {saving ? (
                      <>
                        <Loader2 className="w-3 h-3 animate-spin" /> Saving...
                      </>
                    ) : 'Update Listing'}
                  </button>
                </div>
              </>
            )}
          </form>
        </motion.div>
      </div>
    </AnimatePresence>
  );
}
