import { useEffect, useState, useMemo } from 'react';
import { ChevronLeft, Image as ImageIcon, Download, Calendar, MapPin, Loader2, Filter, X, Trash2, Edit, Heart } from 'lucide-react';
import { useNotification } from '@/hooks/useNotification';
import { useConfirm } from '@/hooks/useConfirm';
import { CoordinateSelectModal } from '../components/CoordinateSelectModal';

const getMostLikedPhoto = (photos: any[]) => {
  if (!photos || photos.length === 0) return null;
  return [...photos].sort((a, b) => {
    const likesA = a.metadata?.likedUserIds?.length || 0;
    const likesB = b.metadata?.likedUserIds?.length || 0;
    return likesB - likesA;
  })[0];
};

export const MyPhotosPage = ({ onBack }: { onBack: () => void }) => {
  const [photos, setPhotos] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedTourIdForPhoto, setSelectedTourIdForPhoto] = useState<string | 'all'>('all');
  const [filterDate, setFilterDate] = useState<string>('');
  const [selectedPhotoForDisplay, setSelectedPhotoForDisplay] = useState<any | null>(null);
  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest'>('newest');
  const notify = useNotification();
  const confirm = useConfirm();

  const [isEditing, setIsEditing] = useState(false);
  const [editTitle, setEditTitle] = useState('');
  const [editDescription, setEditDescription] = useState('');
  const [editLat, setEditLat] = useState<number | ''>('');
  const [editLng, setEditLng] = useState<number | ''>('');
  const [isSavingEdit, setIsSavingEdit] = useState(false);
  const [isMapOpen, setIsMapOpen] = useState(false);
  const [resolvedAddress, setResolvedAddress] = useState<string>('');
  const [isFullscreen, setIsFullscreen] = useState(false);

  useEffect(() => {
    const lat = selectedPhotoForDisplay?.metadata?.lat;
    const lng = selectedPhotoForDisplay?.metadata?.lng;
    if (typeof lat === 'number' && typeof lng === 'number') {
      setResolvedAddress('Đang xác định địa điểm...');
      fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lng}&accept-language=vi`)
        .then(res => {
          if (!res.ok) throw new Error();
          return res.json();
        })
        .then(data => {
          if (data && data.display_name) {
            const shortAddress = data.display_name.split(',').slice(0, 3).join(',').trim();
            setResolvedAddress(shortAddress || data.display_name);
          } else {
            setResolvedAddress(`${lat.toFixed(4)}, ${lng.toFixed(4)}`);
          }
        })
        .catch(() => {
          setResolvedAddress(`${lat.toFixed(4)}, ${lng.toFixed(4)}`);
        });
    } else {
      setResolvedAddress('Chưa xác định tọa độ');
    }
  }, [selectedPhotoForDisplay?.id, selectedPhotoForDisplay?.metadata?.lat, selectedPhotoForDisplay?.metadata?.lng]);

  useEffect(() => {
    if (selectedPhotoForDisplay) {
      setEditTitle(selectedPhotoForDisplay.metadata?.title || '');
      setEditDescription(selectedPhotoForDisplay.metadata?.description || '');
      setEditLat(selectedPhotoForDisplay.metadata?.lat ?? '');
      setEditLng(selectedPhotoForDisplay.metadata?.lng ?? '');
      setIsEditing(false);
    }
  }, [selectedPhotoForDisplay]);

  const handleSaveEdit = async () => {
    if (editLat !== '' && (isNaN(editLat) || editLat < -90 || editLat > 90)) {
      notify({ title: 'Lỗi', message: 'Vĩ độ không hợp lệ (-90 đến 90).', type: 'error' });
      return;
    }
    if (editLng !== '' && (isNaN(editLng) || editLng < -180 || editLng > 180)) {
      notify({ title: 'Lỗi', message: 'Kinh độ không hợp lệ (-180 đến 180).', type: 'error' });
      return;
    }

    setIsSavingEdit(true);
    try {
      const response = await fetch(`/api/v1/photos/${selectedPhotoForDisplay.id}`, {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token') || localStorage.getItem('guest_token')}`
        },
        body: JSON.stringify({
          title: editTitle,
          description: editDescription,
          latitude: editLat === '' ? undefined : editLat,
          longitude: editLng === '' ? undefined : editLng
        })
      });

      if (!response.ok) throw new Error('Failed to update photo info');

      const updatedPhoto = await response.json();
      notify({ title: 'Thành công', message: 'Thông tin ảnh đã được cập nhật.', type: 'success' });
      
      setPhotos(prev => prev.map(p => p.id === updatedPhoto.id ? { ...p, metadata: updatedPhoto.metadata } : p));
      setSelectedPhotoForDisplay((prev: any) => prev ? ({ ...prev, metadata: updatedPhoto.metadata }) : null);
      setIsEditing(false);
    } catch (error) {
      notify({ title: 'Lỗi', message: 'Không thể cập nhật thông tin ảnh. Vui lòng thử lại.', type: 'error' });
    } finally {
      setIsSavingEdit(false);
    }
  };

  const currentUser = useMemo(() => {
    const userStr = localStorage.getItem('user') || localStorage.getItem('guest_user');
    if (!userStr) return null;
    try {
      return JSON.parse(userStr);
    } catch (e) {
      return null;
    }
  }, []);

  const likedUserIds = selectedPhotoForDisplay && selectedPhotoForDisplay.metadata && Array.isArray(selectedPhotoForDisplay.metadata.likedUserIds)
    ? selectedPhotoForDisplay.metadata.likedUserIds
    : [];
  const isLiked = currentUser && likedUserIds.includes(currentUser.id);
  const likeCount = likedUserIds.length;

  const handleToggleLike = async () => {
    if (!selectedPhotoForDisplay) return;
    const token = localStorage.getItem('token') || localStorage.getItem('guest_token');
    if (!token) return;

    try {
      const response = await fetch(`/api/v1/photos/${selectedPhotoForDisplay.id}/toggle-like`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      if (response.ok) {
        const updatedPhoto = await response.json();
        setPhotos(prev => prev.map(p => p.id === updatedPhoto.id ? { ...p, metadata: updatedPhoto.metadata } : p));
        setSelectedPhotoForDisplay((prev: any) => prev ? ({ ...prev, metadata: updatedPhoto.metadata }) : null);
      }
    } catch (error) {
      console.error('Lỗi khi thích ảnh:', error);
    }
  };

  useEffect(() => {
    const fetchPhotos = async () => {
      try {
        const response = await fetch('/api/v1/users/me/photos', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token') || localStorage.getItem('guest_token')}`
          }
        });
        if (!response.ok) throw new Error('Failed to fetch photos');
        const data = await response.json();
        setPhotos(data);
      } catch (error) {
        notify({ title: 'Lỗi', message: 'Không thể tải danh sách ảnh.', type: 'error' });
      } finally {
        setIsLoading(false);
      }
    };
    fetchPhotos();
  }, []);

  const toursWithPhotos = useMemo(() => {
    const tourMap = new Map();
    photos.forEach(p => {
      if (p.tourId && p.tour) {
        tourMap.set(p.tourId, { id: p.tourId, title: p.tour.title });
      }
    });
    return Array.from(tourMap.values());
  }, [photos]);

  const filteredPhotos = useMemo(() => {
    let photosToFilter = photos.filter(p => {
      const matchTour = selectedTourIdForPhoto === 'all' || p.tourId === selectedTourIdForPhoto;
      const photoDate = p.capturedAt ? p.capturedAt.split('T')[0] : '';
      const matchDate = !filterDate || photoDate === filterDate;
      return matchTour && matchDate;
    });
    let sortedPhotos = photosToFilter;
    if (sortOrder === 'newest') {
      sortedPhotos.sort((a, b) => new Date(b.capturedAt).getTime() - new Date(a.capturedAt).getTime());
    } else {
      sortedPhotos.sort((a, b) => new Date(a.capturedAt).getTime() - new Date(b.capturedAt).getTime());
    }
    return sortedPhotos;
  }, [photos, selectedTourIdForPhoto, filterDate, sortOrder]);

  useEffect(() => {
    if (filteredPhotos.length > 0 && (!selectedPhotoForDisplay || !filteredPhotos.some(p => p.id === selectedPhotoForDisplay.id))) {
      setSelectedPhotoForDisplay(getMostLikedPhoto(filteredPhotos));
    } else if (filteredPhotos.length === 0) {
      setSelectedPhotoForDisplay(null);
    }
  }, [filteredPhotos, selectedPhotoForDisplay]);

  const handleDeletePhoto = async (photoId: string) => {
    const isConfirmed = await confirm({
      title: 'Xóa ảnh này?',
      message: 'Bạn có chắc chắn muốn xóa ảnh này không? Hành động này không thể hoàn tác.'
    });

    if (!isConfirmed) return;

    try {
      const response = await fetch(`/api/v1/photos/${photoId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token') || localStorage.getItem('guest_token')}`
        }
      });

      if (!response.ok) throw new Error('Failed to delete photo');

      notify({ title: 'Thành công', message: 'Ảnh đã được xóa.', type: 'success' });
      setPhotos(prev => prev.filter(p => p.id !== photoId));
      setSelectedPhotoForDisplay(null);
    } catch (error) {
      notify({ title: 'Lỗi', message: 'Không thể xóa ảnh. Vui lòng thử lại.', type: 'error' });
    }
  };

  return (
    <div className="w-full flex flex-col text-slate-100 bg-transparent font-sans min-h-dvh overflow-x-hidden">
      {/* Header */}
      <div className="bg-slate-900/60 backdrop-blur-md border-b border-slate-800/80 px-4 py-3 flex items-center gap-3 rounded-t-3xl">
        <button onClick={onBack} className="p-2 hover:bg-slate-800 rounded-full transition-colors">
          <ChevronLeft className="w-5 h-5 text-slate-400 hover:text-white" />
        </button>
        <div>
          <h1 className="text-lg font-black text-white">Ảnh của tôi</h1>
          <p className="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Kho lưu trữ ảnh gốc cá nhân</p>
        </div>
      </div>

      {/* Filter Bar */}
      <div className="bg-slate-900/40 border-b border-slate-800/60 px-4 py-3 flex flex-wrap items-center gap-3 shadow-sm">
        <div className="flex items-center gap-2 text-slate-400">
          <Filter className="w-4 h-4" />
          <span className="text-xs font-bold uppercase tracking-wider">Bộ lọc:</span>
        </div>
        
        <div className="relative min-w-[120px] sm:min-w-[150px]">
          <div className="px-3 py-2 bg-slate-800 text-indigo-300 rounded-xl text-xs font-bold border border-slate-700/60 truncate max-w-[180px] sm:max-w-[200px]">
            {selectedTourIdForPhoto === 'all' ? 'Tất cả hành trình' : toursWithPhotos.find(t => t.id === selectedTourIdForPhoto)?.title || 'Tour đã chọn'}
          </div>
        </div>

        <div className="relative">
          <input
            type="date"
            value={filterDate}
            onChange={(e) => setFilterDate(e.target.value)}
            className="pl-3 pr-3 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-indigo-500/80 transition-all text-slate-200 cursor-pointer"
          />
        </div>

        <div className="relative min-w-[120px]">
          <select
            value={sortOrder}
            onChange={(e) => setSortOrder(e.target.value as 'newest' | 'oldest')}
            className="w-full pl-3 pr-8 py-2 bg-slate-950 border border-slate-800 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-indigo-500/80 transition-all appearance-none cursor-pointer text-slate-200"
          >
            <option value="newest">Mới nhất</option>
            <option value="oldest">Cũ nhất</option>
          </select>
          <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-slate-500">
            <ChevronLeft className="w-3 h-3 -rotate-90" />
          </div>
        </div>

        {(selectedTourIdForPhoto !== 'all' || filterDate) && (
          <button
            onClick={() => { setSelectedTourIdForPhoto('all'); setFilterDate(''); }}
            className="flex items-center gap-1.5 px-3 py-2 text-xs font-bold text-rose-400 hover:bg-rose-950/20 rounded-xl transition-all"
          >
            <X className="w-3.5 h-3.5" />
            Xóa lọc
          </button>
        )}

        <div className="ml-auto">
          <p className="text-[10px] font-black text-slate-400 uppercase tracking-tighter">
            Kết quả: <span className="text-indigo-400">{filteredPhotos.length}</span> / {photos.length} ảnh
          </p>
        </div>
      </div>

      <div className="flex-1 p-4 sm:p-6 w-full max-w-7xl mx-auto">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-16 sm:py-20 text-slate-400">
            <Loader2 className="w-8 h-8 sm:w-10 sm:h-10 animate-spin mb-3 sm:mb-4 text-indigo-500" />
            <p className="font-bold text-xs sm:text-sm">Đang tải kho ảnh...</p>
          </div>
        ) : photos.length === 0 ? (
          <div className="py-16 sm:py-24 text-center bg-slate-900/30 rounded-[32px] sm:rounded-[40px] border-2 border-dashed border-slate-800/80">
            <ImageIcon className="w-12 h-12 sm:w-16 sm:h-16 text-slate-700 mx-auto mb-3 sm:mb-4" />
            <h3 className="text-lg sm:text-xl font-bold text-slate-400">Chưa có ảnh nào</h3>
            <p className="text-xs sm:text-sm text-slate-500">Hãy tham gia các chuyến đi và lưu lại khoảnh khắc nhé!</p>
          </div>
        ) : ( 
          <div className="animate-in fade-in">
            <div className="flex flex-col md:flex-row gap-4 sm:gap-6">
              {/* Left Column: Tour List */}
              <div className="w-full md:w-1/4 bg-slate-900/50 rounded-2xl border border-slate-800/60 p-3 sm:p-4 flex-shrink-0">
                <h3 className="text-[10px] sm:text-xs font-black uppercase text-slate-400 tracking-wider mb-2 sm:mb-3">Hành trình của bạn</h3>
                <div className="space-y-1.5 sm:space-y-2">
                  <button
                    onClick={() => { setSelectedTourIdForPhoto('all'); setSelectedPhotoForDisplay(null); }}
                    className={`w-full text-left px-3 py-2 sm:px-3.5 sm:py-2.5 rounded-xl text-[10px] sm:text-xs font-bold transition-all ${
                      selectedTourIdForPhoto === 'all' ? 'bg-indigo-650 text-white shadow-md' : 'bg-slate-800/60 text-slate-300 hover:bg-slate-800'
                    }`}
                  >
                    Tất cả ảnh
                  </button>
                  {toursWithPhotos.map(tour => (
                    <button
                      key={tour.id}
                      onClick={() => { setSelectedTourIdForPhoto(tour.id); setSelectedPhotoForDisplay(null); }}
                      className={`w-full text-left px-3 py-2 sm:px-3.5 sm:py-2.5 rounded-xl text-[10px] sm:text-xs font-bold transition-all truncate ${
                        selectedTourIdForPhoto === tour.id ? 'bg-indigo-650 text-white shadow-md' : 'bg-slate-800/60 text-slate-300 hover:bg-slate-800'
                      }`}
                      title={tour.title}
                    >
                      {tour.title}
                    </button>
                  ))}
                </div>
              </div>

              {/* Right Column: Large Photo Display */}
              <div className="w-full md:flex-1 bg-slate-900/50 rounded-2xl border border-slate-800/60 p-3 sm:p-4 flex flex-col items-center justify-center min-h-[250px] sm:min-h-[350px]">
                {selectedPhotoForDisplay ? (
                  <div className="relative w-full h-full flex flex-col items-center justify-center">
                    <div className="relative overflow-hidden rounded-xl shadow-lg max-w-full max-h-[calc(100vh-280px)] sm:max-h-[calc(100vh-320px)] group">
                      <img
                        src={selectedPhotoForDisplay.imageUrl || selectedPhotoForDisplay.originalUrl}
                        alt="Selected"
                        className="max-w-full max-h-[calc(100vh-280px)] sm:max-h-[calc(100vh-320px)] object-contain cursor-zoom-in"
                        onClick={() => setIsFullscreen(true)}
                      />
                      
                      {!isEditing && (
                        <>
                          {/* Like Button */}
                          <button
                            onClick={handleToggleLike}
                            className="absolute top-4 left-4 z-10 flex items-center gap-1.5 bg-slate-950/80 hover:bg-slate-950 border border-slate-800/60 text-white font-bold py-1.5 px-3 rounded-full transition-all active:scale-95 text-[11px] backdrop-blur-md"
                            title={isLiked ? "Bỏ thích" : "Thích"}
                          >
                            <Heart className={`w-4 h-4 transition-colors ${
                              isLiked ? 'text-rose-500 fill-rose-500' : 'text-[var(--text-muted)]'
                            }`} />
                            <span>{likeCount}</span>
                          </button>

                          {/* Delete Button */}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              handleDeletePhoto(selectedPhotoForDisplay.id);
                            }}
                            className="absolute top-4 right-4 z-10 p-2 bg-slate-950/80 hover:bg-rose-650 border border-slate-800/60 text-white rounded-full transition-all active:scale-95 backdrop-blur-md"
                            title="Xóa ảnh này"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>

                          {/* Metadata Overlay */}
                          <div className="absolute bottom-0 inset-x-0 bg-gradient-to-t from-slate-950 via-slate-950/45 to-transparent p-6 text-white flex flex-col gap-2 text-left">
                            <div className="flex justify-between items-start gap-4">
                              <div className="flex-1 min-w-0">
                                {selectedPhotoForDisplay.metadata?.title ? (
                                  <h3 className="text-sm font-extrabold text-white break-words drop-shadow-md">
                                    {selectedPhotoForDisplay.metadata.title}
                                  </h3>
                                ) : (
                                  <span className="text-xs text-slate-400 italic block mb-1">Chưa có tiêu đề</span>
                                )}
                                {selectedPhotoForDisplay.metadata?.description ? (
                                  <p className="text-xs text-slate-300 leading-relaxed mt-1 break-words max-h-16 overflow-y-auto no-scrollbar">
                                    {selectedPhotoForDisplay.metadata.description}
                                  </p>
                                ) : (
                                  <span className="text-[11px] text-slate-400 italic block mt-1">Chưa có mô tả</span>
                                )}
                              </div>
                              
                              <button
                                onClick={() => setIsEditing(true)}
                                className="p-2 bg-slate-800 hover:bg-slate-800 border border-slate-700/50 rounded-xl text-white transition-all shrink-0"
                                title="Chỉnh sửa thông tin"
                              >
                                <Edit className="w-4 h-4 text-indigo-400" />
                              </button>
                            </div>

                            <div className="flex flex-wrap items-center justify-between gap-4 border-t border-slate-800/80 pt-3 text-xs text-slate-300">
                              <div className="space-y-1">
                                <div className="flex items-center gap-2 text-slate-450 text-[10px] font-bold uppercase tracking-wider">
                                  <Calendar className="w-3.5 h-3.5 text-indigo-450" />
                                  Ngày chụp: {new Date(selectedPhotoForDisplay.capturedAt).toLocaleDateString('vi-VN')}
                                </div>
                                <div className="flex items-center gap-2 font-bold text-slate-205">
                                  <MapPin className="w-3.5 h-3.5 text-rose-500" />
                                  Địa điểm: {resolvedAddress}
                                </div>
                                {selectedPhotoForDisplay.tour?.title && (
                                  <div className="text-[10px] text-slate-400">
                                    Hành trình: {selectedPhotoForDisplay.tour.title}
                                  </div>
                                )}
                              </div>
                              
                              {selectedPhotoForDisplay.originalUrl && (
                                <a 
                                  href={selectedPhotoForDisplay.originalUrl} 
                                  download 
                                  className="flex items-center gap-2 px-3.5 py-2 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-bold uppercase tracking-wider text-[9px] transition-all shadow-md active:scale-95 shrink-0"
                                >
                                  <Download className="w-3.5 h-3.5" /> Tải ảnh gốc
                                </a>
                              )}
                            </div>
                          </div>
                        </>
                      )}
                    </div>

                    {isEditing && (
                      <div className="mt-6 w-full flex flex-col gap-4 px-2">
                        <div className="space-y-3 bg-slate-950/40 border border-slate-800/80 p-4 rounded-2xl w-full">
                          <h4 className="text-xs font-black uppercase tracking-wider text-indigo-400">Chỉnh sửa thông tin ảnh</h4>
                          
                          <div className="space-y-2">
                            <div>
                              <label className="block text-[10px] uppercase font-bold tracking-wider text-slate-450 mb-1">Tiêu đề</label>
                              <input
                                type="text"
                                value={editTitle}
                                onChange={(e) => setEditTitle(e.target.value)}
                                placeholder="Nhập tiêu đề..."
                                className="w-full bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-indigo-500"
                              />
                            </div>

                            <div>
                              <label className="block text-[10px] uppercase font-bold tracking-wider text-slate-455 mb-1">Mô tả</label>
                              <textarea
                                value={editDescription}
                                onChange={(e) => setEditDescription(e.target.value)}
                                placeholder="Nhập mô tả..."
                                rows={2}
                                className="w-full bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-xs focus:outline-none focus:ring-1 focus:ring-indigo-500 resize-none"
                              />
                            </div>

                            <div className="grid grid-cols-2 gap-2">
                              <div>
                                <label className="block text-[10px] uppercase font-bold tracking-wider text-slate-455 mb-1">Vĩ độ</label>
                                <input
                                  type="number"
                                  step="any"
                                  value={editLat}
                                  onChange={(e) => setEditLat(e.target.value === '' ? '' : parseFloat(e.target.value))}
                                  placeholder="Vĩ độ..."
                                  className="w-full bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-xs focus:outline-none"
                                />
                              </div>
                              <div>
                                <label className="block text-[10px] uppercase font-bold tracking-wider text-slate-455 mb-1">Kinh độ</label>
                                <input
                                  type="number"
                                  step="any"
                                  value={editLng}
                                  onChange={(e) => setEditLng(e.target.value === '' ? '' : parseFloat(e.target.value))}
                                  placeholder="Kinh độ..."
                                  className="w-full bg-slate-950 border border-slate-800 text-white rounded-xl px-3 py-2 text-xs focus:outline-none"
                                />
                              </div>
                            </div>
                          </div>

                          <div className="flex justify-start">
                            <button
                              type="button"
                              onClick={() => setIsMapOpen(true)}
                              className="flex items-center gap-1.5 px-3 py-1.5 bg-slate-800 hover:bg-slate-700 border border-slate-700 text-slate-200 rounded-xl text-[10px] font-bold transition-all"
                            >
                              <MapPin className="w-3.5 h-3.5 text-rose-500" />
                              Chọn trên bản đồ
                            </button>
                          </div>

                          <div className="flex justify-end gap-2 mt-2">
                            <button
                              onClick={() => setIsEditing(false)}
                              disabled={isSavingEdit}
                              className="px-3 py-1.5 bg-slate-800 hover:bg-slate-750 text-slate-300 rounded-lg text-xs font-bold transition-all"
                            >
                              Hủy
                            </button>
                            <button
                              onClick={handleSaveEdit}
                              disabled={isSavingEdit}
                              className="flex items-center gap-1 px-4 py-1.5 bg-indigo-650 hover:bg-indigo-600 disabled:opacity-50 text-white rounded-lg text-xs font-bold transition-all"
                            >
                              {isSavingEdit ? (
                                <>
                                  <Loader2 className="w-3.5 h-3.5 animate-spin" />
                                  Đang lưu...
                                </>
                              ) : (
                                'Lưu lại'
                              )}
                            </button>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="text-center text-slate-500 py-20">
                    <ImageIcon className="w-16 h-16 mx-auto mb-4 opacity-20" />
                    <p className="text-base font-bold">Chọn một tấm ảnh để xem</p>
                  </div>
                )}
              </div>
            </div>

            {/* Bottom Row: Thumbnails */}
            <div className="mt-6 bg-slate-900/50 rounded-2xl border border-slate-800/60 p-4">
              <div className="flex items-center justify-between mb-4 px-1">
                <h3 className="text-xs font-black text-slate-400 uppercase tracking-widest">Kho ảnh ({filteredPhotos.length})</h3>
              </div>
              <div className="grid grid-cols-3 xs:grid-cols-4 sm:grid-cols-5 md:grid-cols-7 lg:grid-cols-10 gap-2 sm:gap-3 max-h-[200px] sm:max-h-[250px] overflow-y-auto pr-1 sm:pr-2 custom-scrollbar">
                {filteredPhotos.map((photo: any) => (
                  <div
                    key={photo.id}
                    onClick={() => setSelectedPhotoForDisplay(photo)}
                    className={`aspect-square bg-slate-950 rounded-xl overflow-hidden relative group border-2 transition-all cursor-pointer ${
                      selectedPhotoForDisplay?.id === photo.id ? 'border-indigo-500 scale-[0.98]' : 'border-transparent hover:border-slate-700'
                    }`}
                  >
                    <img
                      src={photo.imageUrl || photo.originalUrl}
                      alt="thumbnail"
                      className="w-full h-full object-cover"
                    />
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
      <CoordinateSelectModal
        isOpen={isMapOpen}
        onClose={() => setIsMapOpen(false)}
        initialLat={typeof editLat === 'number' ? editLat : undefined}
        initialLng={typeof editLng === 'number' ? editLng : undefined}
        onSelect={(lat, lng) => {
          setEditLat(lat);
          setEditLng(lng);
        }}
      />

      {isFullscreen && selectedPhotoForDisplay && (
        <div
          className="fixed inset-0 z-[9999] bg-black/95 flex items-center justify-center cursor-zoom-out animate-in fade-in duration-200"
          onClick={() => setIsFullscreen(false)}
        >
          <button
            onClick={() => setIsFullscreen(false)}
            className="fixed top-6 right-6 p-3 bg-black/50 hover:bg-black/75 border border-white/10 rounded-full text-white transition-colors z-[10000]"
          >
            <X className="w-6 h-6" />
          </button>
          <img
            src={selectedPhotoForDisplay.imageUrl || selectedPhotoForDisplay.originalUrl}
            alt="Fullscreen"
            className="max-w-full max-h-full object-contain select-none animate-in zoom-in-95 duration-200"
          />
        </div>
      )}
    </div>
  );
};