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

interface MyPhotosModalProps {
  isOpen: boolean;
  onClose: () => void;
  user: any;
}

export const MyPhotosModal: React.FC<MyPhotosModalProps> = ({
  isOpen,
  onClose,
  user,
}) => {
  const notify = useNotification();

  const [photos, setPhotos] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedPhoto, setSelectedPhoto] = useState<any | null>(null);

  useEffect(() => {
    if (isOpen && user) {
      const loadPhotos = async () => {
        setIsLoading(true);
        try {
          const token = localStorage.getItem('token');
          const res = await fetch('/api/v1/users/me/photos', {
            headers: {
              'Authorization': `Bearer ${token}`,
            },
          });
          if (res.ok) {
            const data = await res.json();
            setPhotos(data);
          } else {
            throw new Error('Không thể tải thư viện ảnh.');
          }
        } catch (e: any) {
          console.error(e);
          notify({
            title: 'Lỗi',
            message: e.message || 'Không thể tải ảnh.',
            type: 'error',
          });
        } finally {
          setIsLoading(false);
        }
      };
      loadPhotos();
    }
  }, [isOpen, user]);

  if (!isOpen || !user) return null;

  const handleDownload = async (url: string, filename: string) => {
    try {
      const response = await fetch(url);
      const blob = await response.blob();
      const blobUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = blobUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(blobUrl);
    } catch (e) {
      console.error(e);
      notify({
        title: 'Lỗi tải về',
        message: 'Không thể tải trực tiếp ảnh xuống thiết bị.',
        type: 'error',
      });
    }
  };

  return (
    <div className="fixed inset-0 z-[1000000] bg-black/70 backdrop-blur-sm flex items-end sm:items-center justify-center p-0 sm:p-4 pointer-events-auto">
      <div className="bg-slate-900 w-full sm:max-w-3xl h-[92vh] sm:h-[80vh] rounded-t-3xl sm:rounded-2xl flex flex-col overflow-hidden text-slate-200 text-xs border border-slate-800/80 shadow-2xl animate-in slide-in-from-bottom sm:zoom-in-95 duration-300">
        
        {/* Header */}
        <div className="px-5 py-4 border-b border-slate-800/60 flex justify-between items-center shrink-0">
          <span className="font-bold text-sm text-white flex items-center gap-2">
            <ImageIcon className="w-5 h-5 text-emerald-400" /> Thư viện ảnh
          </span>
          <button 
            onClick={onClose} 
            className="p-1.5 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded-lg transition-colors cursor-pointer"
          >
            <X className="w-4 h-4" />
          </button>
        </div>

        {/* Content body */}
        <div className="flex-1 overflow-y-auto p-5">
          {isLoading ? (
            <div className="h-full flex items-center justify-center flex-col gap-2 py-20">
              <Loader2 className="w-8 h-8 text-emerald-400 animate-spin" />
              <span className="text-slate-400 font-medium">Đang tải thư viện ảnh của bạn...</span>
            </div>
          ) : photos.length === 0 ? (
            <div className="h-full flex flex-col items-center justify-center text-center py-20 px-6 gap-3">
              <div className="w-16 h-16 bg-slate-850 rounded-full flex items-center justify-center border border-slate-800">
                <ImageIcon className="w-8 h-8 text-slate-500" />
              </div>
              <div>
                <div className="font-bold text-white text-sm">Thư viện ảnh trống</div>
                <p className="text-slate-500 mt-1 max-w-xs mx-auto">Bạn chưa đăng tải bức ảnh nào trong các chuyến đi của mình.</p>
              </div>
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              {photos.map((photo) => {
                const dateStr = photo.capturedAt ? new Date(photo.capturedAt).toLocaleDateString('vi-VN') : '';
                return (
                  <div 
                    key={photo.id}
                    className="group relative aspect-square rounded-2xl overflow-hidden bg-slate-950 border border-slate-850 hover:border-slate-700 shadow-lg transition-all flex flex-col"
                  >
                    <img 
                      src={photo.imageUrl} 
                      alt="Gallery Asset" 
                      className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105" 
                    />
                    
                    {/* Hover controls overlay */}
                    <div className="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 flex flex-col justify-between p-3.5 transition-opacity duration-250 z-10">
                      <div className="flex justify-end gap-1.5">
                        <button
                          onClick={() => setSelectedPhoto(photo)}
                          className="p-2 bg-slate-900/85 hover:bg-indigo-650 text-white rounded-xl transition-colors cursor-pointer"
                          title="Xem phóng to"
                        >
                          <Eye className="w-4 h-4" />
                        </button>
                        <button
                          onClick={() => handleDownload(photo.originalUrl || photo.imageUrl, `yotrip-photo-${photo.id}.jpg`)}
                          className="p-2 bg-slate-900/85 hover:bg-emerald-650 text-white rounded-xl transition-colors cursor-pointer"
                          title="Tải về tệp gốc"
                        >
                          <Download className="w-4 h-4" />
                        </button>
                      </div>
                      
                      <div className="min-w-0">
                        {photo.tour?.title && (
                          <div className="text-[10px] font-bold text-indigo-300 truncate flex items-center gap-1">
                            <MapPin className="w-3 h-3 shrink-0" />
                            {photo.tour.title}
                          </div>
                        )}
                        <div className="text-[9px] text-slate-400 mt-0.5 flex items-center gap-1">
                          <Calendar className="w-3 h-3 shrink-0" />
                          {dateStr}
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

      </div>

      {/* Fullscreen Preview overlay */}
      {selectedPhoto && (
        <div className="fixed inset-0 z-[2000000] bg-black/95 flex flex-col justify-between p-4 pointer-events-auto">
          {/* Close trigger top bar */}
          <div className="flex justify-between items-center w-full pb-3 border-b border-slate-900">
            <div className="text-white font-bold text-xs truncate">
              {selectedPhoto.tour?.title || 'Xem ảnh'}
            </div>
            <button
              onClick={() => setSelectedPhoto(null)}
              className="p-2 bg-slate-900 hover:bg-slate-800 text-slate-400 hover:text-white rounded-xl cursor-pointer"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Fullscreen Photo view */}
          <div className="flex-1 flex items-center justify-center p-4">
            <img 
              src={selectedPhoto.originalUrl || selectedPhoto.imageUrl} 
              alt="Fullscreen Preview" 
              className="max-w-full max-h-[75vh] object-contain rounded-xl shadow-2xl" 
            />
          </div>

          {/* Action bottom bar */}
          <div className="flex justify-center items-center py-4 border-t border-slate-900">
            <button
              onClick={() => handleDownload(selectedPhoto.originalUrl || selectedPhoto.imageUrl, `yotrip-photo-${selectedPhoto.id}.jpg`)}
              className="flex items-center gap-2 px-5 py-3 bg-emerald-650 hover:bg-emerald-600 font-bold text-white rounded-xl shadow-lg transition-all active:scale-95 cursor-pointer"
            >
              <Download className="w-4 h-4" /> Tải về tệp gốc (.jpg)
            </button>
          </div>
        </div>
      )}
    </div>
  );
};
