'use client';

import { useEffect, useState } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import Image from 'next/image';
import {
  X, BedDouble, Bath, Maximize2, Car, ShieldCheck,
  Star, MapPin, Phone, MessageCircle, Loader2, AlertCircle,
  Calendar, CheckCircle2
} from 'lucide-react';

interface Agent {
  name: string;
  email: string;
  phone: string;
  avatar: string | null;
  brn: string | null;
}

interface Agency {
  name: string;
  logo: string | null;
  orn: string | null;
}

interface Location {
  name: string;
}

interface Project {
  name: string;
  construction_progress: number;
}

interface PropertyData {
  id: number;
  title: string;
  description: string;
  price_formatted: string;
  price_per_sqft: number | null;
  listing_type: string;
  completion_status: string;
  bedrooms: number | null;
  bathrooms: number | null;
  area_sqft: number | null;
  parking_spots: number;
  images: string[];
  amenities: number[];
  rera_permit_number: string | null;
  rera_verified: boolean;
  location: Location;
  property_type: string;
  project: Project | null;
  agent: Agent;
  agency: Agency | null;
}

interface PropertyDetailModalProps {
  propertyId: number | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

const AMENITY_MAP: Record<number, string> = {
  1: 'Security',
  2: 'CCTV Monitoring',
  3: 'Swimming Pool',
  4: 'Fitness Gym',
  5: 'Dedicated Parking',
  6: 'Balcony / Terrace',
  7: 'Central A/C',
  8: 'Maid Service Room',
  9: 'Study Room',
  10: 'Pets Allowed',
  11: '24/7 Concierge',
  12: 'High-speed Elevator',
  13: 'Valet Parking',
  14: 'Private Beach Access',
  15: 'Infinity Pool',
  16: 'Home Cinema',
  17: 'Smart Home Automation',
  18: 'Wine Cellar',
  19: 'Rooftop Terrace',
  20: 'Barbecue Area',
  21: 'Kids Play Zone',
  22: 'Sauna & Steam Room',
  23: 'Business Lounge',
  24: 'EV Charging Station'
};

export function PropertyDetailModal({ propertyId, open, onOpenChange }: PropertyDetailModalProps) {
  const [property, setProperty] = useState<PropertyData | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [activeImgIndex, setActiveImgIndex] = useState(0);
  
  // Schedule viewing form state
  const [showViewingForm, setShowViewingForm] = useState(false);
  const [viewingName, setViewingName] = useState('');
  const [viewingEmail, setViewingEmail] = useState('');
  const [viewingPhone, setViewingPhone] = useState('');
  const [viewingDate, setViewingDate] = useState('');
  const [viewingTime, setViewingTime] = useState('');
  const [submittingViewing, setSubmittingViewing] = useState(false);
  const [viewingSubmitted, setViewingSubmitted] = useState(false);

  useEffect(() => {
    if (!open || !propertyId) return;

    setLoading(true);
    setError('');
    setProperty(null);
    setActiveImgIndex(0);
    setShowViewingForm(false);
    setViewingName('');
    setViewingEmail('');
    setViewingPhone('');
    setViewingDate('');
    setViewingTime('');
    setViewingSubmitted(false);

    fetch(`/api/properties/${propertyId}`)
      .then((r) => {
        if (!r.ok) throw new Error(`HTTP error ${r.status}`);
        return r.json();
      })
      .then((res) => {
        if (res.success) {
          setProperty(res.data);
        } else {
          throw new Error(res.error || 'Failed to fetch property details');
        }
      })
      .catch((err) => {
        console.error(err);
        setError(err.message || 'Unable to retrieve property details. Please try again.');
      })
      .finally(() => {
        setLoading(false);
      });
  }, [propertyId, open]);

  const handleBookViewing = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!propertyId) return;

