import { API_BASE_URL } from '../../lib/config';
import React, { useState, useEffect } from 'react';
import { 
  Zap, 
  ArrowRightLeft, 
  ChevronLeft, 
  ChevronRight, 
  ShieldAlert, 
  Play,
  Building2,
  Users,
  Layers,
  Calendar,
  ChevronDown,
  Loader2,
  CheckCircle2,
  X,
  AlertTriangle,
  Clock,
  ChevronUp
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '../../lib/utils';
import { 
  format, 
  addMonths, 
  subMonths, 
  startOfMonth, 
  endOfMonth, 
  startOfWeek, 
  endOfWeek, 
  eachDayOfInterval, 
  isSameMonth, 
  isSameDay 
} from 'date-fns';

const DEPARTMENTS = [
  "AI&DS", "AI&ML", "CSE", "CCE", "CSBS", "ECE", 
  "MECH", "EE(VLSI)", "BIOTECH", "Placement Department", 
  "H&S Dept", "Club", "Centre"
];

const BATCHES = ['1st Year', '2nd Year', '3rd Year', '4th Year'];

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;
};

interface Event {
  id: number;
  title: string;
  startDate: string;
  endDate: string;
  department: string;
  academicYears: string[];
  institution?: string;
  type?: string;
  category?: string;
  location?: string;
  proposer?: any;
}

