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

export const MyPhotosPage = ({ onBack }: { onBack: () => void }) => {
  const [photos, setPhotos] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [selectedTourIdForPhoto, setSelectedTourIdForPhoto] = useState<string | 'all'>('all'); // Changed from filterTourId
  const [filterDate, setFilterDate] = useState<string>('');
  const [selectedPhotoForDisplay, setSelectedPhotoForDisplay] = useState<any | null>(null); // New state for large photo display
  const [sortOrder, setSortOrder] = useState<'newest' | 'oldest'>('newest'); // 'newest' by default
  const notify = useNotification();
  const confirm = useConfirm();

  useEffect(() => {
    const fetchPhotos = async () => {
      try {
        const response = await fetch('/api/v1/users/me/photos', {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('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();
  }, []);

  // Lấy danh sách các Tour duy nhất để hiển thị trong bộ lọc
  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]);

  // Logic lọc ảnh tại Frontend
  const filteredPhotos = useMemo(() => {
    let photosToFilter = photos.filter(p => {
      const matchTour = selectedTourIdForPhoto === 'all' || p.tourId === selectedTourIdForPhoto;
      // So sánh ngày định dạng YYYY-MM-DD
      const photoDate = p.capturedAt ? p.capturedAt.split('T')[0] : '';
      const matchDate = !filterDate || photoDate === filterDate;
      return matchTour && matchDate;
    });
    let sortedPhotos = photosToFilter;
    // Sắp xếp ảnh
    if (sortOrder === 'newest') {
      sortedPhotos.sort((a, b) => new Date(b.capturedAt).getTime() - new Date(a.capturedAt).getTime());
    } else { // 'oldest'
      sortedPhotos.sort((a, b) => new Date(a.capturedAt).getTime() - new Date(b.capturedAt).getTime());
    }
    return sortedPhotos;
  }, [photos, selectedTourIdForPhoto, filterDate, sortOrder]);

  // Effect để thiết lập ảnh được chọn hiển thị hoặc reset nếu ảnh hiện tại không còn trong danh sách lọc
  useEffect(() => {
    if (filteredPhotos.length > 0 && (!selectedPhotoForDisplay || !filteredPhotos.some(p => p.id === selectedPhotoForDisplay.id))) {
      setSelectedPhotoForDisplay(filteredPhotos[0]);
    } else if (filteredPhotos.length === 0) {
      setSelectedPhotoForDisplay(null);
    } else if (selectedPhotoForDisplay) {
      // Nếu ảnh đang chọn vẫn còn trong danh sách lọc, không làm gì cả
    } else {
      // Nếu không có ảnh nào để hiển thị
      setSelectedPhotoForDisplay(null); // No photos to display
    }
  }, [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')}`
        }
      });

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

      notify({ title: 'Thành công', message: 'Ảnh đã được xóa.', type: 'success' });
      // Cập nhật lại danh sách ảnh sau khi xóa
      setPhotos(prev => prev.filter(p => p.id !== photoId));
      setSelectedPhotoForDisplay(null); // Reset ảnh đang hiển thị
    } catch (error) {
      notify({ title: 'Lỗi', message: 'Không thể xóa ảnh. Vui lòng thử lại.', type: 'error' });
    }
  };


  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Header */}
      <div className="sticky top-0 z-30 bg-white/80 backdrop-blur-md border-b border-gray-100 px-4 py-4 flex items-center gap-4">
        <button onClick={onBack} className="p-2 hover:bg-gray-100 rounded-full transition-colors">
          <ChevronLeft className="w-6 h-6 text-gray-600" />
        </button>
        <div>
          <h1 className="text-xl font-black text-gray-900">Ảnh của tôi</h1>
          <p className="text-[10px] font-bold text-gray-400 uppercase tracking-widest">Kho lưu trữ ảnh gốc cá nhân</p>
        </div>
      </div>

      {/* Filter Bar - Thanh công cụ lọc */}
      <div className="bg-white border-b border-gray-100 px-6 py-4 flex flex-wrap items-center gap-4 sticky top-[73px] z-20 shadow-sm">
        <div className="flex items-center gap-2 text-gray-500">
          <Filter className="w-4 h-4" />
          <span className="text-xs font-bold uppercase tracking-wider text-gray-400">Bộ lọc:</span>
        </div>
        
        {/* Chỉ báo Tour hiện tại */}
        <div className="relative min-w-[150px]">
          <div className="px-3 py-2 bg-blue-50 text-blue-600 rounded-xl text-xs font-bold border border-blue-100 truncate max-w-[200px]">
            {selectedTourIdForPhoto === 'all' ? 'Tất cả hành trình' : toursWithPhotos.find(t => t.id === selectedTourIdForPhoto)?.title || 'Tour đã chọn'}
          </div>
        </div>

        {/* Lọc theo Thời gian */}
        <div className="relative">
          <input
            type="date"
            value={filterDate}
            onChange={(e) => setFilterDate(e.target.value)}
            className="pl-3 pr-3 py-2 bg-gray-50 border border-gray-100 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-blue-500 transition-all text-gray-700 cursor-pointer"
          />
        </div>

        {/* Lọc theo Sắp xếp */}
        <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-gray-50 border border-gray-100 rounded-xl text-xs font-bold outline-none focus:ring-2 focus:ring-blue-500 transition-all appearance-none cursor-pointer text-gray-700"
          >
            <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-gray-400">
            <ChevronLeft className="w-3 h-3 -rotate-90" />
          </div>
        </div>


        {/* Reset Filters - Nút xóa nhanh lọc */}
        {(selectedTourIdForPhoto !== 'all' || filterDate) && (
          <button
            onClick={() => { setSelectedTourIdForPhoto('all'); setFilterDate(''); }}
            className="flex items-center gap-1.5 px-3 py-2 text-xs font-bold text-red-500 hover:bg-red-50 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-gray-400 uppercase tracking-tighter">
            Kết quả: <span className="text-blue-600">{filteredPhotos.length}</span> / {photos.length} ảnh
          </p>
        </div>
      </div>

      <div className="flex-1 p-6 max-w-5xl mx-auto w-full">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20 text-gray-400">
            <Loader2 className="w-10 h-10 animate-spin mb-4" />
            <p className="font-bold">Đang tải kho ảnh...</p>
          </div>
        ) : ( 
          <div className="animate-in fade-in">
            <div className="flex flex-col md:flex-row gap-4">
              {/* Left Column: Tour List */}
              <div className="md:w-1/4 bg-white rounded-2xl shadow-lg border border-gray-100 p-4 flex-shrink-0">
                <h3 className="text-sm font-bold text-gray-800 mb-3">Tour của bạn</h3>
                <div className="space-y-2">
                  <button
                    onClick={() => { setSelectedTourIdForPhoto('all'); setSelectedPhotoForDisplay(null); }}
                    className={`w-full text-left px-3 py-2 rounded-xl text-xs font-bold transition-all ${
                      selectedTourIdForPhoto === 'all' ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                    }`}
                  >
                    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 rounded-xl text-xs font-bold transition-all ${
                        selectedTourIdForPhoto === tour.id ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
                      }`}
                    >
                      {tour.title}
                    </button>
                  ))}
                </div>
              </div>

              {/* Right Column: Large Photo Display */}
              <div className="md:flex-1 bg-white rounded-2xl shadow-lg border border-gray-100 p-4 flex flex-col items-center justify-center min-h-[300px]">
                {selectedPhotoForDisplay ? (
                  <div className="relative w-full h-full flex flex-col items-center justify-center">
                    <img
                      src={selectedPhotoForDisplay.imageUrl || selectedPhotoForDisplay.originalUrl}
                      alt="Selected Photo"
                      className="max-w-full max-h-[calc(100vh-350px)] object-contain rounded-xl shadow-md"
                    />
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDeletePhoto(selectedPhotoForDisplay.id);
                      }}
                      className="absolute top-4 right-4 p-2 bg-red-500/80 backdrop-blur-sm text-white rounded-full shadow-lg hover:bg-red-600 transition-all active:scale-90"
                      title="Xóa ảnh này"
                    >
                      <Trash2 className="w-5 h-5" />
                    </button>

                    <div className="mt-6 w-full flex items-center justify-between px-2">
                      <div className="space-y-1">
                        <div className="flex items-center gap-2 text-gray-900 font-bold">
                          <MapPin className="w-4 h-4 text-blue-500" />
                          {selectedPhotoForDisplay.tour?.title || 'Không rõ hành trình'}
                        </div>
                        <div className="flex items-center gap-2 text-gray-400 text-xs font-medium uppercase tracking-wider">
                          <Calendar className="w-3.5 h-3.5" />
                          {new Date(selectedPhotoForDisplay.capturedAt).toLocaleDateString('vi-VN', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' })}
                        </div>
                      </div>
                      
                      {selectedPhotoForDisplay.originalUrl && (
                        <a 
                          href={selectedPhotoForDisplay.originalUrl} 
                          download 
                          className="flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-2xl font-black uppercase tracking-widest text-[10px] transition-all shadow-lg shadow-blue-900/20 active:scale-95"
                        >
                          <Download className="w-4 h-4" /> Tải xuống ảnh gốc
                        </a>
                      )}
                    </div>
                  </div>
                ) : (
                  <div className="text-center text-gray-400 py-20">
                    <ImageIcon className="w-16 h-16 mx-auto mb-4 opacity-20" />
                    <p className="text-lg font-bold">Chọn một tấm ảnh để xem</p>
                  </div>
                )}
              </div>
            </div>

            {/* Bottom Row: Thumbnails */}
            <div className="mt-4 bg-white rounded-2xl shadow-lg border border-gray-100 p-4">
              <div className="flex items-center justify-between mb-4 px-1">
                <h3 className="text-xs font-black text-gray-400 uppercase tracking-widest">Kho ảnh ({filteredPhotos.length})</h3>
              </div>
              <div className="grid grid-cols-4 sm:grid-cols-6 md:grid-cols-8 lg:grid-cols-10 gap-3 max-h-[300px] overflow-y-auto pr-2 custom-scrollbar">
                {filteredPhotos.map((photo: any) => (
                  <div
                    key={photo.id}
                    onClick={() => setSelectedPhotoForDisplay(photo)}
                    className={`aspect-square bg-gray-100 rounded-xl overflow-hidden relative group border-2 transition-all cursor-pointer ${
                      selectedPhotoForDisplay?.id === photo.id ? 'border-blue-500 scale-[0.98]' : 'border-transparent hover:border-blue-200'
                    }`}
                  >
                    <img
                      src={photo.imageUrl || photo.originalUrl}
                      alt="thumbnail"
                      className="w-full h-full object-cover"
                    />
                  </div>
                ))}
              </div>
            </div>
          </div>
         ) }
         <div className="h-4"></div>
          <div className="py-32 text-center bg-white rounded-[40px] border-2 border-dashed border-gray-100">
            <ImageIcon className="w-16 h-16 text-gray-200 mx-auto mb-4" />
            <h3 className="text-xl font-bold text-gray-400">Chưa có ảnh nào</h3>
            <p className="text-sm text-gray-300">Hãy tham gia các chuyến đi và lưu lại khoảnh khắc nhé!</p>
          </div>
        {}
      </div>
    </div>
  );
};