import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Search, Grid, List, ImageIcon, Download, X, Plus, Save } from 'lucide-react';
import { cn } from '../utils/helpers';
import { fetchRadiologyImages, createRadiologyImage, type APIRadiologyImage } from '../services/medical';
import { format, parseISO } from 'date-fns';
import { DatePickerInput } from '../components/DatePickerInput';
import { useActivePatientId } from '../hooks/useActivePatientId';

export function ImagesPage() {
 const [viewMode, setViewMode] = useState<'grid' | 'list'>('list');
 const [searchTerm, setSearchTerm] = useState('');
 const [images, setImages] = useState<APIRadiologyImage[]>([]);
 const [selectedImage, setSelectedImage] = useState<APIRadiologyImage | null>(null);
 const [loading, setLoading] = useState(true);
 const activePatientId = useActivePatientId();

 // Upload Form States
 const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
 const [uploadForm, setUploadForm] = useState({
   hospital: '',
   explanation: '',
   date: format(new Date(), 'yyyy-MM-dd')
 });
 const [uploadFile, setUploadFile] = useState<File | null>(null);
 const [uploading, setUploading] = useState(false);

 const loadImages = async () => {
   if (!activePatientId) return;
   setLoading(true);
   try {
     const fetched = await fetchRadiologyImages(activePatientId);
     fetched.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
     setImages(fetched);
   } catch (err) {
     console.error("Failed to load images:", err);
   } finally {
     setLoading(false);
   }
 };

 useEffect(() => {
   loadImages();
 }, [activePatientId]);

 const handleUpload = async () => {
   if (!activePatientId) return;
   
   if (!uploadForm.hospital || !uploadForm.explanation || !uploadForm.date) {
     alert("Please fill all required fields.");
     return;
   }

   setUploading(true);
   try {
     const formData = new FormData();
     formData.append('hospital', uploadForm.hospital);
     formData.append('explanation', uploadForm.explanation);
     formData.append('date', uploadForm.date);
     formData.append('patientId', activePatientId);
     if (uploadFile) {
       formData.append('file', uploadFile);
     }

     await createRadiologyImage(formData);
     setIsUploadModalOpen(false);
     setUploadForm({ hospital: '', explanation: '', date: format(new Date(), 'yyyy-MM-dd') });
     setUploadFile(null);
     await loadImages();
   } catch (err) {
     console.error("Upload failed", err);
     alert("Upload failed.");
   } finally {
     setUploading(false);
   }
 };

 const filteredImages = images.filter(img => 
   (img.explanation || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
   (img.hospital || '').toLowerCase().includes(searchTerm.toLowerCase())
 );

 if (loading) {
    return (
      <div className="flex items-center justify-center py-32">
        <div className="animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full" />
      </div>
    );
 }

 return (
  <div className="pb-20">
   <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8 gap-4">
    <div>
     <h1 className="text-2xl font-semibold text-gray-900">My Imaging Data</h1>
     <p className="text-gray-500 text-sm mt-1">View your existing radiological scans and imaging data</p>
    </div>

    <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
     <div className="bg-gray-100 p-1 rounded-lg flex shrink-0">
      <button
       onClick={() => setViewMode('grid')}
       className={cn("p-2 rounded-md transition-all", viewMode === 'grid' ? "bg-white shadow-sm text-gray-900" : "text-gray-400 hover:text-gray-600")}
       title="Grid View"
      >
       <Grid className="w-4 h-4" />
      </button>
      <button
       onClick={() => setViewMode('list')}
       className={cn("p-2 rounded-md transition-all", viewMode === 'list' ? "bg-white shadow-sm text-gray-900" : "text-gray-400 hover:text-gray-600")}
       title="List View"
      >
       <List className="w-4 h-4" />
      </button>
     </div>

     <div className="relative flex-1 md:w-64">
      <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-4 h-4" />
      <input
       type="text"
       placeholder="Search scans..."
       className="pl-10 pr-4 py-2 w-full bg-white border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 transition-all"
       value={searchTerm}
       onChange={(e) => setSearchTerm(e.target.value)}
      />
     </div>
     
     <button
        onClick={() => setIsUploadModalOpen(true)}
        className="flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-primary text-white text-sm font-bold shadow-lg shadow-primary/25 hover:-translate-y-0.5 active:translate-y-0 transition-all shrink-0"
      >
        <Plus className="w-4 h-4" />
        <span>Upload Scan</span>
      </button>
    </div>
   </div>

   {filteredImages.length > 0 ? (
     <div className={viewMode === 'grid' ? "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4" : "space-y-4"}>
       {filteredImages.map(img => {
         const dateFormatted = img.date ? format(parseISO(img.date), 'MMMM d, yyyy') : '';
         return (
         <div 
           key={img._id} 
           className="bg-white rounded-xl border border-gray-200 overflow-hidden hover:shadow-md transition-all cursor-pointer group"
           onClick={() => setSelectedImage(img)}
         >
           {viewMode === 'grid' ? (
             <>
                <div className="h-40 bg-gray-100 flex items-center justify-center overflow-hidden">
                  {img.imageUrl ? (
                    <img src={img.imageUrl} alt={img.explanation} className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" />
                  ) : (
                    <ImageIcon className="w-12 h-12 text-gray-300" />
                  )}
                </div>
                <div className="p-4">
                  <h3 className="font-bold text-gray-900 mb-1">{img.explanation}</h3>
                  <div className="flex justify-between items-center text-sm text-gray-500">
                    <span className="truncate max-w-[120px]">{img.hospital}</span>
                    <span>{dateFormatted}</span>
                  </div>
                </div>
             </>
           ) : (
             <div className="flex items-center p-4 gap-4">
                <div className="w-16 h-16 rounded-lg bg-gray-100 flex items-center justify-center shrink-0 overflow-hidden">
                  {img.imageUrl ? (
                    <img src={img.imageUrl} alt={img.explanation} className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" />
                  ) : (
                    <ImageIcon className="w-8 h-8 text-gray-300" />
                  )}
                </div>
                <div className="flex-1">
                  <h3 className="font-bold text-gray-900">{img.explanation}</h3>
                  <div className="flex gap-4 text-sm text-gray-500 mt-1">
                    <span>{img.hospital}</span>
                    <span>•</span>
                    <span>{dateFormatted}</span>
                  </div>
                </div>
             </div>
           )}
         </div>
       )})}
     </div>
   ) : (
     <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-12 text-center">
      <ImageIcon className="w-12 h-12 text-gray-300 mx-auto mb-4" />
      <h3 className="text-lg font-medium text-gray-900 mb-1">No Scans Found</h3>
      <p className="text-gray-500">Upload a scan to get started.</p>
     </div>
   )}

   {/* Upload Modal */}
   {isUploadModalOpen && (
     <div className="fixed inset-0 bg-black/60 z-[100] backdrop-blur-sm flex items-center justify-center p-4">
       <div className="bg-white rounded-2xl shadow-xl w-full max-w-md overflow-hidden animate-in zoom-in-95 duration-200">
         <div className="p-4 border-b flex justify-between items-center bg-gray-50">
           <h3 className="font-bold text-gray-900">Upload New Scan</h3>
           <button onClick={() => setIsUploadModalOpen(false)} className="p-1 hover:bg-gray-200 rounded-md">
             <X className="w-5 h-5 text-gray-500" />
           </button>
         </div>
         <div className="p-6 space-y-4">
           <div>
             <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Hospital Name</label>
             <input type="text" value={uploadForm.hospital} onChange={e => setUploadForm({...uploadForm, hospital: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20" placeholder="e.g. Memorial Hospital" />
           </div>
           <div>
             <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Date</label>
             <DatePickerInput value={uploadForm.date} onChange={value => setUploadForm({...uploadForm, date: value})} className="w-full" />
           </div>
           <div>
             <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Explanation</label>
             <input type="text" value={uploadForm.explanation} onChange={e => setUploadForm({...uploadForm, explanation: e.target.value})} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20" placeholder="e.g. Chest X-Ray" />
           </div>
           <div>
             <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Image File (.png, .jpg)</label>
             <input type="file" accept="image/png, image/jpeg" onChange={e => setUploadFile(e.target.files?.[0] || null)} className="w-full px-3 py-2 rounded-lg border border-gray-200 focus:ring-2 focus:ring-primary/20" />
           </div>
           
           <button 
             onClick={handleUpload}
             disabled={uploading}
             className="w-full flex items-center justify-center gap-2 bg-primary text-white py-2.5 rounded-lg font-bold shadow-md hover:bg-primary/90 mt-2 transition-all disabled:opacity-50"
           >
             {uploading ? <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <Save className="w-4 h-4" />}
             {uploading ? 'Uploading...' : 'Save Scan'}
           </button>
         </div>
       </div>
     </div>
   )}

   {/* Image Viewer Modal */}
   {selectedImage && typeof document !== 'undefined' && createPortal(
    <>
     <div
      className="fixed inset-0 z-[200] bg-black/90 backdrop-blur-sm animate-in fade-in duration-200"
      onClick={() => setSelectedImage(null)}
     />
     <div className="fixed inset-0 z-[210] flex items-center justify-center p-4 pointer-events-none">
      <div className="relative max-w-6xl w-full max-h-[90vh] flex flex-col animate-in zoom-in-95 fade-in duration-200 pointer-events-auto">
       {/* Header */}
       <div className="bg-white rounded-t-2xl p-4 flex justify-between items-start shadow-lg">
        <div className="flex-1">
         <h3 className="font-bold text-gray-900 text-lg">{selectedImage.explanation}</h3>
         <div className="flex items-center gap-4 mt-1 text-sm text-gray-500">
          <span>{selectedImage.hospital}</span>
          <span>•</span>
          <span>{selectedImage.date ? format(parseISO(selectedImage.date), 'MMMM d, yyyy') : ''}</span>
         </div>
        </div>
        <div className="flex items-center gap-2">
         {selectedImage.imageUrl && (
          <a
           href={selectedImage.imageUrl}
           download
           className="p-2 hover:bg-gray-100 rounded-lg text-gray-600 hover:text-gray-900 transition-colors"
           title="Download"
           onClick={(e) => e.stopPropagation()}
          >
           <Download className="w-5 h-5" />
          </a>
         )}
         <button
          onClick={() => setSelectedImage(null)}
          className="p-2 hover:bg-gray-100 rounded-lg text-gray-600 hover:text-gray-900 transition-colors"
          title="Close"
         >
          <X className="w-5 h-5" />
         </button>
        </div>
       </div>

       {/* Image Container */}
       <div className="bg-gray-900 rounded-b-2xl overflow-hidden flex items-center justify-center" style={{ height: 'calc(90vh - 80px)', minHeight: '500px' }}>
        {selectedImage.imageUrl ? (
         <img
          src={selectedImage.imageUrl}
          alt={selectedImage.explanation}
          className="object-contain"
          style={{ width: '100%', height: '100%', maxWidth: '1200px', maxHeight: 'calc(90vh - 80px)' }}
          onClick={(e) => e.stopPropagation()}
         />
        ) : (
         <div className="flex flex-col items-center justify-center py-20 text-gray-500">
          <ImageIcon className="w-20 h-20 mb-4" />
          <p className="text-lg">No image available</p>
         </div>
        )}
       </div>
      </div>
     </div>
    </>,
    document.body
   )}
  </div>
 );
}
