'use client';

import { useEffect, useState } from 'react';
import { X, Loader2, CheckCircle2, Building2 } 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 AdminEditPropertyModalProps {
  property: any | null;
  onClose: () => void;
  onSuccess: () => void;
}

export function AdminEditPropertyModal({ property, onClose, onSuccess }: AdminEditPropertyModalProps) {
  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);

  // Load metadata and populate form when property changes
  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 () => {
    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,
        // Premium dynamic fields
        floor_level: form.floor_level || null,
        furnishing: form.furnishing,
        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/${property.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const data = await res.json();
      if (!data.success) {
        throw new Error(data.error || 'Failed to update property');
      }

      setSuccess(true);
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1000);
    } catch (err: any) {
      setError(err.message || 'Something went wrong while saving changes.');
    } finally {
      setSaving(false);
    }
  };

  const labelCls = 'block text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1.5 font-serif';
  const inputCls = 'w-full text-xs font-semibold text-gray-700 bg-gray-50 border border-gray-150 rounded-lg px-3 py-2 focus:outline-none focus:border-[#C5A880] transition-colors';

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-sm overflow-y-auto">
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 10 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 10 }}
          className="relative w-full max-w-2xl bg-white rounded-2xl shadow-2xl flex flex-col my-8 max-h-[85vh] overflow-hidden"
        >
          {/* Header */}
          <div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between shrink-0">
            <div>
              <h3 className="font-serif text-lg font-bold text-[#0d1c32]">Edit Listing</h3>
              <p className="text-[10px] font-bold text-[#C5A880] uppercase tracking-widest mt-0.5">Modify Property Fields</p>
            </div>
            <button onClick={onClose} className="p-2 hover:bg-gray-50 rounded-full transition-colors text-gray-400 hover:text-gray-700">
              <X className="w-4 h-4" />
            </button>
          </div>

          {/* Form Content */}
          <div className="flex-grow overflow-y-auto p-6 space-y-4">
            {success ? (
              <div className="flex flex-col items-center justify-center py-10 text-center">
                <CheckCircle2 className="w-12 h-12 text-emerald-500 mb-3" />
                <h4 className="text-sm font-bold text-[#0d1c32]">Changes Saved Successfully</h4>
                <p className="text-xs text-gray-400 mt-1">Listing details updated in the database.</p>
              </div>
            ) : (
              <>
                {error && (
                  <div className="p-3.5 bg-red-50 border border-red-200 text-red-600 rounded-xl text-xs font-medium">
                    {error}
                  </div>
                )}

                <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. Luxury 5BR Villa in Palm Jumeirah"
                      className={inputCls}
                      required
                    />
                  </div>

                  <div className="col-span-2">
                    <label className={labelCls}>Description</label>
                    <textarea
                      value={form.description}
                      onChange={(e) => set('description', e.target.value)}
                      placeholder="Detailed details about the property..."
                      rows={4}
                      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. 5200000"
                      className={inputCls}
                      required
                    />
                  </div>

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

                  <div>
                    <label className={labelCls}>Listing Type</label>
                    <select
                      value={form.listing_type}
                      onChange={(e) => set('listing_type', e.target.value)}
                      className={inputCls}
                    >
                      <option value="sale">Sale</option>
                      <option value="rent">Rent</option>
                      <option value="installment">Installment</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>
                    <label className={labelCls}>Location</label>
                    <select
                      value={form.location_id}
                      onChange={(e) => set('location_id', e.target.value)}
                      className={inputCls}
                      required
                    >
                      <option value="">Select Location</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="">No Project</option>
                      {meta?.projects.map((proj) => (
                        <option key={proj.id} value={proj.id}>{proj.name}</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. 7117823412"
                      className={inputCls}
                    />
                  </div>

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

                <div className="border-t border-gray-100 pt-4 mt-2">
                  <h4 className="text-xs font-bold text-[#0d1c32] uppercase tracking-wider mb-3 font-serif">Premium Specs & Custom Inputs</h4>
                  
                  <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. Mid Floor, Penthouse"
                        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="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"
                        value={form.plot_size}
                        onChange={(e) => set('plot_size', e.target.value)}
                        placeholder="e.g. 6000"
                        className={inputCls}
                      />
                    </div>

                    <div>
                      <label className={labelCls}>BUA (Sq. Ft.)</label>
                      <input
                        type="number"
                        value={form.bua}
                        onChange={(e) => set('bua', e.target.value)}
                        placeholder="e.g. 5200"
                        className={inputCls}
                      />
                    </div>

                    <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"
                        className={inputCls}
                      />
                    </div>

                    <div className="flex flex-col justify-center space-y-2 mt-4 pl-1">
                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={form.maids_room}
                          onChange={(e) => set('maids_room', e.target.checked)}
                          className="w-4 h-4 accent-[#C5A880]"
                        />
                        <span className="text-xs font-semibold text-[#0d1c32]">Maids Room Included</span>
                      </label>

                      <label className="flex items-center gap-2 cursor-pointer select-none">
                        <input
                          type="checkbox"
                          checked={form.private_pool}
                          onChange={(e) => set('private_pool', e.target.checked)}
                          className="w-4 h-4 accent-[#C5A880]"
                        />
                        <span className="text-xs font-semibold text-[#0d1c32]">Private Swimming Pool</span>
                      </label>
                    </div>
                  </div>
                </div>
              </>
            )}
          </div>

          {/* Footer Actions */}
          {!success && (
            <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3 shrink-0 bg-gray-50">
              <button
                type="button"
                onClick={onClose}
                className="px-4 py-2 text-xs font-bold text-gray-500 uppercase tracking-wider hover:text-[#0d1c32] transition-colors"
                disabled={saving}
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={handleSubmit}
                className="flex items-center gap-1.5 text-[10px] font-bold text-white bg-[#0d1c32] hover:bg-[#C5A880] hover:text-[#0d1c32] uppercase tracking-wider px-5 py-2.5 rounded-lg transition-all"
                disabled={saving}
              >
                {saving ? (
                  <>
                    <Loader2 className="w-3.5 h-3.5 animate-spin" /> Saving...
                  </>
                ) : (
                  'Save Changes'
                )}
              </button>
            </div>
          )}
        </motion.div>
      </div>
    </AnimatePresence>
  );
}
