import React, { useState, useEffect, useRef } from 'react';
import { X, MapPin, Loader2, Clock, Map as MapIcon } from 'lucide-react';
import { useTourStore } from './useTourStore.js';
import { MapContainer, TileLayer, Marker, useMapEvents, useMap } from 'react-leaflet';
import L from 'leaflet';

// Cấu hình Icon mặc định để tránh crash Marker trong Modal
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png',
  iconUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png',
  shadowUrl: 'https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png',
});

// Component Helper xử lý việc chọn vị trí trên mini map bằng chuột phải
const MapPicker = ({ onPick, center }: { onPick: (latlng: L.LatLng) => void, center: [number, number] }) => {
  const [menuPos, setMenuPos] = useState<{ x: number, y: number, latlng: L.LatLng } | null>(null);
  const menuRef = useRef<HTMLDivElement>(null);
  const map = useMap();

  useMapEvents({
    contextmenu: (e) => {
      L.DomEvent.preventDefault(e.originalEvent);
      L.DomEvent.stopPropagation(e.originalEvent);
      setMenuPos({ x: e.containerPoint.x, y: e.containerPoint.y, latlng: e.latlng });
    },
    click: () => setMenuPos(null),
    dragstart: () => setMenuPos(null),
  });

  useEffect(() => {
    if (menuPos && menuRef.current) {
      L.DomEvent.disableClickPropagation(menuRef.current);
    }
  }, [menuPos]);

  useEffect(() => {
    map.setView(center, map.getZoom());
  }, [center]);

  return (
    <>
      {menuPos && (
        <div 
          ref={menuRef}
          className="absolute z-[3000] bg-white rounded-xl shadow-xl border border-gray-100 py-1 w-44 animate-in zoom-in-95 duration-200"
          style={{ top: menuPos.y, left: menuPos.x }}
        >
          <button 
            type="button"
            onClick={() => { onPick(menuPos.latlng); setMenuPos(null); }}
            className="w-full text-left px-4 py-2 hover:bg-blue-50 text-xs font-bold text-blue-600 flex items-center gap-2"
          >
            <MapPin className="w-3 h-3" /> Thêm vào chặng hiện tại
          </button>
        </div>
      )}
    </>
  );
};

