import React, { useRef, useState } from 'react';
import { useData } from '../../context/DataContext';
import { useToast } from '../../context/ToastContext';

export const PatientMedia: React.FC = () => {
  const { clinicType } = useData();
  const { addToast } = useToast();
  const fileInputRef = useRef<HTMLInputElement>(null);

  const getMediaConfig = () => {
    switch (clinicType) {
      case 'dental':
        return {
          title: 'الأشعة السينية (X-Rays)',
          icon: 'fa-x-ray',
          color: 'text-emerald-600',
          bgColor: 'bg-emerald-50',
        };
      case 'obgyn':
        return {
          title: 'صور السونار (Ultrasound)',
          icon: 'fa-baby',
          color: 'text-rose-500',
          bgColor: 'bg-rose-50',
        };
      default:
        return {
          title: 'التقارير والمرفقات',
          icon: 'fa-file-medical',
          color: 'text-blue-600',
          bgColor: 'bg-blue-50',
        };
    }
  };

  const initialItems = [
     { id: 1, title: 'Sample Image 1', date: '2024-01-15', url: 'https://placehold.co/300x200/e2e8f0/64748b?text=Sample+1' }
  ];

  const [items, setItems] = useState(initialItems);
  const config = getMediaConfig();

  const handleUploadClick = () => {
      fileInputRef.current?.click();
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      if (file) {
          const reader = new FileReader();
          reader.onloadend = () => {
              const newItem = {
                  id: Date.now(),
                  title: file.name,
                  date: new Date().toISOString().split('T')[0],
                  url: reader.result as string
              };
              setItems(prev => [newItem, ...prev]);
              addToast('تم رفع الملف بنجاح', 'success');
          };
          reader.readAsDataURL(file);
      }
  };

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 mt-6">
      <div className="flex justify-between items-center mb-6 border-b border-gray-100 pb-4">
        <h3 className={`text-lg font-bold flex items-center gap-2 ${config.color}`}>
          <i className={`fas ${config.icon}`}></i>
          {config.title}
        </h3>
        <button 
            onClick={handleUploadClick}
            className={`text-xs px-3 py-1.5 rounded-lg font-medium transition-colors hover:opacity-80 text-white flex items-center gap-1 ${clinicType === 'dental' ? 'bg-emerald-500' : clinicType === 'obgyn' ? 'bg-rose-500' : 'bg-primary'}`}
        >
          <i className="fas fa-upload"></i> رفع ملف
        </button>
        <input 
            type="file" 
            ref={fileInputRef} 
            className="hidden" 
            accept="image/*"
            onChange={handleFileChange}
        />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
        {items.map((item) => (
          <div key={item.id} className="group relative rounded-xl overflow-hidden border border-gray-200 hover:shadow-md transition-all">
            <div className="aspect-video bg-gray-100 relative">
              <img src={item.url} alt={item.title} className="w-full h-full object-cover" />
              <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                <button className="w-8 h-8 bg-white rounded-full text-gray-800 flex items-center justify-center hover:bg-primary hover:text-white transition-colors">
                    <i className="fas fa-eye"></i>
                </button>
                <button 
                    onClick={() => setItems(prev => prev.filter(i => i.id !== item.id))}
                    className="w-8 h-8 bg-white rounded-full text-gray-800 flex items-center justify-center hover:bg-danger hover:text-white transition-colors"
                >
                    <i className="fas fa-trash"></i>
                </button>
              </div>
            </div>
            <div className="p-3 bg-white">
              <h4 className="font-bold text-gray-800 text-sm truncate">{item.title}</h4>
              <p className="text-xs text-gray-500">{item.date}</p>
            </div>
          </div>
        ))}

        {/* Upload Placeholder */}
        <div 
            onClick={handleUploadClick}
            className={`border-2 border-dashed border-gray-300 rounded-xl flex flex-col items-center justify-center p-4 cursor-pointer hover:border-gray-400 transition-colors aspect-video ${config.bgColor}`}
        >
          <i className={`fas fa-cloud-upload-alt text-3xl mb-2 opacity-50 ${config.color}`}></i>
          <span className="text-xs text-gray-500 font-medium">اضغط لرفع صورة جديدة</span>
        </div>
      </div>
    </div>
  );
};