/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React, { useState, useRef } from 'react';
import { X, Plus, Image as ImageIcon, Upload, Paperclip, FileText } from 'lucide-react';
import { PropertyType } from '../types';

interface AddPropertyModalProps {
  onClose: () => void;
  onSubmit: (propertyData: {
    name: string;
    type: PropertyType;
    address: string;
    description: string;
    priceDay?: number;
    priceMonth?: number;
    priceBuy?: number;
    imageUrl?: string;
    contactPhone?: string;
    contactEmail?: string;
    mapEmbedUrl?: string;
  }) => void;
}

export default function AddPropertyModal({
  onClose,
  onSubmit,
}: AddPropertyModalProps) {
  const [name, setName] = useState('');
  const [type, setType] = useState<PropertyType>('hotel');
  const [address, setAddress] = useState('');
  const [description, setDescription] = useState('');
  const [priceDay, setPriceDay] = useState('');
  const [priceMonth, setPriceMonth] = useState('');
  const [priceBuy, setPriceBuy] = useState('');
  const [imageUrl, setImageUrl] = useState('');
  const [contactPhone, setContactPhone] = useState('');
  const [contactEmail, setContactEmail] = useState('');
  const [mapEmbedUrl, setMapEmbedUrl] = useState('');

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // File Upload drag and drop states
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [uploadedFile, setUploadedFile] = useState<{ name: string, size: string, dataUrl: string } | null>(null);
  const [uploadedBrochure, setUploadedBrochure] = useState<{ name: string, size: string, dataUrl: string } | null>(null);
  const [dragActive, setDragActive] = useState(false);
  const [brochureDragActive, setBrochureDragActive] = useState(false);

  const handleFile = (file: File, isBrochure: boolean = false) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      const dataUrl = e.target?.result as string;
      if (isBrochure) {
        setUploadedBrochure({
          name: file.name,
          size: (file.size / (1024 * 1024)).toFixed(2) + ' MB',
          dataUrl
        });
      } else {
        setImageUrl(dataUrl); // This directly binds the uploaded image as the property image URL!
        setUploadedFile({
          name: file.name,
          size: (file.size / (1024 * 1024)).toFixed(2) + ' MB',
          dataUrl
        });
      }
    };
    reader.readAsDataURL(file);
  };

  const handleDrag = (e: React.DragEvent, isBrochure: boolean = false) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.type === "dragenter" || e.type === "dragover") {
      if (isBrochure) setBrochureDragActive(true);
      else setDragActive(true);
    } else if (e.type === "dragleave") {
      if (isBrochure) setBrochureDragActive(false);
      else setDragActive(false);
    }
  };

  const handleDrop = (e: React.DragEvent, isBrochure: boolean = false) => {
    e.preventDefault();
    e.stopPropagation();
    if (isBrochure) {
      setBrochureDragActive(false);
      if (e.dataTransfer.files && e.dataTransfer.files[0]) {
        handleFile(e.dataTransfer.files[0], true);
      }
    } else {
      setDragActive(false);
      if (e.dataTransfer.files && e.dataTransfer.files[0]) {
        handleFile(e.dataTransfer.files[0], false);
      }
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>, isBrochure: boolean = false) => {
    if (e.target.files && e.target.files[0]) {
      handleFile(e.target.files[0], isBrochure);
    }
  };

  // Suggestions for rapid testing
  const presetImages = [
    { name: 'Hotel Mewah', url: 'https://images.unsplash.com/photo-1566073771259-6a8506099945?auto=format&fit=crop&w=800&q=80' },
    { name: 'Modern Villa', url: 'https://images.unsplash.com/photo-1580587771525-78b9dba3b914?auto=format&fit=crop&w=800&q=80' },
    { name: 'Cozy Apart', url: 'https://images.unsplash.com/photo-1545324418-cc1a3fa10c00?auto=format&fit=crop&w=800&q=80' },
    { name: 'Rumah Tinggal', url: 'https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&w=800&q=80' },
  ];

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    if (!name || !address || !description) {
      setError('Mohon lengkapi seluruh kolom wajib!');
      return;
    }

    setLoading(true);
    onSubmit({
      name,
      type,
      address,
      description,
      priceDay: priceDay ? Number(priceDay) : undefined,
      priceMonth: priceMonth ? Number(priceMonth) : undefined,
      priceBuy: priceBuy ? Number(priceBuy) : undefined,
      imageUrl: imageUrl || 'https://images.unsplash.com/photo-1564013799919-ab600027ffc6?auto=format&fit=crop&w=800&q=80',
      contactPhone: contactPhone || undefined,
      contactEmail: contactEmail || undefined,
      mapEmbedUrl: mapEmbedUrl || undefined
    });
    setLoading(false);
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs overflow-y-auto">
      <div className="bg-white rounded-2xl w-full max-w-2xl overflow-hidden shadow-2xl border border-gray-100 relative">
        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-100 flex justify-between items-center bg-gray-50">
          <div>
            <h3 className="font-sans font-bold text-lg text-gray-900">Menyewakan / Menjual Properti Baru</h3>
            <p className="text-xs text-gray-500">Daftarkan akomodasi, kamar hotel, sewa kos, atau rumah Anda ke platform.</p>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 p-1 rounded-full hover:bg-gray-100 transition-colors cursor-pointer"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Form Body */}
        <form onSubmit={handleFormSubmit} className="p-6 space-y-4 max-h-[75vh] overflow-y-auto">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1">Nama Properti / Hotel / Kos *</label>
              <input
                type="text"
                required
                placeholder="Contoh: Hotel Mercure Sabang, Kost Kemanggisan Cozy"
                value={name}
                onChange={(e) => setName(e.target.value)}
                className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
              />
            </div>
            <div>
              <label className="block text-xs font-semibold text-gray-700 mb-1">Tipe Properti *</label>
              <select
                value={type}
                onChange={(e) => setType(e.target.value as PropertyType)}
                className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
              >
                <option value="hotel">Hotel (Menginap Harian)</option>
                <option value="villa">Villa (Menginap Harian)</option>
                <option value="apartment">Apartemen (Sewa Bulanan / Jual)</option>
                <option value="house">Rumah (Jual Milik Sendiri)</option>
                <option value="kos">Kos-Kosan (Sewa Bulanan)</option>
              </select>
              {/* Quick Preset Pills for Property Type */}
              <div className="flex flex-wrap gap-1 mt-1.5">
                {(['hotel', 'villa', 'apartment', 'house', 'kos'] as PropertyType[]).map((t) => (
                  <button
                    key={t}
                    type="button"
                    onClick={() => setType(t)}
                    className={`text-[10px] px-2 py-0.5 rounded-full border transition-all cursor-pointer ${
                      type === t 
                        ? 'bg-blue-600 border-blue-600 text-white font-semibold' 
                        : 'bg-gray-50 border-gray-200 text-gray-600 hover:border-gray-300'
                    }`}
                  >
                    {t === 'hotel' ? '🏨 Hotel' : t === 'villa' ? '🏡 Villa' : t === 'apartment' ? '🏢 Apartemen' : t === 'house' ? '🏠 Rumah' : '🛏️ Kos'}
                  </button>
                ))}
              </div>
            </div>
          </div>

          <div>
            <div className="flex justify-between items-center mb-1">
              <label className="block text-xs font-semibold text-gray-700">Alamat Lengkap Properti *</label>
              <span className="text-[10px] text-gray-400 font-medium">Klik kota untuk auto-isi</span>
            </div>
            <textarea
              required
              rows={2}
              placeholder="Contoh: Jl. Diponegoro No. 12, Menteng, Jakarta Pusat"
              value={address}
              onChange={(e) => setAddress(e.target.value)}
              className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
            />
            {/* Quick Location presets */}
            <div className="flex flex-wrap gap-1 mt-1.5 items-center">
              <span className="text-[9px] text-gray-400 font-black uppercase mr-1">Preset Kota:</span>
              {['Jakarta Pusat', 'Jakarta Selatan', 'Bandung', 'Bali', 'Yogyakarta', 'Surabaya', 'Medan'].map((city) => (
                <button
                  key={city}
                  type="button"
                  onClick={() => {
                    if (address.toLowerCase().includes(city.toLowerCase())) return;
                    if (!address.trim()) {
                      setAddress(city);
                    } else {
                      const trimmed = address.trim();
                      setAddress(trimmed.endsWith(',') ? `${trimmed} ${city}` : `${trimmed}, ${city}`);
                    }
                  }}
                  className="text-[9px] px-2 py-0.5 rounded bg-gray-100 hover:bg-gray-200 text-gray-700 border border-gray-200/50 transition-all cursor-pointer"
                >
                  📍 {city}
                </button>
              ))}
            </div>
          </div>

          <div>
            <div className="flex justify-between items-center mb-1">
              <label className="block text-xs font-semibold text-gray-700">Deskripsi dan Fasilitas Properti *</label>
              <span className="text-[10px] text-gray-400 font-medium">Klik fasilitas untuk tambah cepat</span>
            </div>
            <textarea
              required
              rows={3}
              placeholder="Detail fasilitas, misal: Kolam renang, WiFi, AC, Kamar Mandi Dalam, dekat halte busway, dll."
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              className="w-full p-2.5 border border-gray-200 rounded-lg text-sm bg-white focus:outline-hidden focus:border-blue-500"
            />
            {/* Quick Facility Tag Presets */}
            <div className="flex flex-wrap gap-1 mt-1.5 items-center">
              <span className="text-[9px] text-gray-400 font-black uppercase mr-1">Preset Fasilitas:</span>
              {['WiFi Gratis', 'AC', 'Kolam Renang', 'Kamar Mandi Dalam', 'Parkir Mobil', 'Dapur Bersama', 'Keamanan 24 Jam', 'TV', 'Kulkas', 'Sofa'].map((fac) => (
                <button
                  key={fac}
                  type="button"
                  onClick={() => {
                    if (description.toLowerCase().includes(fac.toLowerCase())) return;
                    if (!description.trim()) {
                      setDescription(`Fasilitas: ${fac}`);
                    } else {
                      const trimmed = description.trim();
                      if (trimmed.endsWith('.') || trimmed.endsWith(',')) {
                        setDescription(`${trimmed} ${fac}`);
                      } else {
                        setDescription(`${trimmed}, ${fac}`);
                      }
                    }
                  }}
                  className="text-[9px] px-2 py-0.5 rounded-full bg-blue-50 hover:bg-blue-100 text-blue-700 border border-blue-100/30 transition-all cursor-pointer font-medium"
                >
                  ✨ {fac}
                </button>
              ))}
            </div>
          </div>

          {/* Contacts Section */}
          <div className="bg-emerald-50/20 p-4 rounded-xl border border-emerald-100/50 space-y-3">
            <h4 className="text-xs font-bold text-emerald-900 uppercase tracking-wider">Informasi Kontak Pengelola</h4>
            <p className="text-[11px] text-gray-500">Isi kontak agar calon penyewa/pembeli dapat menghubungi Anda langsung:</p>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
              <div>
                <label className="block text-[11px] font-semibold text-gray-600 mb-1">No. Telepon / WhatsApp Kontak *</label>
                <input
                  type="text"
                  required
                  placeholder="Misal: 081234567890"
                  value={contactPhone}
                  onChange={(e) => setContactPhone(e.target.value)}
                  className="w-full p-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-gray-600 mb-1">Email Kontak (Opsional)</label>
                <input
                  type="email"
                  placeholder="Misal: manager@hotel.com"
                  value={contactEmail}
                  onChange={(e) => setContactEmail(e.target.value)}
                  className="w-full p-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* Map Setup & Preview */}
          <div className="bg-amber-50/20 p-4 rounded-xl border border-amber-100/50 space-y-3">
            <h4 className="text-xs font-bold text-amber-900 uppercase tracking-wider">Peta & Koordinat Lokasi</h4>
            <p className="text-[11px] text-gray-500">Kami akan memetakan alamat otomatis atau Anda dapat memasukkan URL custom embed:</p>
            
            <div>
              <label className="block text-[11px] font-semibold text-gray-600 mb-1">URL Google Maps Embed Custom (Opsional)</label>
              <input
                type="url"
                placeholder="https://maps.google.com/maps?q=... atau kosongkan untuk auto-generasi"
                value={mapEmbedUrl}
                onChange={(e) => setMapEmbedUrl(e.target.value)}
                className="w-full p-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
              />
            </div>

            {address && (
              <div className="space-y-1">
                <span className="block text-[10px] font-bold text-gray-400 uppercase">Live Preview Peta Alamat:</span>
                <div className="rounded-lg overflow-hidden border border-gray-200 bg-white aspect-video relative h-36">
                  <iframe
                    title="Live Preview Peta"
                    src={mapEmbedUrl || `https://maps.google.com/maps?q=${encodeURIComponent(address)}&t=&z=15&ie=UTF8&iwloc=&output=embed`}
                    width="100%"
                    height="100%"
                    style={{ border: 0 }}
                    allowFullScreen={false}
                    loading="lazy"
                    className="w-full h-full relative z-10"
                  />
                  <div className="absolute inset-0 flex items-center justify-center bg-gray-50 text-gray-400 text-xs z-0">
                    <span>Memuat Preview Peta...</span>
                  </div>
                </div>
              </div>
            )}
          </div>

          {/* Pricing Config based on Type Selection */}
          <div className="bg-blue-50/50 p-4 rounded-xl border border-blue-100/50 space-y-3">
            <h4 className="text-xs font-bold text-blue-900 uppercase tracking-wider">Konfigurasi Harga & Transaksi</h4>
            <p className="text-[11px] text-gray-500">Anda dapat mengisi salah satu atau beberapa skema transaksi di bawah ini:</p>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div>
                <label className="block text-[11px] font-semibold text-gray-600 mb-1">Tarif Harian (Rupiah)</label>
                <input
                  type="number"
                  placeholder="Misal: 500000"
                  value={priceDay}
                  onChange={(e) => setPriceDay(e.target.value)}
                  className="w-full p-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-gray-600 mb-1">Tarif Bulanan (Rupiah)</label>
                <input
                  type="number"
                  placeholder="Misal: 2500000"
                  value={priceMonth}
                  onChange={(e) => setPriceMonth(e.target.value)}
                  className="w-full p-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                />
              </div>
              <div>
                <label className="block text-[11px] font-semibold text-gray-600 mb-1">Harga Jual Unit (Rupiah)</label>
                <input
                  type="number"
                  placeholder="Misal: 750000000"
                  value={priceBuy}
                  onChange={(e) => setPriceBuy(e.target.value)}
                  className="w-full p-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                />
              </div>
            </div>
          </div>

          {/* Image & Brochure File Upload Zone (Supports Drag & Drop + Manual Select) */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            
            {/* Column 1: Foto Properti */}
            <div className="space-y-2">
              <label className="block text-xs font-semibold text-gray-700">Foto Utama Properti *</label>
              
              <div 
                onDragEnter={(e) => handleDrag(e, false)}
                onDragOver={(e) => handleDrag(e, false)}
                onDragLeave={(e) => handleDrag(e, false)}
                onDrop={(e) => handleDrop(e, false)}
                onClick={() => fileInputRef.current?.click()}
                className={`border-2 border-dashed rounded-xl p-4 text-center cursor-pointer transition-all flex flex-col items-center justify-center space-y-1.5 h-36 ${
                  dragActive 
                    ? 'border-blue-600 bg-blue-50/50' 
                    : 'border-gray-200 hover:border-blue-500 hover:bg-gray-50/40 bg-white'
                }`}
              >
                <input 
                  type="file"
                  ref={fileInputRef}
                  onChange={(e) => handleFileChange(e, false)}
                  accept="image/*"
                  className="hidden"
                />
                
                {imageUrl && imageUrl.startsWith('data:') ? (
                  <div className="flex flex-col items-center space-y-1 w-full h-full justify-center">
                    <img src={imageUrl} alt="Uploaded" className="h-16 w-24 object-cover rounded-md border border-gray-100 shadow-xs" />
                    <span className="text-[10px] font-semibold text-emerald-600 flex items-center gap-0.5">
                      <ImageIcon className="h-3 w-3" />
                      <span>{uploadedFile ? uploadedFile.name : "Foto Terunggah"}</span>
                    </span>
                  </div>
                ) : (
                  <>
                    <div className="bg-blue-50 text-blue-600 p-2 rounded-lg">
                      <Upload className="h-4 w-4" />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-gray-700">Seret & Lepas Gambar</p>
                      <p className="text-[10px] text-gray-400">atau klik untuk telusuri file</p>
                    </div>
                  </>
                )}
              </div>

              {/* URL Input (Alternative if they prefer URL) */}
              <div className="space-y-1">
                <span className="text-[10px] text-gray-400 block font-semibold">Atau gunakan URL gambar langsung:</span>
                <input
                  type="url"
                  placeholder="https://images.unsplash.com/... atau gunakan preset"
                  value={imageUrl && !imageUrl.startsWith('data:') ? imageUrl : ''}
                  onChange={(e) => {
                    setImageUrl(e.target.value);
                    setUploadedFile(null);
                  }}
                  className="w-full p-2 border border-gray-200 rounded-lg text-[11px] bg-white focus:outline-hidden focus:border-blue-500"
                />
                
                {/* Presets */}
                <div className="flex flex-wrap gap-1 mt-1">
                  {presetImages.map((img) => (
                    <button
                      key={img.name}
                      type="button"
                      onClick={() => {
                        setImageUrl(img.url);
                        setUploadedFile(null);
                      }}
                      className={`px-2 py-0.5 text-[9px] rounded border transition-colors cursor-pointer ${
                        imageUrl === img.url
                          ? 'bg-blue-600 text-white border-blue-600 font-bold'
                          : 'bg-gray-50 text-gray-500 border-gray-200 hover:bg-gray-100'
                      }`}
                    >
                      {img.name}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {/* Column 2: Dokumen Brosur / Legalitas (File) */}
            <div className="space-y-2">
              <label className="block text-xs font-semibold text-gray-700">Dokumen Pendukung / Brosur (PDF/Files)</label>
              
              <div 
                onDragEnter={(e) => handleDrag(e, true)}
                onDragOver={(e) => handleDrag(e, true)}
                onDragLeave={(e) => handleDrag(e, true)}
                onDrop={(e) => handleDrop(e, true)}
                onClick={() => {
                  const input = document.createElement('input');
                  input.type = 'file';
                  input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.zip';
                  input.onchange = (e: any) => {
                    if (e.target.files && e.target.files[0]) {
                      handleFile(e.target.files[0], true);
                    }
                  };
                  input.click();
                }}
                className={`border-2 border-dashed rounded-xl p-4 text-center cursor-pointer transition-all flex flex-col items-center justify-center space-y-1.5 h-36 ${
                  brochureDragActive 
                    ? 'border-emerald-600 bg-emerald-50/50' 
                    : 'border-gray-200 hover:border-emerald-500 hover:bg-gray-50/40 bg-white'
                }`}
              >
                {uploadedBrochure ? (
                  <div className="flex flex-col items-center space-y-1 w-full h-full justify-center text-center p-2">
                    <FileText className="h-8 w-8 text-emerald-600" />
                    <span className="text-xs font-bold text-gray-800 line-clamp-1">{uploadedBrochure.name}</span>
                    <span className="text-[10px] text-gray-400 font-semibold">{uploadedBrochure.size} • Terlampir</span>
                  </div>
                ) : (
                  <>
                    <div className="bg-emerald-50 text-emerald-600 p-2 rounded-lg">
                      <Paperclip className="h-4 w-4" />
                    </div>
                    <div>
                      <p className="text-xs font-bold text-gray-700">Upload Brosur Properti</p>
                      <p className="text-[10px] text-gray-400">PDF, Word, Excel, ZIP up to 10MB</p>
                    </div>
                  </>
                )}
              </div>
              <p className="text-[10px] text-gray-400 italic leading-normal">
                Unggah lampiran brosur, skema angsuran sewa beli, denah bangunan, sertifikat, atau file pelengkap untuk dilihat calon pembeli/penyewa.
              </p>
            </div>

          </div>

          {error && (
            <div className="p-3 bg-red-50 border border-red-100 text-red-700 rounded-lg text-xs font-semibold" id="add-property-error">
              {error}
            </div>
          )}

          {/* Submit Action */}
          <div className="pt-4 border-t border-gray-100 flex justify-end space-x-3">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg text-xs font-semibold hover:bg-gray-50 transition-colors cursor-pointer"
            >
              Batalkan
            </button>
            <button
              type="submit"
              disabled={loading}
              className="bg-blue-600 hover:bg-blue-700 disabled:bg-blue-400 text-white px-5 py-2 rounded-lg text-xs font-bold shadow-sm transition-colors flex items-center space-x-1 cursor-pointer"
            >
              <Plus className="h-4 w-4" />
              <span>{loading ? 'Menyimpan...' : 'Daftarkan Properti'}</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
