import { useState } from 'react';
import { Syringe, Search, Calendar, MapPin, SearchX, Plus, X, Save } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import { createVaccination } from '../services/medical';
import { DatePickerInput } from '../components/DatePickerInput';
import { useHealthStore } from '../store/useHealthStore';
import { useActivePatientId } from '../hooks/useActivePatientId';

export function VaccinationsPage() {
  const { _rawVaccinations: vaccinations, loadUserData } = useHealthStore();
  const [searchTerm, setSearchTerm] = useState('');
  const activePatientId = useActivePatientId();

  // Upload Form States
  const [isUploadModalOpen, setIsUploadModalOpen] = useState(false);
  const [uploadForm, setUploadForm] = useState({
    name: '',
    administrationPlace: '',
    administeredDate: format(new Date(), 'yyyy-MM-dd')
  });
  const [uploading, setUploading] = useState(false);


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

    setUploading(true);
    try {
      await createVaccination({
        ...uploadForm,
        vaccineId: ``,
        patientId: activePatientId
      });
      setIsUploadModalOpen(false);
      setUploadForm({ name: '', administrationPlace: '', administeredDate: format(new Date(), 'yyyy-MM-dd') });
      await loadUserData(activePatientId, true);
    } catch (err) {
      console.error("Upload failed", err);
      alert("Upload failed.");
    } finally {
      setUploading(false);
    }
  };

  const sortedVaccinations = (vaccinations || []).slice().sort((a, b) => 
    new Date(b.administeredDate || 0).getTime() - new Date(a.administeredDate || 0).getTime()
  );

  const filteredVaccinations = sortedVaccinations.filter(v =>
    (v.name || '').toLowerCase().includes(searchTerm.toLowerCase()) ||
    (v.administrationPlace || '').toLowerCase().includes(searchTerm.toLowerCase())
  );

  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 Vaccinations</h1>
          <p className="text-gray-500 text-sm mt-1">View your vaccination history and immunization records</p>
        </div>

        <div className="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
          <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 vaccines..."
              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>Add Vaccination</span>
          </button>
        </div>
      </div>

      {filteredVaccinations.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {filteredVaccinations.map((vaccination) => {
            const dateObj = vaccination.administeredDate ? parseISO(vaccination.administeredDate) : null;
            
            return (
              <div key={vaccination._id} className="bg-white rounded-xl border border-gray-200 overflow-hidden hover:shadow-md transition-shadow">
                <div className="p-5 flex items-start gap-4">
                  <div className="w-12 h-12 rounded-xl bg-blue-50 flex items-center justify-center shrink-0">
                    <Syringe className="w-6 h-6 text-blue-500" />
                  </div>
                  <div>
                    <h3 className="font-bold text-gray-900 mb-1">{vaccination.name}</h3>
                    
                    <div className="flex items-center gap-2 text-sm text-gray-500 mb-1">
                      <Calendar className="w-4 h-4 text-gray-400 shrink-0" />
                      <span>{dateObj ? format(dateObj, 'MMMM d, yyyy') : 'Unknown Date'}</span>
                    </div>
                    
                    <div className="flex items-start gap-2 text-sm text-gray-500 line-clamp-2">
                      <MapPin className="w-4 h-4 text-gray-400 shrink-0 mt-0.5" />
                      <span className="leading-snug">{vaccination.administrationPlace || 'Unknown Location'}</span>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        <div className="text-center py-16 bg-gray-50 rounded-2xl border border-dashed border-gray-200">
          <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <SearchX className="w-8 h-8 text-gray-400" />
          </div>
          <h3 className="text-lg font-semibold text-gray-900 mb-1">No vaccinations found</h3>
          <p className="text-gray-500 text-sm">
            {searchTerm ? "Try adjusting your search criteria" : "Your vaccination records will appear here"}
          </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">Add New Vaccination</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">Vaccine Name</label>
                <input type="text" value={uploadForm.name} onChange={e => setUploadForm({...uploadForm, name: 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. COVID-19 mRNA" />
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Date Administered</label>
                <DatePickerInput value={uploadForm.administeredDate} onChange={value => setUploadForm({...uploadForm, administeredDate: value})} className="w-full" />
              </div>
              <div>
                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1.5">Place of Administration</label>
                <input type="text" value={uploadForm.administrationPlace} onChange={e => setUploadForm({...uploadForm, administrationPlace: 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>
              
              <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 ? 'Adding...' : 'Add Vaccination'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