    setSubmittingViewing(true);
    try {
      const response = await fetch('/api/inquiries', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          unit_id: propertyId,
          customer_name: viewingName,
          customer_email: viewingEmail,
          customer_phone: viewingPhone,
          viewing_date: viewingDate,
          time_slot: viewingTime,
          message: `Scheduled viewing request by ${viewingName}. preferred_contact_method: phone`
        })
      });
      const data = await response.json();
      if (data.success) {
        setViewingSubmitted(true);
        setTimeout(() => {
          setShowViewingForm(false);
          setViewingSubmitted(false);
        }, 3000);
      } else {
        alert(data.error || 'Failed to schedule viewing');
      }
    } catch (err) {
      alert('Network error occurred. Please try again.');
    } finally {
      setSubmittingViewing(false);
    }
  };

  const fallbackImg = 'https://images.unsplash.com/photo-1600585154340-be6161a56a0c';

  const parsedImages = (() => {
    if (!property) return [];
    const imgs = property.images as any;
    if (Array.isArray(imgs)) return imgs;
    if (typeof imgs === 'string' && imgs.trim() !== '') {
      try {
        return JSON.parse(imgs);
      } catch {
        return [fallbackImg];
      }
    }
    return [fallbackImg];
  })();

  const rawImage = parsedImages[activeImgIndex];
  const currentImage = rawImage && typeof rawImage === 'string' && rawImage.trim() !== "" 
    ? rawImage 
    : 'https://images.unsplash.com/photo-1564013799919-ab600027ffc6?w=800&q=80';
  const whatsappUrl = property
    ? `https://wa.me/${property.agent.phone.replace(/\D/g, '')}?text=${encodeURIComponent(
        `Hi, I am interested in your listing "${property.title}" (AED ${property.price_formatted}). Please share more details.`
      )}`
    : '#';

  return (
    <Dialog.Root open={open} onOpenChange={onOpenChange}>
      <Dialog.Portal>
        {/* Backdrop */}
        <Dialog.Overlay className="fixed inset-0 z-50 bg-[#0d1c32]/65 backdrop-blur-sm transition-opacity" />

        {/* Content Container */}
        <Dialog.Content className="fixed left-1/2 top-1/2 z-50 w-[95%] max-w-[800px] -translate-x-1/2 -translate-y-1/2 rounded-2xl bg-white text-[#0d1c32] shadow-2xl overflow-hidden focus:outline-none max-h-[85vh] flex flex-col border border-gray-100">
          
          {/* Close Button */}
          <Dialog.Close className="absolute right-4 top-4 z-50 rounded-full p-2 bg-white/95 text-gray-500 hover:text-black shadow-md hover:bg-white transition-all outline-none">
            <X className="h-4 w-4" />
          </Dialog.Close>

          {/* SKELETON LOADER STATE */}
          {loading && (
            <div className="flex-grow overflow-y-auto p-6 space-y-6 animate-pulse">
              <div className="h-72 w-full bg-gray-200 rounded-xl" />
              <div className="flex gap-2">
                {[1, 2, 4, 5].map((i) => (
                  <div key={i} className="h-16 w-20 bg-gray-200 rounded-lg" />
                ))}
              </div>
              <div className="space-y-3 pt-4">
                <div className="h-6 bg-gray-200 rounded w-1/3" />
                <div className="h-8 bg-gray-200 rounded w-3/4" />
                <div className="h-4 bg-gray-200 rounded w-1/4" />
              </div>
              <div className="grid grid-cols-4 gap-3">
                {[1, 2, 3, 4].map((i) => (
                  <div key={i} className="h-16 bg-gray-200 rounded-xl" />
                ))}
              </div>
              <div className="h-24 bg-gray-200 rounded-xl" />
            </div>
          )}

          {/* ERROR STATE */}
          {error && !loading && (
            <div className="flex flex-col items-center justify-center p-12 text-center space-y-4">
              <AlertCircle className="h-12 w-12 text-red-500" />
              <Dialog.Title className="text-lg font-bold text-gray-900">Error Loading Property</Dialog.Title>
              <p className="text-sm text-gray-500 max-w-sm">{error}</p>
              <button
                onClick={() => onOpenChange(false)}
                className="px-5 py-2.5 bg-[#0d1c32] text-white font-bold text-xs uppercase tracking-wider rounded-lg"
              >
                Close
              </button>
            </div>
          )}

          {/* CONTENT RENDER STATE */}
          {property && !loading && (
            <>
              {/* Modal Body (Scrollable) */}
              <div className="flex-grow overflow-y-auto">
                
                {/* Image Gallery */}
                <div className="relative w-full h-[280px] sm:h-[380px] bg-gray-100">
                  <Image
                    src={currentImage}
                    alt={property.title}
                    fill
                    sizes="(max-width: 800px) 100vw, 800px"
                    className="object-cover"
                    priority
                  />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none" />
                  
                  {/* Absolute Badges */}
                  <div className="absolute bottom-4 left-4 flex gap-2">
                    <span className="text-[10px] font-bold px-3 py-1 bg-[#098E4B] text-white uppercase rounded shadow">
                      {property.listing_type === 'rent' ? 'For Rent' : 'For Sale'}
                    </span>
                    <span className="text-[10px] font-bold px-3 py-1 bg-white/95 text-[#0d1c32] uppercase rounded shadow capitalize">
                      {property.completion_status.replace('_', ' ')}
                    </span>
                  </div>
                </div>

                {/* Thumbnails Row */}
                {parsedImages.length > 1 && (
                  <div className="flex gap-2 p-4 overflow-x-auto bg-gray-50 border-b border-gray-100 shrink-0">
                    {parsedImages.map((img: string, i: number) => {
                      const validImg = img && typeof img === 'string' && img.trim() !== "" ? img : fallbackImg;
                      return (
                      <button
                        key={i}
                        onClick={() => setActiveImgIndex(i)}
                        className={`relative w-20 h-14 rounded-lg overflow-hidden border-2 transition-all flex-shrink-0 ${
                          activeImgIndex === i ? 'border-[#098E4B] scale-95 shadow-md' : 'border-transparent opacity-80 hover:opacity-100'
                        }`}
                      >
                        <Image src={validImg} alt="" fill sizes="80px" className="object-cover" />
                      </button>
                      );
                    })}
                  </div>
                )}

                {/* Detailed Metadata Content */}
                <div className="p-6 space-y-6">
                  
                  {/* Location & Header */}
                  <div>
                    <div className="flex items-center gap-1 text-[10px] font-bold text-[#098E4B] uppercase tracking-wider mb-1">
                      <MapPin className="h-3.5 w-3.5" />
                      <span>{property.location.name}</span>
                    </div>
                    
                    <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-2">
                      <Dialog.Title className="font-serif text-xl sm:text-2xl font-bold text-[#0d1c32] leading-tight">
                        {property.title}
                      </Dialog.Title>
                      
                      <div className="text-right shrink-0">
                        <p className="font-serif text-2xl font-bold text-[#098E4B]">
                          AED {property.price_formatted.replace('AED', '').trim()}
                        </p>
                        {property.price_per_sqft && (
                          <p className="text-[10px] text-gray-400 font-semibold mt-0.5">
                            AED {Math.round(property.price_per_sqft).toLocaleString()} / sqft
                          </p>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Core Features Grid */}
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    {[
                      { icon: <BedDouble className="h-4 w-4" />, label: 'Bedrooms', value: property.bedrooms ?? 'Studio' },
                      { icon: <Bath className="h-4 w-4" />, label: 'Bathrooms', value: property.bathrooms ?? '—' },
                      { icon: <Maximize2 className="h-4 w-4" />, label: 'Built Up Area', value: property.area_sqft ? `${property.area_sqft.toLocaleString()} sqft` : '—' },
                      { icon: <Car className="h-4 w-4" />, label: 'Parking Spots', value: property.parking_spots ?? 0 }
                    ].map((feature, i) => (
                      <div key={i} className="bg-[#f7f9fb] border border-gray-100 rounded-xl p-3 text-center shadow-sm">
                        <div className="flex justify-center text-[#098E4B] mb-1.5">{feature.icon}</div>
                        <p className="font-bold text-[#0d1c32] text-sm">{feature.value}</p>
                        <p className="text-[9px] text-gray-400 uppercase font-bold tracking-wider mt-0.5">{feature.label}</p>
                      </div>
                    ))}
                  </div>

                  {/* RERA Permit Bar */}
                  {property.rera_verified && (
                    <div className="flex items-center gap-2 p-3 bg-emerald-50 text-emerald-800 rounded-xl border border-emerald-100 text-xs font-semibold">
                      <ShieldCheck className="h-4 w-4 text-emerald-600 shrink-0" />
                      <span>RERA Verified Listing</span>
                      {property.rera_permit_number && (
                        <span className="text-gray-400 font-mono text-[10px] ml-auto">
                          Permit: {property.rera_permit_number}
                        </span>
                      )}
                    </div>
                  )}

                  {/* Description Section */}
                  <div className="space-y-2">
                    <h3 className="text-xs font-bold text-gray-400 uppercase tracking-widest">About This Property</h3>
                    <p className="text-sm text-gray-600 leading-relaxed whitespace-pre-line">
                      {property.description}
                    </p>
                  </div>

                  {/* Amenities */}
                  {property.amenities && property.amenities.length > 0 && (
                    <div className="space-y-3">
                      <h3 className="text-xs font-bold text-gray-400 uppercase tracking-widest">Amenities & Features</h3>
                      <div className="flex flex-wrap gap-2">
                        {property.amenities.map((id) => {
                          const name = AMENITY_MAP[Number(id)];
                          if (!name) return null;
                          return (
                            <span
                              key={id}
                              className="px-3 py-1.5 bg-gray-50 border border-gray-200/60 rounded-full text-[10px] font-bold text-[#0d1c32]"
                            >
                              {name}
                            </span>
                          );
                        })}
                      </div>
                    </div>
                  )}

                  {/* Booking Appointment Widget Form */}
                  {showViewingForm && (
                    <div className="bg-[#f7f9fb] border border-[#098E4B]/30 rounded-xl p-5 space-y-4 animate-in fade-in slide-in-from-bottom-2 duration-300">
                      <div className="flex items-center justify-between">
                        <h4 className="font-serif text-sm font-bold text-[#0d1c32]">Schedule Viewing Appointment</h4>
                        <button
                          type="button"
                          onClick={() => setShowViewingForm(false)}
                          className="text-gray-400 hover:text-[#0d1c32]"
                        >
                          Cancel
                        </button>
                      </div>

                      {viewingSubmitted ? (
                        <div className="text-center py-4 space-y-2">
                          <CheckCircle2 className="h-10 w-10 text-emerald-500 mx-auto" />
                          <p className="text-xs font-bold text-gray-800">Inquiry Request Sent Successfully!</p>
                          <p className="text-[10px] text-gray-400">Our real estate agent will contact you shortly.</p>
                        </div>
                      ) : (
                        <form onSubmit={handleBookViewing} className="space-y-3">
                          <div className="space-y-3">
                            <input
                              type="text"
                              required
                              placeholder="Full Name"
                              value={viewingName}
                              onChange={(e) => setViewingName(e.target.value)}
                              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                            />
                            <div className="grid grid-cols-2 gap-2">
                              <input
                                type="email"
                                required
                                placeholder="Email Address"
                                value={viewingEmail}
                                onChange={(e) => setViewingEmail(e.target.value)}
                                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                              />
                              <input
                                type="tel"
                                required
                                placeholder="Phone Number"
                                value={viewingPhone}
                                onChange={(e) => setViewingPhone(e.target.value)}
                                className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                              />
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-2">
                            <input
                              type="date"
                              required
                              min={new Date().toISOString().split('T')[0]}
                              value={viewingDate}
                              onChange={(e) => setViewingDate(e.target.value)}
                              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs"
                            />
                            <select
                              required
                              value={viewingTime}
                              onChange={(e) => setViewingTime(e.target.value)}
                              className="w-full px-3 py-2 border border-gray-200 rounded-lg text-xs bg-white"
                            >
                              <option value="">Select Time Slot</option>
                              <option value="09:00 AM">09:00 AM</option>
                              <option value="11:00 AM">11:00 AM</option>
                              <option value="01:00 PM">01:00 PM</option>
                              <option value="03:00 PM">03:00 PM</option>
                              <option value="05:00 PM">05:00 PM</option>
                            </select>
                          </div>
                          <button
                            type="submit"
                            disabled={submittingViewing}
                            className="w-full py-2 bg-[#098E4B] text-white font-bold text-xs uppercase tracking-wider rounded-lg hover:bg-[#077a3f] flex justify-center items-center gap-1.5"
                          >
                            {submittingViewing ? (
                              <Loader2 className="h-3.5 w-3.5 animate-spin" />
                            ) : (
                              'Confirm Viewing Request'
                            )}
                          </button>
                        </form>
                      )}
                    </div>
                  )}

                </div>
              </div>

              {/* Sticky Footer / Contact Bar */}
              <div className="sticky bottom-0 border-t border-gray-100 bg-white p-4 flex flex-col sm:flex-row items-center justify-between gap-4 z-10 shrink-0 shadow-lg">
                <div className="flex items-center gap-3 w-full sm:w-auto">
                  <div className="w-10 h-10 rounded-full bg-[#0d1c32]/5 flex items-center justify-center font-bold text-xs text-[#0d1c32] uppercase shrink-0">
                    {property.agent.avatar && property.agent.avatar.trim() !== "" ? (
                      <div className="relative w-full h-full rounded-full overflow-hidden">
                        <Image src={property.agent.avatar} alt={property.agent.name} fill className="object-cover" />
                      </div>
                    ) : (
                      property.agent.name.split(' ').map(n => n[0]).join('').slice(0, 2)
                    )}
                  </div>
                  <div className="min-w-0">
                    <p className="text-xs font-bold text-[#0d1c32] truncate">{property.agent.name}</p>
                    <p className="text-[10px] text-gray-400 truncate">
                      {property.agency?.name ?? 'Premium Advisory'}
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2 w-full sm:w-auto shrink-0">
                  <a
                    href={`tel:${property.agent.phone}`}
                    className="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-4 py-2.5 border border-gray-200 rounded-lg text-[10px] font-bold text-[#0d1c32] uppercase hover:bg-gray-50 transition-colors"
                  >
                    <Phone className="h-3.5 w-3.5" /> Call Agent
                  </a>
                  <a
                    href={whatsappUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-4 py-2.5 bg-emerald-500 hover:bg-emerald-600 text-white rounded-lg text-[10px] font-bold uppercase tracking-wider transition-colors"
                  >
                    <MessageCircle className="h-3.5 w-3.5" /> WhatsApp
                  </a>
                  <button
                    onClick={() => setShowViewingForm(!showViewingForm)}
                    className="flex-1 sm:flex-none flex items-center justify-center gap-1.5 px-5 py-2.5 bg-[#098E4B] hover:bg-[#077a3f] text-white rounded-lg text-[10px] font-bold uppercase tracking-wider transition-colors"
                  >
                    <Calendar className="h-3.5 w-3.5" /> Book Now
                  </button>
                </div>
              </div>
            </>
          )}

        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  );
}