const MiniCalendar: React.FC<{ 
  title: string; 
  subtitle: string; 
  date: Date; 
  onDateChange: (d: Date) => void;
  events: Event[];
  accentColor: string;
  onEventClick?: (e: Event) => void;
}> = ({ title, subtitle, date, onDateChange, events, accentColor, onEventClick }) => {
  const days = eachDayOfInterval({
    start: startOfWeek(startOfMonth(date)),
    end: endOfWeek(endOfMonth(date))
  });

  return (
    <div className="bg-white rounded-[2.5rem] border border-slate-100 premium-shadow overflow-hidden flex-1">
      <div className="p-6 border-b border-slate-50 flex items-center justify-between">
        <div>
          <h4 className="text-sm font-black text-text-dark tracking-tight">{title}</h4>
          <p className="text-[9px] font-black uppercase tracking-widest text-text-muted mt-0.5">{subtitle}</p>
        </div>
        <div className="flex gap-1">
          <button onClick={() => onDateChange(subMonths(date, 1))} className="p-1.5 hover:bg-slate-50 rounded-lg transition-all"><ChevronLeft className="w-4 h-4 text-text-muted" /></button>
          <button onClick={() => onDateChange(addMonths(date, 1))} className="p-1.5 hover:bg-slate-50 rounded-lg transition-all"><ChevronRight className="w-4 h-4 text-text-muted" /></button>
        </div>
      </div>
      <div className="p-6">
        <div className="text-center mb-4">
          <span className="text-lg font-black text-text-dark">{format(date, 'MMMM yyyy')}</span>
        </div>
        <div className="grid grid-cols-7 gap-px bg-slate-50 border border-slate-50 rounded-2xl overflow-hidden">
          {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((d, i) => (
            <div key={`${d}-${i}`} className="bg-white py-2 text-center text-[8px] font-black text-text-muted">{d}</div>
          ))}
          {days.map(day => {
            const isCurrentMonth = isSameMonth(day, date);
            const dayStr = format(day, 'yyyy-MM-dd');
            const dayEvents = events.filter(e => {
              const d = parseDate(e.startDate);
              return d && format(d, 'yyyy-MM-dd') === dayStr;
            });
            
            return (
              <div key={day.toString()} className={cn(
                "min-h-[8rem] bg-white p-2 border-t border-slate-50 relative",
                !isCurrentMonth && "opacity-20"
              )}>
                <span className="text-xs font-black text-text-muted mb-2 block">{format(day, 'd')}</span>
                <div className="space-y-1.5 overflow-y-auto max-h-[6rem] custom-scrollbar">
                  {dayEvents.map(e => (
                    <div 
                      key={e.id} 
                      onClick={() => onEventClick?.(e)}
                      className="bg-brand-glow border border-brand-indigo/10 rounded-lg p-2 transition-all hover:scale-[1.02] cursor-pointer"
                    >
                      <h5 className="text-[9px] font-black text-brand-indigo leading-tight truncate">{e.title}</h5>
                      <p className="text-[7px] font-bold text-brand-indigo/60 uppercase tracking-wider">{e.department}</p>
                    </div>
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export const AutomationView: React.FC = () => {
  const [sourceDate, setSourceDate] = useState(new Date());
  const [targetDate, setTargetDate] = useState(addMonths(new Date(), 6));
  const [events, setEvents] = useState<Event[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isExecuting, setIsExecuting] = useState(false);
  const [status, setStatus] = useState<'idle' | 'success'>('idle');

  const [sourceConfig, setSourceConfig] = useState({
    institution: 'RIT',
    department: 'AI&DS',
    batch: '1st Year'
  });

  const [targetConfig, setTargetConfig] = useState({
    institution: 'RIT',
    department: 'AI&DS',
    batch: '1st Year'
  });

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

  const fetchEvents = async () => {
    try {
      const response = await fetch(API_BASE_URL + '/api/events');
      if (response.ok) {
        const data = await response.json();
        setEvents(data);
      }
    } catch (error) {
      console.error('Failed to fetch events:', error);
    } finally {
      setIsLoading(false);
    }
  }

  const filteredSourceEvents = events.filter(e => 
    e.department?.trim() === sourceConfig.department.trim() && 
    (e.academicYears || []).map((y: string) => y.trim()).includes(sourceConfig.batch.trim())
  );

  const filteredTargetEvents = events.filter(e => 
    e.department?.trim() === targetConfig.department.trim() && 
    (e.academicYears || []).map((y: string) => y.trim()).includes(targetConfig.batch.trim())
  );

  const [proposedChanges, setProposedChanges] = useState<any[]>([]);
  const [showReviewModal, setShowReviewModal] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState<any>(null);

  const prepareSwap = () => {
    const changes = filteredSourceEvents.map(event => {
      const originalDate = parseDate(event.startDate);
      if (!originalDate) return { ...event, resolution: 'skip' };
      
      const isOddSem = originalDate.getMonth() >= 6;
      const targetBaseDate = isOddSem ? subMonths(originalDate, 6) : addMonths(originalDate, 6);
      
      // Preserving time
      const targetDateStr = format(targetBaseDate, 'yyyy-MM-dd');
      const timeStr = format(originalDate, 'HH:mm:ss');
      const finalDateTimeStr = `${targetDateStr}T${timeStr}`;
      
      const dayOfWeek = targetBaseDate.getDay();
      const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
      
      // Conflict Detection (Any event on target date)
      const targetConflicts = filteredTargetEvents.filter(te => 
        format(parseDate(te.startDate)!, 'yyyy-MM-dd') === targetDateStr
      );

      const hasTimeConflict = targetConflicts.some(tc => {
        const tcDate = parseDate(tc.startDate);
        return tcDate && format(tcDate, 'HH:mm') === format(originalDate, 'HH:mm');
      });

      const isAlreadySwapped = targetConflicts.some(tc => 
        tc.title.trim().toLowerCase() === event.title.trim().toLowerCase()
      );
      
      return {
        ...event,
        originalDate: event.startDate,
        targetDate: finalDateTimeStr, // Now includes time
        targetDepartment: targetConfig.department,
        targetBatch: targetConfig.batch,
        isWeekend,
        isAlreadySwapped,
        targetConflicts,
        hasTimeConflict,
        resolution: isAlreadySwapped ? 'skip' : (targetConflicts.length > 0 ? 'review' : 'create'),
        adjustment: isWeekend ? 'monday' : 'none'
      };
    });
    setProposedChanges(changes);
    setShowReviewModal(true);
  };

  const handleExecuteSwap = async () => {
    setIsExecuting(true);
    
    const finalizedChanges = proposedChanges
      .filter(c => c.resolution !== 'skip')
      .map(change => {
      let finalDate = new Date(change.targetDate);
      
      // Handle Weekend Adjustments
      if (change.resolution !== 'reschedule' && change.isWeekend) {
        if (change.adjustment === 'friday') {
          const day = finalDate.getDay();
          const diff = day === 6 ? 1 : 2;
          finalDate.setDate(finalDate.getDate() - diff);
        } else if (change.adjustment === 'monday') {
          const day = finalDate.getDay();
          const diff = day === 6 ? 2 : 1;
          finalDate.setDate(finalDate.getDate() + diff);
        }
      }
      
      return {
        ...change,
        finalDate: format(finalDate, "yyyy-MM-dd'T'HH:mm:ss")
      };
    });

    console.log('Finalized Swap Payload:', finalizedChanges);
    
    try {
      const response = await fetch(API_BASE_URL + '/api/events/batch-create', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(finalizedChanges.map(c => ({
            ...c,
            targetDepartment: c.targetDepartment,
            targetBatch: c.targetBatch,
            startDate: c.finalDate
        })))
      });

      if (response.ok) {
        setStatus('success');
        fetchEvents();
      } else {
        const errData = await response.json();
        alert('Failed to execute automation swap: ' + (errData.message || 'Unknown error'));
      }
    } catch (error) {
      console.error('Automation swap failed:', error);
      alert('Network error during automation swap');
    } finally {
      setIsExecuting(false);
      setShowReviewModal(false);
      setTimeout(() => setStatus('idle'), 3000);
    }
  };

  return (
    <div className="space-y-8 pb-20">
      <div className="flex justify-between items-start">
        <div>
          <h2 className="text-3xl font-black text-text-dark tracking-tight">Event Automation</h2>
          <p className="text-text-muted font-medium">Configure and manage automated department event workflows.</p>
        </div>
        <div className="w-12 h-12 bg-amber-50 rounded-2xl flex items-center justify-center text-amber-500 premium-shadow">
          <Zap className="w-6 h-6 fill-current" />
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <div className="bg-white rounded-[2.5rem] p-8 border border-slate-100 premium-shadow relative overflow-hidden">
          <div className="flex items-center gap-4 mb-8">
            <div className="w-10 h-10 bg-slate-50 rounded-xl flex items-center justify-center text-text-muted">
              <Building2 className="w-5 h-5" />
            </div>
            <div>
              <h3 className="font-black text-text-dark">Source Selection</h3>
              <p className="text-[9px] font-black uppercase tracking-widest text-text-muted">Select branch to clone events from</p>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Institution</label>
              <div className="bg-slate-50 rounded-xl p-3 flex justify-between items-center cursor-pointer">
                <span className="text-xs font-bold text-text-dark">RIT</span>
                <ChevronDown className="w-3 h-3 text-text-muted" />
              </div>
            </div>
            <div>
              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Department</label>
              <select 
                value={sourceConfig.department}
                onChange={(e) => setSourceConfig({...sourceConfig, department: e.target.value})}
                className="w-full bg-slate-50 border-none rounded-xl p-3 text-xs font-bold text-text-dark outline-none appearance-none"
              >
                {DEPARTMENTS.map(d => <option key={d} value={d}>{d}</option>)}
              </select>
            </div>
            <div>
              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Batch</label>
              <select 
                value={sourceConfig.batch}
                onChange={(e) => setSourceConfig({...sourceConfig, batch: e.target.value})}
                className="w-full bg-slate-50 border-none rounded-xl p-3 text-xs font-bold text-text-dark outline-none appearance-none"
              >
                {BATCHES.map(b => <option key={b} value={b}>{b}</option>)}
              </select>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-[2.5rem] p-8 border border-slate-100 premium-shadow relative overflow-hidden">
          <div className="flex items-center gap-4 mb-8">
            <div className="w-10 h-10 bg-brand-indigo rounded-xl flex items-center justify-center text-white">
              <ArrowRightLeft className="w-5 h-5" />
            </div>
            <div>
              <h3 className="font-black text-text-dark">Target Workspace</h3>
              <p className="text-[9px] font-black uppercase tracking-widest text-brand-indigo">Automation output destination</p>
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div>
              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Target Inst</label>
              <div className="bg-slate-50 rounded-xl p-3 flex justify-between items-center cursor-pointer">
                <span className="text-xs font-bold text-text-dark">RIT</span>
                <ChevronDown className="w-3 h-3 text-text-muted" />
              </div>
            </div>
            <div>
              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Target Dept</label>
              <select 
                value={targetConfig.department}
                onChange={(e) => setTargetConfig({...targetConfig, department: e.target.value})}
                className="w-full bg-slate-50 border-none rounded-xl p-3 text-xs font-bold text-text-dark outline-none appearance-none"
              >
                {DEPARTMENTS.map(d => <option key={d} value={d}>{d}</option>)}
              </select>
            </div>
            <div>
              <label className="text-[8px] font-black uppercase tracking-widest text-text-muted mb-2 block">Target Batch</label>
              <select 
                value={targetConfig.batch}
                onChange={(e) => setTargetConfig({...targetConfig, batch: e.target.value})}
                className="w-full bg-slate-50 border-none rounded-xl p-3 text-xs font-bold text-text-dark outline-none appearance-none"
              >
                {BATCHES.map(b => <option key={b} value={b}>{b}</option>)}
              </select>
            </div>
          </div>
        </div>
      </div>

      <div className="bg-brand-navy rounded-3xl p-6 flex items-center justify-between text-white premium-shadow">
        <div className="flex items-center gap-4">
          <div className="w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center text-amber-400">
            <ShieldAlert className="w-5 h-5" />
          </div>
          <div>
            <h4 className="text-sm font-black tracking-tight">Automation Safety Protocols Active</h4>
            <p className="text-[9px] font-medium text-white/50">Cloning institutional events shifts schedules by +/- 6 months (Semester Swap).</p>
          </div>
        </div>
        <div className="flex items-center gap-6">
          <button className="text-[9px] font-black uppercase tracking-widest text-white/40 hover:text-white transition-colors">Clear Workspace</button>
          <button 
            onClick={prepareSwap}
            disabled={isExecuting || filteredSourceEvents.length === 0}
            className={cn(
              "flex items-center gap-3 px-8 py-4 rounded-2xl font-black text-[10px] uppercase tracking-[0.2em] transition-all premium-shadow",
              status === 'success' ? "bg-emerald-500 text-white" : 
              filteredSourceEvents.length === 0 ? "bg-slate-200 text-slate-400 cursor-not-allowed" :
              "bg-brand-indigo text-white hover:scale-105"
            )}
          >
            {isExecuting ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : status === 'success' ? (
              <>
                <CheckCircle2 className="w-4 h-4" />
                Swap Completed
              </>
            ) : filteredSourceEvents.length === 0 ? (
              <>
                <ShieldAlert className="w-4 h-4" />
                No Events Found to Swap
              </>
            ) : (
              <>
                <ArrowRightLeft className="w-4 h-4" />
                Execute Semester Swap
              </>
            )}
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
        <MiniCalendar 
          title="Primary Schedule (Source)" 
          subtitle={`${sourceConfig.department} • ${sourceConfig.batch}`} 
          date={sourceDate} 
          onDateChange={setSourceDate}
          events={filteredSourceEvents}
          accentColor="bg-brand-indigo"
          onEventClick={setSelectedEvent}
        />
        <MiniCalendar 
          title="Target Workspace Events" 
          subtitle={`${targetConfig.department} • ${targetConfig.batch}`} 
          date={targetDate} 
          onDateChange={setTargetDate}
          events={filteredTargetEvents}
          accentColor="bg-emerald-400"
          onEventClick={setSelectedEvent}
        />
      </div>

      <AnimatePresence>
        {selectedEvent && (
          <div className="fixed inset-0 z-[150] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setSelectedEvent(null)}
              className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-xl bg-white rounded-[2.5rem] premium-shadow overflow-hidden"
            >
              <div className="p-8 bg-brand-navy text-white flex justify-between items-start">
                <div>
                  <span className="px-3 py-1 bg-white/10 rounded-full text-[8px] font-black uppercase tracking-widest text-brand-indigo border border-white/10">
                    {selectedEvent.category || 'Academic'} Event
                  </span>
                  <h3 className="text-2xl font-black tracking-tight mt-3">{selectedEvent.title}</h3>
                </div>
                <button onClick={() => setSelectedEvent(null)} className="p-2 hover:bg-white/10 rounded-xl transition-all">
                  <X className="w-6 h-6" />
                </button>
              </div>

              <div className="p-8 space-y-6">
                <div className="grid grid-cols-2 gap-6">
                  <div className="space-y-1">
                    <span className="text-[8px] font-black uppercase tracking-widest text-text-muted">Start Date</span>
                    <p className="text-xs font-bold text-text-dark">
                      {parseDate(selectedEvent.startDate) ? format(parseDate(selectedEvent.startDate)!, 'PPP') : 'N/A'}
                    </p>
                  </div>
                  <div className="space-y-1">
                    <span className="text-[8px] font-black uppercase tracking-widest text-text-muted">Venue</span>
                    <p className="text-xs font-bold text-text-dark">{selectedEvent.location || 'Seminar Hall'}</p>
                  </div>
                  <div className="space-y-1">
                    <span className="text-[8px] font-black uppercase tracking-widest text-text-muted">Department</span>
                    <p className="text-xs font-bold text-text-dark">{selectedEvent.department}</p>
                  </div>
                  <div className="space-y-1">
                    <span className="text-[8px] font-black uppercase tracking-widest text-text-muted">Academic Year</span>
                    <p className="text-xs font-bold text-text-dark">{selectedEvent.academicYears?.join(', ') || 'N/A'}</p>
                  </div>
                </div>

                <div className="p-4 bg-slate-50 rounded-2xl border border-slate-100">
                  <span className="text-[8px] font-black uppercase tracking-widest text-text-muted block mb-2">Proposer Information</span>
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 bg-white rounded-lg border border-slate-200 flex items-center justify-center text-[10px] font-black text-brand-indigo">
                      {selectedEvent.proposer?.fullName?.charAt(0) || 'F'}
                    </div>
                    <div>
                      <p className="text-[10px] font-black text-text-dark leading-none">{selectedEvent.proposer?.fullName || 'Faculty Member'}</p>
                      <p className="text-[8px] font-bold text-text-muted mt-1">{selectedEvent.proposer?.email || 'faculty@rit.edu'}</p>
                    </div>
                  </div>
                </div>
              </div>

              <div className="p-8 border-t border-slate-100 flex justify-end">
                <button 
                  onClick={() => setSelectedEvent(null)}
                  className="px-10 py-4 bg-brand-navy text-white rounded-2xl font-black text-xs uppercase tracking-widest premium-shadow hover:scale-105 active:scale-95 transition-all"
                >
                  Close Insights
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>

      <AnimatePresence>
        {showReviewModal && (
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setShowReviewModal(false)}
              className="absolute inset-0 bg-slate-900/40 backdrop-blur-sm"
            />
            <motion.div
              initial={{ opacity: 0, scale: 0.9, y: 20 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.9, y: 20 }}
              className="relative w-full max-w-4xl bg-white rounded-[2.5rem] premium-shadow overflow-hidden flex flex-col max-h-[80vh]"
            >
              <div className="p-8 bg-brand-navy text-white flex justify-between items-start">
                <div>
                  <h3 className="text-2xl font-black tracking-tight">Review Automated Changes</h3>
                  <p className="text-white/60 text-xs font-medium mt-1">Audit and adjust planned semester-swap dates.</p>
                </div>
                <button onClick={() => setShowReviewModal(false)} className="p-2 hover:bg-white/10 rounded-xl transition-all">
                  <ChevronDown className="w-6 h-6 rotate-180" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
                <div className="space-y-4">
                  {proposedChanges.map((change, idx) => (
                    <div key={change.id} className={cn(
                      "p-6 rounded-[2.5rem] border transition-all space-y-6",
                      change.resolution === 'skip' ? "bg-slate-50 border-slate-100 opacity-60" :
                      change.targetConflicts?.length > 0 ? "bg-red-50/30 border-red-100" :
                      change.isWeekend ? "bg-amber-50 border-amber-100" : "bg-white border-slate-100"
                    )}>
                      <div className="flex items-center justify-between gap-8">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <span className="text-[8px] font-black uppercase tracking-widest text-text-muted">Event</span>
                            <h4 className="text-sm font-black text-text-dark">{change.title}</h4>
                          </div>
                          <div className="flex items-center gap-4">
                            <div className="flex items-center gap-2 px-3 py-1.5 bg-slate-100 rounded-lg">
                              <Calendar className="w-3 h-3 text-text-muted" />
                              <span className="text-[10px] font-bold text-text-dark">
                                  {parseDate(change.originalDate) ? format(parseDate(change.originalDate)!, 'MMM d') : 'N/A'}
                                </span>
                              <ArrowRightLeft className="w-3 h-3 text-brand-indigo" />
                              <span className="text-[10px] font-black text-brand-indigo">
                                {parseDate(change.targetDate) ? format(parseDate(change.targetDate)!, 'MMM d, yyyy') : 'N/A'}
                              </span>
                            </div>
                            
                            {change.isAlreadySwapped && (
                              <span className="flex items-center gap-1.5 px-3 py-1 bg-emerald-100 text-emerald-700 rounded-full text-[8px] font-black uppercase tracking-widest">
                                <CheckCircle2 className="w-3 h-3" /> Already Swapped
                              </span>
                            )}
                          </div>
                        </div>

                        <div className="flex items-center gap-3">
                          {change.targetConflicts?.length > 0 && change.resolution !== 'skip' && (
                            <div className="flex items-center gap-2 px-4 py-2 bg-red-100 text-red-700 rounded-2xl border border-red-200">
                              <AlertTriangle className="w-4 h-4" />
                              <div className="flex flex-col">
                                <span className="text-[9px] font-black uppercase">Conflict Detected</span>
                                <span className="text-[8px] font-bold opacity-70">
                                  {change.targetConflicts.length} event(s) already on this date
                                  {change.hasTimeConflict && " (Time Overlap!)"}
                                </span>
                              </div>
                            </div>
                          )}

                          <div className="flex bg-white rounded-2xl border border-slate-100 p-1.5 premium-shadow-sm">
                            <button
                              onClick={() => {
                                const updated = [...proposedChanges];
                                updated[idx].resolution = 'create';
                                setProposedChanges(updated);
                              }}
                              className={cn(
                                "px-4 py-2 rounded-xl text-[9px] font-black uppercase tracking-widest transition-all",
                                change.resolution === 'create' || change.resolution === 'review' ? "bg-brand-indigo text-white shadow-lg shadow-brand-indigo/20" : "text-text-muted hover:text-text-dark"
                              )}
                            >
                              Commit
                            </button>
                            <button
                              onClick={() => {
                                const updated = [...proposedChanges];
                                updated[idx].resolution = 'reschedule';
                                setProposedChanges(updated);
                              }}
                              className={cn(
                                "px-4 py-2 rounded-xl text-[9px] font-black uppercase tracking-widest transition-all",
                                change.resolution === 'reschedule' ? "bg-amber-500 text-white shadow-lg shadow-amber-500/20" : "text-text-muted hover:text-text-dark"
                              )}
                            >
                              Reschedule
                            </button>
                            <button
                              onClick={() => {
                                const updated = [...proposedChanges];
                                updated[idx].resolution = 'skip';
                                setProposedChanges(updated);
                              }}
                              className={cn(
                                "px-4 py-2 rounded-xl text-[9px] font-black uppercase tracking-widest transition-all",
                                change.resolution === 'skip' ? "bg-slate-200 text-slate-600" : "text-text-muted hover:text-text-dark"
                              )}
                            >
                              Skip
                            </button>
                          </div>

                          {/* Weekend Quick-Shift */}
                          {change.isWeekend && change.resolution !== 'skip' && change.resolution !== 'reschedule' && (
                            <div className="flex bg-amber-100/50 p-1 rounded-xl border border-amber-200">
                              <button
                                onClick={() => {
                                  const updated = [...proposedChanges];
                                  updated[idx].adjustment = 'friday';
                                  setProposedChanges(updated);
                                }}
                                title="Shift to Friday"
                                className={cn(
                                  "px-3 py-1.5 rounded-lg text-[8px] font-black uppercase tracking-widest transition-all",
                                  change.adjustment === 'friday' ? "bg-amber-600 text-white shadow-sm" : "text-amber-700 hover:bg-amber-100"
                                )}
                              >
                                Fri
                              </button>
                              <button
                                onClick={() => {
                                  const updated = [...proposedChanges];
                                  updated[idx].adjustment = 'monday';
                                  setProposedChanges(updated);
                                }}
                                title="Shift to Monday"
                                className={cn(
                                  "px-3 py-1.5 rounded-lg text-[8px] font-black uppercase tracking-widest transition-all",
                                  change.adjustment === 'monday' ? "bg-amber-600 text-white shadow-sm" : "text-amber-700 hover:bg-amber-100"
                                )}
                              >
                                Mon
                              </button>
                            </div>
                          )}
                        </div>
                      </div>

                      {/* Expanded Conflict / Reschedule Details */}
                      {(change.resolution === 'reschedule' || (change.targetConflicts?.length > 0 && change.resolution !== 'skip')) && (
                        <motion.div 
                          initial={{ opacity: 0, height: 0 }}
                          animate={{ opacity: 1, height: 'auto' }}
                          className="pt-6 border-t border-slate-100 space-y-4"
                        >
                          {change.targetConflicts?.length > 0 && (
                            <div className="space-y-2">
                              <span className="text-[8px] font-black uppercase tracking-widest text-red-500">Conflicts at Destination</span>
                              {change.targetConflicts.map((conf: any) => (
                                <div key={conf.id} className="flex items-center justify-between p-3 bg-red-50/50 rounded-xl border border-red-100">
                                  <div className="flex items-center gap-3">
                                    <div className="w-6 h-6 bg-white rounded-lg flex items-center justify-center text-[8px] font-black text-red-500 border border-red-100">
                                      {conf.department.substring(0, 2)}
                                    </div>
                                    <span className="text-[11px] font-bold text-text-dark">{conf.title}</span>
                                  </div>
                                  <div className="flex items-center gap-2 text-[9px] font-black text-red-600/60 uppercase">
                                    <Clock className="w-3 h-3" />
                                    {format(new Date(conf.startDate), 'hh:mm a')}
                                  </div>
                                </div>
                              ))}
                            </div>
                          )}

                          {change.resolution === 'reschedule' && (
                            <div className="flex items-end gap-4 bg-amber-50/50 p-6 rounded-[2rem] border border-amber-100">
                              <div className="flex-1">
                                <label className="text-[8px] font-black uppercase tracking-widest text-amber-600 mb-2 block">New Target Date</label>
                                <input 
                                  type="date"
                                  value={change.targetDate}
                                  onChange={(e) => {
                                    const updated = [...proposedChanges];
                                    updated[idx].targetDate = e.target.value;
                                    setProposedChanges(updated);
                                  }}
                                  className="w-full bg-white border border-amber-200 rounded-xl p-3 text-xs font-bold text-text-dark focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                                />
                              </div>
                              <div className="flex flex-col gap-2">
                                <button 
                                  onClick={() => {
                                    const d = new Date(change.targetDate);
                                    d.setDate(d.getDate() + 1);
                                    const updated = [...proposedChanges];
                                    updated[idx].targetDate = format(d, 'yyyy-MM-dd');
                                    setProposedChanges(updated);
                                  }}
                                  className="p-2 bg-white border border-amber-200 rounded-lg hover:bg-amber-100 transition-all"
                                >
                                  <ChevronUp className="w-4 h-4 text-amber-600" />
                                </button>
                                <button 
                                  onClick={() => {
                                    const d = new Date(change.targetDate);
                                    d.setDate(d.getDate() - 1);
                                    const updated = [...proposedChanges];
                                    updated[idx].targetDate = format(d, 'yyyy-MM-dd');
                                    setProposedChanges(updated);
                                  }}
                                  className="p-2 bg-white border border-amber-200 rounded-lg hover:bg-amber-100 transition-all"
                                >
                                  <ChevronDown className="w-4 h-4 text-amber-600" />
                                </button>
                              </div>
                              <div className="flex flex-col gap-1 px-4 py-2 bg-white rounded-2xl border border-amber-100">
                                <span className="text-[7px] font-black uppercase text-amber-400">Shift Result</span>
                                <span className="text-[10px] font-black text-amber-700">{format(new Date(change.targetDate), 'EEEE')}</span>
                              </div>
                            </div>
                          )}
                        </motion.div>
                      )}
                    </div>
                  ))}
                </div>
              </div>

              <div className="p-8 border-t border-slate-100 bg-slate-50/50 flex justify-end gap-4">
                <button 
                  onClick={() => setShowReviewModal(false)}
                  className="px-8 py-4 text-xs font-black uppercase tracking-widest text-text-muted hover:text-text-dark transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleExecuteSwap}
                  className="px-10 py-4 bg-brand-navy text-white rounded-2xl font-black text-xs uppercase tracking-widest premium-shadow hover:scale-105 active:scale-95 transition-all"
                >
                  Commit Automation Swap
                </button>
              </div>
            </motion.div>
          </div>
        )}
      </AnimatePresence>
    </div>
  );
};
