import { API_BASE_URL } from '../../lib/config';
import React, { useState, useEffect } from 'react';
import { 
  Calendar as CalendarIcon, 
  ChevronLeft, 
  ChevronRight, 
  Plus, 
  MessageSquare, 
  Loader2, 
  X,
  FilePlus,
  Clock
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '../../lib/utils';
import { 
  format, 
  startOfMonth, 
  endOfMonth, 
  startOfWeek, 
  endOfWeek, 
  eachDayOfInterval, 
  isSameMonth, 
  isSameDay, 
  addMonths, 
  subMonths,
  isWeekend
} from 'date-fns';
import { useAuth } from '../../context/AuthContext';

interface Event {
  id: number;
  title: string;
  type: string;
  status: string;
  department: string;
  startDate: string;
  endDate: string;
}

interface Note {
  id: number;
  content: string;
  targetDate: string;
  authorName: string;
}

interface InstitutionalCalendarProps {
  onProposeEvent?: (date: string) => void;
  compact?: boolean;
}

export const InstitutionalCalendar: React.FC<InstitutionalCalendarProps> = ({ onProposeEvent, compact }) => {
  const { user } = useAuth();
  const [currentDate, setCurrentDate] = useState(new Date());
  const [events, setEvents] = useState<Event[]>([]);
  const [notes, setNotes] = useState<Note[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedDay, setSelectedDay] = useState<Date | null>(null);
  const [newNote, setNewNote] = useState('');
  const [isSubmittingNote, setIsSubmittingNote] = useState(false);
  
  // Advanced Filters
  const [filters, setFilters] = useState({
    department: '',
    batch: '',
    section: ''
  });

  // Rescheduling State
  const [reschedulingEvent, setReschedulingEvent] = useState<Event | null>(null);
  const [newTargetDate, setNewTargetDate] = useState('');
  const [startTime, setStartTime] = useState('10:00');
  const [endTime, setEndTime] = useState('12:00');

  const parseDate = (dateSource: any): Date | null => {
    if (!dateSource) return null;
    if (typeof dateSource === 'string') return new Date(dateSource);
    if (Array.isArray(dateSource)) {
      // Handle Spring Boot LocalDateTime array: [yyyy, mm, dd, hh, mm, ss]
      return new Date(dateSource[0], dateSource[1] - 1, dateSource[2], dateSource[3] || 0, dateSource[4] || 0);
    }
    return null;
  };

  const fetchData = async () => {
    try {
      const [eventsRes, notesRes] = await Promise.all([
        fetch(API_BASE_URL + '/api/events'),
        fetch(API_BASE_URL + '/api/notes')
      ]);
      
      if (eventsRes.ok && notesRes.ok) {
        const eventsData = await eventsRes.json();
        const notesData = await notesRes.json();
        
        // Robust filtering and status check
        const filteredEvents = eventsData.filter((e: any) => {
          const status = e.status?.toUpperCase();
          return status === 'APPROVED' || status === 'COMPLETED';
        });
        
        setEvents(filteredEvents);
        setNotes(notesData);
      }
    } catch (error) {
      console.error('Failed to fetch calendar data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  const handleAddNote = async () => {
    if (!newNote.trim() || !selectedDay) return;
    setIsSubmittingNote(true);
    try {
      const response = await fetch(API_BASE_URL + '/api/notes', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content: newNote,
          targetDate: format(selectedDay, 'yyyy-MM-dd'),
          authorName: user?.fullName || 'Anonymous',
          authorEmail: user?.email
        })
      });
      if (response.ok) {
        setNewNote('');
        fetchData();
      }
    } catch (error) {
      console.error('Failed to add note:', error);
    } finally {
      setIsSubmittingNote(false);
    }
  };

  const handleReschedule = async () => {
    if (!reschedulingEvent || !newTargetDate) return;
    
    try {
      const response = await fetch(`${API_BASE_URL}/api/events/${reschedulingEvent.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          startDate: `${newTargetDate}T${startTime}:00`,
          endDate: `${newTargetDate}T${endTime}:00`
        })
      });
      
      if (response.ok) {
        setReschedulingEvent(null);
        setNewTargetDate('');
        setSelectedDay(null);
        fetchData();
      }
    } catch (error) {
      console.error('Failed to reschedule event:', error);
    }
  };

  const filteredEvents = events.filter(e => {
    const matchesDept = !filters.department || e.department === filters.department;
    // We'd need to cast to any for targetedSections if not in interface
    const matchesBatch = !filters.batch || (e as any).academicYears?.includes(filters.batch);
    const matchesSection = !filters.section || (e as any).targetedSections?.includes(filters.section);
    return matchesDept && matchesBatch && matchesSection;
  });

  const days = eachDayOfInterval({
    start: startOfWeek(startOfMonth(currentDate)),
    end: endOfWeek(endOfMonth(currentDate))
  });

  if (loading) {
    return (
      <div className="flex flex-col items-center justify-center p-20 gap-4">
        <Loader2 className="w-10 h-10 text-brand-indigo animate-spin" />
        <p className="text-sm font-black text-brand-indigo uppercase tracking-widest">Loading Institutional Schedule...</p>
      </div>
    );
  }

  return (
    <div className={cn("space-y-8", compact && "space-y-4")}>
      {/* Header & Advanced Filters */}
      {!compact && (
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6">
          <div className="flex items-center gap-4">
            <div className="w-12 h-12 bg-brand-indigo rounded-2xl flex items-center justify-center text-white premium-shadow">
              <CalendarIcon className="w-6 h-6" />
            </div>
            <div>
              <h2 className="text-2xl font-black text-text-dark tracking-tight">Event & Notes Manager</h2>
              <p className="text-[10px] font-black uppercase tracking-widest text-text-muted">Master schedule audit & granular management</p>
            </div>
          </div>

          <div className="flex flex-wrap items-center gap-3">
            <select 
              value={filters.department}
              onChange={(e) => setFilters({...filters, department: e.target.value})}
              className="bg-white border border-slate-100 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest text-text-dark outline-none premium-shadow-sm"
            >
              <option value="">All Departments</option>
              {Array.from(new Set(events.map(e => e.department))).sort().map(d => (
                <option key={d} value={d}>{d}</option>
              ))}
            </select>
            <select 
              value={filters.batch}
              onChange={(e) => setFilters({...filters, batch: e.target.value})}
              className="bg-white border border-slate-100 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest text-text-dark outline-none premium-shadow-sm"
            >
              <option value="">All Batches</option>
              {['1st Year', '2nd Year', '3rd Year', '4th Year'].map(b => (
                <option key={b} value={b}>{b}</option>
              ))}
            </select>
            <select 
              value={filters.section}
              onChange={(e) => setFilters({...filters, section: e.target.value})}
              className="bg-white border border-slate-100 px-4 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest text-text-dark outline-none premium-shadow-sm"
            >
              <option value="">All Sections</option>
              {['A', 'B', 'C', 'D'].map(s => (
                <option key={s} value={s}>Section {s}</option>
              ))}
            </select>
          </div>
        </div>
      )}

      <div className={cn(
        "bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden",
        compact && "rounded-none shadow-none border-none"
      )}>
        {/* Calendar Navigation */}
        <div className={cn("flex items-center justify-between border-b border-slate-50", compact ? "p-4" : "p-8")}>
          <h3 className={cn("font-black text-text-dark tracking-tighter", compact ? "text-xl" : "text-3xl")}>
            {format(currentDate, 'MMMM yyyy')}
          </h3>
          <div className="flex gap-2">
            <button 
              onClick={() => setCurrentDate(subMonths(currentDate, 1))}
              className={cn("hover:bg-slate-50 rounded-2xl transition-all border border-slate-100", compact ? "p-2" : "p-3")}
            >
              <ChevronLeft className={cn("text-text-muted", compact ? "w-4 h-4" : "w-5 h-5")} />
            </button>
            <button 
              onClick={() => setCurrentDate(addMonths(currentDate, 1))}
              className={cn("hover:bg-slate-50 rounded-2xl transition-all border border-slate-100", compact ? "p-2" : "p-3")}
            >
              <ChevronRight className={cn("text-text-muted", compact ? "w-4 h-4" : "w-5 h-5")} />
            </button>
          </div>
        </div>

        {/* Calendar Grid */}
        <div className={cn(compact ? "p-4" : "p-8")}>
          <div className="grid grid-cols-7 gap-px bg-slate-100 border border-slate-100 rounded-3xl overflow-hidden">
            {['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'].map((day, i) => (
              <div key={`${day}-${i}`} className="bg-white py-4 text-center text-[10px] font-black text-text-muted tracking-widest border-b border-slate-50">
                {day}
              </div>
            ))}
            {days.map((day, idx) => {
              const dayStr = format(day, 'yyyy-MM-dd');
              const dayEvents = filteredEvents.filter(e => {
                const date = parseDate(e.startDate);
                return date && format(date, 'yyyy-MM-dd') === dayStr;
              });
              const dayNotes = notes.filter(n => {
                const date = parseDate(n.targetDate);
                return date && format(date, 'yyyy-MM-dd') === dayStr;
              });
              const isToday = isSameDay(day, new Date());
              const isCurrentMonth = isSameMonth(day, currentDate);
              const weekend = isWeekend(day);

              return (
                <div 
                  key={day.toString()}
                  onClick={() => setSelectedDay(day)}
                  className={cn(
                    compact ? "min-h-[80px] p-2" : "min-h-[140px] p-4",
                    "bg-white hover:bg-slate-50/50 transition-all cursor-pointer group relative",
                    !isCurrentMonth && "opacity-30 grayscale pointer-events-none",
                    isToday && "bg-brand-glow/10"
                  )}
                >
                  <div className="flex justify-between items-start mb-2">
                    <span className={cn(
                      "text-sm font-black",
                      isToday ? "text-brand-indigo" : "text-text-dark",
                      weekend && !isToday && "text-red-400"
                    )}>
                      {format(day, 'd')}
                    </span>
                    {weekend && isCurrentMonth && (
                      <span className="text-[8px] font-black text-red-300 uppercase tracking-widest">Holiday</span>
                    )}
                  </div>

                  {/* Day Content */}
                  <div className="space-y-1.5 overflow-y-auto max-h-[100px] custom-scrollbar pr-1">
                    {dayEvents.map(event => (
                      <div key={event.id} className="p-2.5 bg-brand-glow/20 border border-brand-indigo/10 rounded-xl transition-all hover:bg-brand-glow/40">
                        <p className="text-[10px] font-black text-brand-indigo leading-tight truncate">{event.title}</p>
                        <p className="text-[8px] font-black text-brand-indigo/60 uppercase tracking-widest mt-0.5">
                          {event.department === 'AI&DS' ? 'AI&DS' : event.department?.split(' ')[0]}
                        </p>
                      </div>
                    ))}
                    {dayNotes.map(note => (
                      <div key={note.id} className="p-2 bg-amber-50 border border-amber-200 rounded-lg flex gap-2 items-start">
                        <MessageSquare className="w-2.5 h-2.5 text-amber-500 mt-0.5 shrink-0" />
                        <p className="text-[9px] font-bold text-amber-700 leading-tight">{note.content}</p>
                      </div>
                    ))}
                  </div>

                  {/* Hover Action Indicator */}
                  <div className="absolute inset-0 border-2 border-brand-indigo/0 group-hover:border-brand-indigo/10 rounded-xl transition-all pointer-events-none" />
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <AnimatePresence>
        {selectedDay && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-6 bg-slate-900/40 backdrop-blur-sm">
            <motion.div
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.95 }}
              className="bg-white w-full max-w-md rounded-[2.5rem] premium-shadow-2xl overflow-hidden p-10 space-y-8"
            >
              {/* Modal Header */}
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-2xl font-black text-text-dark tracking-tight">Add Event Info</h3>
                  <p className="text-sm font-bold text-text-muted mt-1">Details for {format(selectedDay, 'yyyy-MM-dd')}</p>
                </div>
                <button onClick={() => setSelectedDay(null)} className="p-2 hover:bg-slate-50 rounded-xl transition-all">
                  <X className="w-6 h-6 text-slate-300" />
                </button>
              </div>

              {/* Event List in Modal */}
              <div className="space-y-4 max-h-[300px] overflow-y-auto custom-scrollbar pr-2">
                {filteredEvents.filter(e => {
                  const date = parseDate(e.startDate);
                  return date && format(date, 'yyyy-MM-dd') === format(selectedDay, 'yyyy-MM-dd');
                }).map(event => (
                  <div key={event.id} className="flex flex-col gap-4 p-5 bg-slate-50 border border-slate-100 rounded-[2rem] transition-all hover:bg-white hover:premium-shadow group">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-4">
                        <div className="w-1.5 h-8 bg-brand-indigo rounded-full" />
                        <div>
                          <p className="text-sm font-black text-text-dark">{event.title}</p>
                          <p className="text-[8px] font-black uppercase tracking-widest text-text-muted mt-0.5">{event.department} • {event.type}</p>
                        </div>
                      </div>
                      <button 
                        onClick={() => {
                          setReschedulingEvent(event);
                          setNewTargetDate(format(selectedDay, 'yyyy-MM-dd'));
                          const d = parseDate(event.startDate);
                          if (d) {
                            setStartTime(format(d, 'HH:mm'));
                          }
                          const ed = parseDate(event.endDate);
                          if (ed) {
                            setEndTime(format(ed, 'HH:mm'));
                          }
                        }}
                        className="p-2.5 bg-white rounded-xl border border-slate-100 text-brand-indigo hover:bg-brand-indigo hover:text-white transition-all premium-shadow-sm"
                      >
                        <Clock className="w-4 h-4" />
                      </button>
                    </div>

                    {reschedulingEvent?.id === event.id && (
                      <motion.div 
                        initial={{ opacity: 0, height: 0 }}
                        animate={{ opacity: 1, height: 'auto' }}
                        className="pt-4 border-t border-slate-100 space-y-4"
                      >
                        <div className="space-y-4">
                          <div>
                            <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Reschedule Date</label>
                            <input 
                              type="date"
                              value={newTargetDate}
                              onChange={(e) => setNewTargetDate(e.target.value)}
                              className="w-full bg-white border border-slate-200 rounded-xl p-3 text-[10px] font-black text-text-dark focus:outline-none focus:ring-2 focus:ring-brand-indigo/10"
                            />
                          </div>
                          
                          <div className="grid grid-cols-2 gap-3">
                            <div>
                              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Start Time</label>
                              <input 
                                type="time"
                                value={startTime}
                                onChange={(e) => setStartTime(e.target.value)}
                                className="w-full bg-white border border-slate-200 rounded-xl p-3 text-[10px] font-black text-text-dark focus:outline-none focus:ring-2 focus:ring-brand-indigo/10"
                              />
                            </div>
                            <div>
                              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">End Time</label>
                              <input 
                                type="time"
                                value={endTime}
                                onChange={(e) => setEndTime(e.target.value)}
                                className="w-full bg-white border border-slate-200 rounded-xl p-3 text-[10px] font-black text-text-dark focus:outline-none focus:ring-2 focus:ring-brand-indigo/10"
                              />
                            </div>
                          </div>

                          <button
                            onClick={handleReschedule}
                            className="w-full py-4 bg-brand-indigo text-white rounded-xl text-[9px] font-black uppercase tracking-widest premium-shadow active:scale-95 transition-all mt-2"
                          >
                            Apply Schedule Change
                          </button>
                        </div>
                      </motion.div>
                    )}
                  </div>
                ))}
              </div>

              {/* Note Input */}
              <div className="space-y-4">
                <label className="text-[10px] font-black uppercase tracking-widest text-text-muted">New Note</label>
                <input
                  type="text"
                  value={newNote}
                  onChange={(e) => setNewNote(e.target.value)}
                  placeholder="e.g. AI Workshop"
                  className="w-full h-16 px-6 bg-white border-2 border-brand-indigo/30 rounded-2xl text-sm font-bold text-text-dark focus:outline-none focus:border-brand-indigo transition-all"
                />
              </div>

              {/* Action Buttons */}
              <div className="flex items-center justify-end gap-6 pt-4">
                <button 
                  onClick={() => setSelectedDay(null)}
                  className="text-sm font-black text-text-dark/60 hover:text-text-dark transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleAddNote}
                  disabled={!newNote.trim() || isSubmittingNote}
                  className="px-8 py-4 bg-brand-indigo text-white rounded-3xl font-black text-sm premium-shadow-sm hover:translate-y-[-2px] active:translate-y-[0px] transition-all disabled:opacity-50"
                >
                  {isSubmittingNote ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Save Note'}
                </button>
              </div>

              {/* Propose Action Fallback */}
              <div className="pt-6 border-t border-slate-50 text-center">
                <button
                  onClick={() => {
                    if (onProposeEvent) onProposeEvent(format(selectedDay, 'yyyy-MM-dd'));
                    setSelectedDay(null);
                  }}
                  className="text-[10px] font-black uppercase tracking-widest text-brand-indigo hover:underline"
                >
                  + Propose New Event for this date
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};