export const AddLocationModal = ({ isOpen, onClose, tourId, initialLegId, editingLocation }: { isOpen: boolean, onClose: () => void, tourId: string, initialLegId?: string, editingLocation?: any }) => {
  const [formData, setFormData] = useState({
    name: '',
    address: '',
    latitude: 10.7769,
    longitude: 106.7009,
    type: 'VISIT',
    legId: '',
    note: '',
    expenseAmount: '',
    expenseCategory: 'OTHER',
    expenseDescription: '',
    expenseNote: '',
    paidById: '',
    plannedStart: '',
    plannedEnd: ''
  });
  const [isLoading, setIsLoading] = useState(false);
  
  // Gom các selector lại để giảm số lượng Hook gọi nội bộ và tăng hiệu năng
  const { legs, addLocation, updateLocation, mapCenter, currentTour } = useTourStore();

  // 1. Luôn khai báo Hook ở cấp cao nhất, không đặt code logic/return giữa các Hook
  useEffect(() => {
    if (isOpen) {
      if (editingLocation) {
        const leg = legs.find(l => l.id === editingLocation.legId);
        const expense = leg?.expenses?.find((e: any) => e.locationId === editingLocation.id);

        setFormData({
          name: editingLocation.name || '',
          address: editingLocation.address || '',
          latitude: editingLocation.latitude,
          longitude: editingLocation.longitude,
          type: editingLocation.type || 'VISIT',
          legId: editingLocation.legId || '',
          note: editingLocation.note || '',
          expenseAmount: expense?.amount?.toString() || '',
          expenseCategory: expense?.category || 'OTHER',
          expenseDescription: expense?.description || '',
          expenseNote: expense?.note || '',
          paidById: expense?.paidById || '',
          plannedStart: editingLocation.plannedStart ? editingLocation.plannedStart.slice(0, 16) : '',
          plannedEnd: editingLocation.plannedEnd ? editingLocation.plannedEnd.slice(0, 16) : ''
        });
      } else {
        setFormData(prev => ({ 
          ...prev, 
          name: '', address: '', 
          legId: initialLegId || (legs.length > 0 ? legs[0].id : ''),
          note: '', expenseAmount: '', expenseCategory: 'OTHER',
          expenseDescription: '', expenseNote: '', paidById: '',
          plannedStart: '', plannedEnd: '' 
        }));
      }
    }
  }, [initialLegId, editingLocation, isOpen]);

  useEffect(() => {
    if (isOpen && !formData.name) {
      setFormData(prev => ({ ...prev, latitude: mapCenter[0], longitude: mapCenter[1] }));
    }
  }, [isOpen, mapCenter]);

  // 2. Thực hiện các tính toán và hàm xử lý
  const currentLegId = formData.legId || (legs.length > 0 ? legs[0].id : '');
  const targetLeg = legs.find(l => l.id === currentLegId);
  const titleText = editingLocation ? `Sửa địa điểm: ${editingLocation.name}` : (initialLegId ? `Thêm địa điểm cho ${targetLeg?.note || `Chặng ${targetLeg?.sequence}`}` : 'Thêm địa điểm mới');
  const buttonText = editingLocation ? 'Cập nhật thay đổi' : (initialLegId ? 'Xác nhận thêm vào chặng' : 'Thêm địa điểm');

  const handlePickLocation = async (latlng: L.LatLng) => {
    setFormData(prev => ({ ...prev, latitude: latlng.lat, longitude: latlng.lng }));
    
    // Tự động lấy tên địa điểm từ tọa độ vừa chọn
    try {
      const res = await fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latlng.lat}&lon=${latlng.lng}`);
      const data = await res.json();
      const addr = data.address;
      const detectedName = addr.amenity || addr.building || addr.historic || addr.tourist || 
                    addr.shop || addr.office || addr.leisure || addr.attraction ||
                    addr.road || addr.neighbourhood || addr.suburb || 
                    data.display_name?.split(',')[0] || "";
      
      setFormData(prev => ({ ...prev, name: detectedName || prev.name, address: data.display_name || prev.address }));
    } catch (e) {}
  };

  // 3. Early return phải nằm SAU tất cả các khai báo Hook
  if (!isOpen) return null;

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const payload: any = {
        ...formData,
        legId: currentLegId,
        latitude: parseFloat(formData.latitude as any),
        longitude: parseFloat(formData.longitude as any),
      };

      if (editingLocation) {
        await updateLocation(editingLocation.id, payload);
      } else {
        await addLocation(tourId, payload);
      }
      onClose();
    } catch (error) {
      alert('Lỗi khi lưu địa điểm');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[2000] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-gray-900/60 backdrop-blur-sm" onClick={onClose} />
      <div className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl overflow-hidden p-8 max-h-[90vh] overflow-y-auto">
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <MapIcon className="w-6 h-6 text-blue-600" /> {titleText}
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
            <X className="w-6 h-6 text-gray-400" />
          </button>
        </div>

        {/* Mini Map Picker */}
        <div className="h-48 w-full rounded-2xl overflow-hidden mb-6 border border-gray-100 relative shadow-inner group">
          <MapContainer center={[formData.latitude, formData.longitude]} zoom={13} className="h-full w-full">
            <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
            <Marker position={[formData.latitude, formData.longitude]} />
            <MapPicker center={[formData.latitude, formData.longitude]} onPick={handlePickLocation} />
          </MapContainer>
          <div className="absolute bottom-2 left-2 z-[1000] bg-white/90 backdrop-blur-sm px-2 py-1 rounded-lg text-[10px] font-black text-gray-500 shadow-sm border border-gray-100">
            CHUỘT PHẢI ĐỂ CHỌN VỊ TRÍ
          </div>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Tên địa điểm</label>
            <input required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none" 
              value={formData.name} onChange={e => setFormData({...formData, name: e.target.value})} />
          </div>
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Địa chỉ</label>
            <input className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none" 
              value={formData.address} onChange={e => setFormData({...formData, address: e.target.value})} />
          </div>
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Ghi chú địa điểm / Dịch vụ sử dụng</label>
            <textarea className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none resize-none" rows={2}
              placeholder="Ví dụ: Ăn trưa tại quán X, thuê hướng dẫn viên..."
              value={formData.note} onChange={e => setFormData({...formData, note: e.target.value})} />
          </div>
          <div className="bg-blue-50/60 border border-blue-100 rounded-2xl p-4 space-y-3">
            <p className="text-xs font-black text-blue-500 uppercase tracking-widest">Chi phí nhanh tại điểm này</p>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-bold text-gray-600 mb-1">Số tiền (VNĐ)</label>
                <input type="number" className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl outline-none text-sm" 
                  placeholder="0"
                  value={formData.expenseAmount} onChange={e => setFormData({...formData, expenseAmount: e.target.value})} />
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-600 mb-1">Loại dịch vụ</label>
                <select className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl outline-none text-sm" 
                  value={formData.expenseCategory} onChange={e => setFormData({...formData, expenseCategory: e.target.value})}>
                  <option value="FOOD">Ăn uống</option>
                  <option value="TRANSPORT">Di chuyển</option>
                  <option value="ACCOMMODATION">Chỗ ở</option>
                  <option value="TICKET">Vé tham quan</option>
                  <option value="OTHER">Khác</option>
                </select>
              </div>
            </div>
            <div>
              <label className="block text-xs font-bold text-gray-600 mb-1">Dịch vụ / Mô tả</label>
              <input className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl outline-none text-sm" 
                placeholder="Ví dụ: Ăn trưa, taxi, vé..."
                value={formData.expenseDescription} onChange={e => setFormData({...formData, expenseDescription: e.target.value})} />
            </div>
            <div>
              <label className="block text-xs font-bold text-gray-600 mb-1">Ghi chú chi phí</label>
              <textarea className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl outline-none resize-none text-sm" rows={2}
                placeholder="Ghi chú thêm..."
                value={formData.expenseNote} onChange={e => setFormData({...formData, expenseNote: e.target.value})} />
            </div>
            <div>
              <label className="block text-xs font-bold text-gray-600 mb-1">Thành viên đã thanh toán</label>
               <select className="w-full px-3 py-2 bg-white border border-gray-200 rounded-xl outline-none text-sm" 
                 value={formData.paidById} onChange={e => setFormData({...formData, paidById: e.target.value})}>
                 <option value="">-- Chọn người thanh toán --</option>
                 {currentTour?.participants?.map((p: any) => {
                   const name = p.user?.name;
                   const email = p.user?.email;
                   const label = [name, email && name ? `(${email})` : email].filter(Boolean).join(' ');
                   return (
                   <option key={p.userId} value={p.userId}>{label || p.userId}</option>
                   );
                 })}
               </select>
            </div>
          </div>
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Gán vào chặng</label>
            <select required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none"
              value={currentLegId} onChange={e => setFormData({...formData, legId: e.target.value})}>
              {legs.map(leg => (
                <option key={leg.id} value={leg.id}>Chặng {leg.sequence}: {leg.note || 'Không có tên'}</option>
              ))}
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">Vĩ độ</label>
              <input type="number" step="any" required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none" 
                value={formData.latitude} onChange={e => setFormData({...formData, latitude: e.target.value as any})} />
            </div>
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">Kinh độ</label>
              <input type="number" step="any" required className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none" 
                value={formData.longitude} onChange={e => setFormData({...formData, longitude: e.target.value as any})} />
            </div>
          </div>
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-1">Loại</label>
            <select className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none" 
              value={formData.type} onChange={e => setFormData({...formData, type: e.target.value as any})}>
              <option value="VISIT">Tham quan</option>
              <option value="EAT">Ăn uống</option>
              <option value="REST">Nghỉ ngơi</option>
              <option value="MOVE">Di chuyển</option>
            </select>
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-bold text-gray-700 mb-1">Bắt đầu</label>
              <input type="datetime-local" className="w-full px-4 py-3 bg-gray-50 border border-gray-100 rounded-xl outline-none" 
                value={formData.plannedStart} onChange={e => setFormData({...formData, plannedStart: e.target.value})} />
            </div>
          </div>
          <button disabled={isLoading} className="w-full py-4 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-2xl flex items-center justify-center gap-2 mt-4">
            {isLoading ? <Loader2 className="w-5 h-5 animate-spin" /> : buttonText}
          </button>
        </form>
      </div>
    </div>
  );
};