import React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  X, 
  Calendar as CalendarIcon, 
  MapPin, 
  Clock, 
  Building2, 
  Users, 
  Tag, 
  Target
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { format } from 'date-fns';
import { useAuth } from '../../context/AuthContext';

interface EventDetailsModalProps {
  isOpen: boolean;
  onClose: () => void;
  event: any;
}

export const EventDetailsModal: React.FC<EventDetailsModalProps> = ({ isOpen, onClose, event }) => {
  const { user } = useAuth();
  if (!isOpen || !event) return null;

  const parseDate = (dateSource: any): Date | null => {
    if (!dateSource) return null;
    if (typeof dateSource === 'string') return new Date(dateSource);
    if (Array.isArray(dateSource)) {
      return new Date(dateSource[0], dateSource[1] - 1, dateSource[2], dateSource[3] || 0, dateSource[4] || 0);
    }
    return null;
  };

  const startDate = parseDate(event.startDate);
  const endDate = parseDate(event.endDate);

  const isOrganizer = user?.role === 'ADMIN' || 
                      user?.role === 'PRINCIPAL' || 
                      user?.role === 'HOD' || 
                      event.userId === user?.id || 
                      event.created_by === user?.email || 
                      event.coordinator === user?.fullName;

  return (
    <AnimatePresence>
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4 sm:p-6">
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          onClick={onClose}
          className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
        />
        
        <motion.div
          initial={{ opacity: 0, scale: 0.95, y: 20 }}
          animate={{ opacity: 1, scale: 1, y: 0 }}
          exit={{ opacity: 0, scale: 0.95, y: 20 }}
          className="relative w-full max-w-2xl bg-white rounded-[2.5rem] shadow-2xl overflow-hidden flex flex-col max-h-[90vh]"
        >
          {/* Header */}
          <div className="p-8 bg-brand-navy text-white flex justify-between items-start relative overflow-hidden">
            <div className="relative z-10 pr-12">
              <div className="flex items-center gap-3 mb-3">
                <span className="px-3 py-1 bg-white/10 rounded-full text-[10px] font-black uppercase tracking-widest border border-white/10">
                  {event.department}
                </span>
                <span className="px-3 py-1 bg-brand-indigo/30 rounded-full text-[10px] font-black uppercase tracking-widest text-brand-glow border border-brand-indigo/50">
                  {event.type || event.eventType}
                </span>
              </div>
              <h2 className="text-2xl sm:text-3xl font-black tracking-tight leading-tight">
                {event.title}
              </h2>
            </div>
            
            <button 
              onClick={onClose}
              className="absolute top-8 right-8 p-2 bg-white/10 hover:bg-white/20 rounded-xl transition-colors z-10"
            >
              <X className="w-5 h-5" />
            </button>
            
            {/* Background Decoration */}
            <div className="absolute -right-10 -bottom-10 w-40 h-40 bg-brand-indigo/20 rounded-full blur-3xl" />
          </div>

          {/* Content */}
          <div className="p-8 overflow-y-auto custom-scrollbar space-y-8">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
              <div className="flex items-start gap-4 p-4 rounded-2xl bg-slate-50 border border-slate-100">
                <div className="w-10 h-10 bg-white rounded-xl flex items-center justify-center shadow-sm text-brand-indigo shrink-0">
                  <CalendarIcon className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-1">Date & Time</p>
                  <p className="text-sm font-bold text-text-dark">
                    {startDate ? format(startDate, 'MMMM d, yyyy') : 'TBD'}
                  </p>
                  <p className="text-xs font-bold text-text-muted mt-0.5">
                    {startDate ? format(startDate, 'hh:mm a') : 'TBD'} - {endDate ? format(endDate, 'hh:mm a') : 'TBD'}
                  </p>
                </div>
              </div>

              <div className="flex items-start gap-4 p-4 rounded-2xl bg-slate-50 border border-slate-100">
                <div className="w-10 h-10 bg-white rounded-xl flex items-center justify-center shadow-sm text-emerald-500 shrink-0">
                  <MapPin className="w-5 h-5" />
                </div>
                <div>
                  <p className="text-[10px] font-black uppercase tracking-widest text-text-muted mb-1">Venue</p>
                  <p className="text-sm font-bold text-text-dark">
                    {event.location || event.venue || 'TBD'}
                  </p>
                  <p className="text-xs font-bold text-text-muted mt-0.5">
                    {event.institution || 'RIT'}
                  </p>
                </div>
              </div>
            </div>

            {event.description && (
              <div>
                <h3 className="text-sm font-black text-text-dark mb-3">Event Description</h3>
                <div className="p-5 rounded-2xl bg-slate-50 border border-slate-100">
                  <p className="text-sm font-medium text-text-muted leading-relaxed whitespace-pre-wrap">
                    {event.description}
                  </p>
                </div>
              </div>
            )}



            <div className="grid grid-cols-1 sm:grid-cols-2 gap-6">
              {event.academicYears && event.academicYears.length > 0 && (
                <div>
                  <h3 className="text-sm font-black text-text-dark mb-3 flex items-center gap-2">
                    <Target className="w-4 h-4 text-brand-indigo" />
                    Target Audience
                  </h3>
                  <div className="flex flex-wrap gap-2">
                    {event.targetedBatch ? (
                      <span className="px-3 py-1.5 bg-brand-indigo text-white text-xs font-bold rounded-xl shadow-sm">
                        {event.targetedBatch}
                      </span>
                    ) : (
                      event.academicYears.map((year: string) => (
                        <span key={year} className="px-3 py-1.5 bg-brand-glow text-brand-indigo text-xs font-bold rounded-xl border border-brand-indigo/10">
                          {year}
                        </span>
                      ))
                    )}
                  </div>
                </div>
              )}
              
              {event.targetedSections && event.targetedSections.length > 0 && (
                <div>
                  <h3 className="text-sm font-black text-text-dark mb-3 flex items-center gap-2">
                    <Users className="w-4 h-4 text-emerald-500" />
                    Sections
                  </h3>
                  <div className="flex flex-wrap gap-2">
                    {event.targetedSections.map((sec: string) => (
                      <span key={sec} className="px-3 py-1.5 bg-emerald-50 text-emerald-600 text-xs font-bold rounded-xl border border-emerald-100">
                        Section {sec}
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>



            {/* Global registration capacity */}
            {event.maxParticipants && (
              <div className="p-5 rounded-2xl bg-brand-glow border border-brand-indigo/10 flex items-center justify-between">
                <div>
                  <p className="text-[10px] font-black uppercase tracking-widest text-brand-indigo mb-1">Registration Capacity</p>
                  <p className="text-sm font-black text-brand-navy">
                    {event.currentParticipants || 0} / {event.maxParticipants} Registered
                  </p>
                </div>
                <div className="w-24 h-2 bg-slate-100 rounded-full overflow-hidden">
                  <div 
                    className="bg-brand-indigo h-full"
                    style={{ width: `${Math.min(((event.currentParticipants || 0) / event.maxParticipants) * 100, 100)}%` }}
                  />
                </div>
              </div>
            )}

            {event.guestName && (
              <div>
                <h3 className="text-sm font-black text-text-dark mb-3">Special Guest</h3>
                <div className="p-4 rounded-2xl bg-slate-50 border border-slate-100 flex items-center justify-between">
                  <div>
                    <p className="text-sm font-bold text-text-dark">{event.guestName}</p>
                    {event.guestSocialProfile && (
                      <a href={event.guestSocialProfile} target="_blank" rel="noopener noreferrer" className="text-xs font-bold text-brand-indigo hover:underline mt-0.5 inline-block">
                        View Profile
                      </a>
                    )}
                  </div>
                </div>
              </div>
            )}

            {/* Detailed Financial Projections (Organizers only) */}
            {isOrganizer && (event.total_expense || event.refreshment_expense || event.transportation_expense || event.session_coverage_fee) ? (
              <div>
                <h3 className="text-sm font-black text-text-dark mb-3 flex items-center gap-2">
                  <Tag className="w-4 h-4 text-emerald-500" />
                  Financial Projection Details (Organizer Only)
                </h3>
                <div className="p-5 rounded-2xl bg-emerald-50/30 border border-emerald-100 space-y-4">
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
                    <div className="bg-white p-3.5 rounded-xl border border-slate-100 text-center">
                      <span className="block text-[8px] font-black text-slate-400 uppercase tracking-widest mb-1">Refreshments</span>
                      <span className="text-xs font-black text-slate-800">₹{event.refreshment_expense || 0}</span>
                    </div>
                    <div className="bg-white p-3.5 rounded-xl border border-slate-100 text-center">
                      <span className="block text-[8px] font-black text-slate-400 uppercase tracking-widest mb-1">Transport</span>
                      <span className="text-xs font-black text-slate-800">₹{event.transportation_expense || 0}</span>
                    </div>
                    <div className="bg-white p-3.5 rounded-xl border border-slate-100 text-center">
                      <span className="block text-[8px] font-black text-slate-400 uppercase tracking-widest mb-1">Session Fee</span>
                      <span className="text-xs font-black text-slate-800">₹{event.session_coverage_fee || 0}</span>
                    </div>
                    <div className="bg-emerald-100/50 p-3.5 rounded-xl border border-emerald-200 text-center">
                      <span className="block text-[8px] font-black text-emerald-700 uppercase tracking-widest mb-1">Total Expense</span>
                      <span className="text-xs font-black text-emerald-800">₹{event.total_expense || 0}</span>
                    </div>
                  </div>
                </div>
              </div>
            ) : null}
          </div>
          
          {/* Footer */}
          <div className="p-6 border-t border-slate-100 bg-slate-50/50 flex justify-end">
            <button 
              onClick={onClose}
              className="px-6 py-3 bg-white border border-slate-200 text-text-dark rounded-xl text-sm font-black hover:bg-slate-50 hover:border-slate-300 transition-all shadow-sm"
            >
              Close
            </button>
          </div>
        </motion.div>
      </div>
    </AnimatePresence>
  );
};
