import { API_BASE_URL } from '../../lib/config';
import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Calendar as CalendarIcon, 
  Clock, 
  CheckCircle2, 
  AlertCircle, 
  TrendingUp, 
  Users, 
  MapPin,
  ChevronRight,
  Plus,
  ShieldCheck,
  Zap,
  ArrowUpRight,
  Target,
  BarChart3,
  LayoutDashboard,
  Bell,
  GraduationCap,
  Save,
  Check
} from 'lucide-react';
import { useAuth } from '../../context/AuthContext';
import { InstitutionalChecklist } from './InstitutionalChecklist';
import { StatusTimeline, type Event } from './EventStatusTimeline';
import { InstitutionalCalendar } from './InstitutionalCalendar';
import { VenueTimeline } from './VenueTimeline';
import { PrincipalMasterChecklist } from './PrincipalMasterChecklist';
import { VenuesAtGlance } from './VenuesAtGlance';
import { FacultyEventManagement } from './FacultyEventManagement';
import { cn } from '../../lib/utils';
import { format, formatDistanceToNow } from 'date-fns';

interface OverviewProps {
  userEvents: any[];
  onNavigate: (id: string) => void;
  onIncompleteClick: (data: any) => void;
  onCalendarPropose: (date: string) => void;
  onClubEventClick: (data: any) => void;
  onEditEvent?: (event: any) => void;
}

export const Overview: React.FC<OverviewProps> = ({ 
  userEvents, 
  onNavigate, 
  onIncompleteClick, 
  onCalendarPropose,
  onClubEventClick,
  onEditEvent
}) => {
  const { user } = useAuth();
  const [stats, setStats] = useState({
    upcoming: 0,
    pending: 0,
    completed: 0,
    budget: '₹0'
  });
  const [alerts, setAlerts] = useState<Array<{type: string, msg: string, time: string}>>([]);
  const { login } = useAuth();
  const [strengthInput, setStrengthInput] = useState<number>(user?.classStrength || 0);
  const [isSavingStrength, setIsSavingStrength] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);

  const handleSaveStrength = async () => {
    if (!user) return;
    setIsSavingStrength(true);
    try {
      const response = await fetch(`${API_BASE_URL}/api/admin/users/${user.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...user, classStrength: strengthInput })
      });
      if (response.ok) {
        const updatedUser = await response.json();
        login(updatedUser);
        setSaveSuccess(true);
        setTimeout(() => setSaveSuccess(false), 2000);
      }
    } catch (error) {
      console.error('Failed to update class strength:', error);
    } finally {
      setIsSavingStrength(false);
    }
  };

  useEffect(() => {
    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 calculateStats = (data: any[]) => {
      if (!Array.isArray(data)) return;
      const now = new Date();
      
      const upcoming = data.filter(e => {
        const d = parseDate(e.startDate);
        return e.status === 'APPROVED' && d && d > now;
      }).length;

      const pending = data.filter(e => e.status === 'REQUESTED' || e.status === 'PENDING_PR').length;
      
      const completed = data.filter(e => {
        const d = parseDate(e.endDate);
        return e.status === 'APPROVED' && d && d < now;
      }).length;
      
      const totalBudget = data
        .filter(e => e.status === 'APPROVED')
        .reduce((acc, e) => acc + (e.budget || 0), 0);
      
      let budgetDisplay = `₹${totalBudget.toLocaleString()}`;
      if (totalBudget >= 100000) {
        budgetDisplay = `₹${(totalBudget / 100000).toFixed(1)}L`;
      } else if (totalBudget >= 1000) {
        budgetDisplay = `₹${(totalBudget / 1000).toFixed(1)}K`;
      }

      setStats({
        upcoming,
        pending,
        completed,
        budget: budgetDisplay
      });

      const generatedAlerts: any[] = [];
      const sortedEvents = [...data].sort((a, b) => {
        return new Date(b.updatedAt || b.createdAt || 0).getTime() - new Date(a.updatedAt || a.createdAt || 0).getTime();
      });

      for (const event of sortedEvents) {
        if (generatedAlerts.length >= 4) break;
        const dateToUse = event.updatedAt || event.createdAt;
        if (!dateToUse) continue;
        
        let timeStr = formatDistanceToNow(new Date(dateToUse), { addSuffix: true })
          .replace('about ', '')
          .replace(' minutes', 'm')
          .replace(' minute', 'm')
          .replace(' hours', 'h')
          .replace(' hour', 'h')
          .replace(' days', 'd')
          .replace(' day', 'd');
        
        if (event.conflictMessage) {
          generatedAlerts.push({ type: 'warning', msg: `Conflict: ${event.title}`, time: timeStr });
        } else if (event.status === 'REJECTED') {
          generatedAlerts.push({ type: 'error', msg: `Rejected: ${event.title}`, time: timeStr });
        } else if (event.status === 'APPROVED') {
          generatedAlerts.push({ type: 'success', msg: `Approved: ${event.title}`, time: timeStr });
        } else if (event.status === 'REQUESTED' || event.status === 'PENDING_PR') {
          generatedAlerts.push({ type: 'info', msg: `New proposal: ${event.title}`, time: timeStr });
        }
      }
      
      if (generatedAlerts.length === 0) {
        generatedAlerts.push({ type: 'info', msg: 'No recent activity', time: 'Just now' });
      }

      setAlerts(generatedAlerts);
    };

    if (userEvents && userEvents.length > 0) {
      calculateStats(userEvents);
    } else {
      fetch(API_BASE_URL + '/api/events')
        .then(res => {
          if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
          return res.json();
        })
        .then(data => {
          if (Array.isArray(data)) {
            const statsData = (user?.role === 'PRINCIPAL' || user?.role === 'ADMIN')
              ? data 
              : data.filter(e => {
                  if (e.proposer?.email === user?.email) return true;
                  const userDepts = user?.department ? user.department.split(',').map(d => d.trim().toLowerCase()) : [];
                  return userDepts.includes(e.department?.trim().toLowerCase());
                });
            calculateStats(statsData);
          }
        })
        .catch(err => console.error("Stats fetch error:", err));
    }
  }, [userEvents, user]);

  return (
    <div className="space-y-8 animate-in fade-in duration-700">
      {/* Welcome Bar - Subtle */}
      <div className="flex items-center justify-between mb-2">
        <div>
          <h2 className="text-2xl font-black text-brand-navy tracking-tight">
            Welcome back, <span className="text-brand-indigo">{user?.fullName?.split(' ')[0]}</span>
          </h2>
          <p className="text-xs font-bold text-slate-400 uppercase tracking-widest mt-1">
            Institutional Dashboard • {format(new Date(), 'EEEE, MMMM do')}
          </p>
        </div>
      </div>

      {/* Principal Master Checklist - Only for Principal Desk */}
      {user?.role === 'PRINCIPAL' && (
        <PrincipalMasterChecklist />
      )}

      {user?.role === 'FACULTY' && user?.isClassIncharge && (
        <div className="bg-brand-indigo/5 border border-brand-indigo/10 rounded-[1.5rem] p-6 mb-8 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div className="flex items-start gap-4">
            <div className="w-12 h-12 rounded-xl bg-brand-indigo text-white flex items-center justify-center shrink-0 shadow-sm">
              <GraduationCap className="w-6 h-6" />
            </div>
            <div>
              <h3 className="text-lg font-black text-brand-navy tracking-tight">Class Incharge Dashboard</h3>
              <p className="text-xs font-bold text-slate-500 mt-1">
                Assigned Class: <span className="text-brand-indigo uppercase tracking-wider">{user.inchargeClass} • {user.inchargeBatch} • Sec {user.inchargeSection}</span>
              </p>
            </div>
          </div>
          
          <div className="flex items-center gap-4 bg-white p-2 pr-4 rounded-xl shadow-sm border border-slate-100">
            <div className="flex flex-col pl-3">
              <label className="text-[9px] font-black uppercase tracking-widest text-slate-400">Class Strength</label>
              <input 
                type="number"
                min="1"
                value={strengthInput || ''}
                onChange={(e) => setStrengthInput(parseInt(e.target.value) || 0)}
                className="w-20 text-lg font-black text-brand-navy focus:outline-none placeholder:text-slate-200"
                placeholder="0"
              />
            </div>
            <button
              onClick={handleSaveStrength}
              disabled={isSavingStrength || strengthInput === user.classStrength}
              className={cn(
                "p-2.5 rounded-lg transition-all flex items-center justify-center text-white min-w-[40px]",
                saveSuccess ? "bg-emerald-500" :
                strengthInput !== user.classStrength ? "bg-brand-indigo hover:shadow-md hover:scale-105 active:scale-95" :
                "bg-slate-200 text-slate-400"
              )}
            >
              {isSavingStrength ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> :
               saveSuccess ? <Check className="w-4 h-4" /> :
               <Save className="w-4 h-4" />}
            </button>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        {/* Row 1: Live Status and Analytics */}
        <div className="lg:col-span-12 flex flex-col gap-8">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
            <div className="w-full">
              <div className="card-widget">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="font-black text-brand-navy flex items-center gap-2">
                    Live Status
              </h3>
              <div className="flex items-center gap-1.5">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span className="text-[10px] font-black text-emerald-500 uppercase tracking-widest">Active</span>
              </div>
            </div>
            
            <div className="grid grid-cols-2 gap-4">
              {[
                { label: 'Upcoming', value: stats.upcoming, icon: CalendarIcon, color: 'text-indigo-600', bg: 'bg-indigo-50' },
                { label: 'Pending', value: stats.pending, icon: Bell, color: 'text-amber-600', bg: 'bg-amber-50' },
                { label: 'Finished', value: stats.completed, icon: CheckCircle2, color: 'text-emerald-600', bg: 'bg-emerald-50' },
                { label: 'Budget', value: stats.budget, icon: TrendingUp, color: 'text-slate-600', bg: 'bg-slate-50' },
              ].map((stat) => (
                <div key={stat.label} className={cn("p-4 rounded-2xl border border-slate-100/50", stat.bg)}>
                  <div className="flex items-center gap-3 mb-2">
                    <stat.icon className={cn("w-4 h-4", stat.color)} />
                    <span className="text-[9px] font-black uppercase tracking-widest text-slate-400">{stat.label}</span>
                  </div>
                  <p className="text-xl font-black text-brand-navy">{stat.value}</p>
                </div>
              ))}
            </div>

            <div className="mt-6 p-4 bg-brand-glow rounded-2xl border border-brand-indigo/10">
              <div className="flex items-center gap-3 mb-2">
                <Zap className="w-4 h-4 text-brand-indigo" />
                <span className="text-[10px] font-black uppercase tracking-widest text-brand-indigo">Quick Insight</span>
              </div>
              <p className="text-[11px] font-bold text-brand-indigo/70 leading-relaxed">
                {stats.pending > 0 
                  ? `You have ${stats.pending} proposals waiting for your review. Processing them now ensures timely venue booking.`
                  : "All systems clear. Your departmental compliance is currently at 100% for the current cycle."}
              </p>
            </div>
          </div>
        </div>

            <div className="w-full">
              <div className="card-widget">
                <div className="flex items-center justify-between mb-6">
                  <h3 className="font-black text-brand-navy flex items-center gap-2">
                    Analytics
                  </h3>
                  <BarChart3 className="w-4 h-4 text-slate-300" />
                </div>
                
                <div className="flex flex-col items-center justify-center py-4">
                  {(() => {
                    const total = userEvents.length;
                    const approvedCount = userEvents.filter(e => e.status === 'APPROVED' || e.status === 'COMPLETED').length;
                    const approvedPercentage = total > 0 ? approvedCount / total : 0;
                    
                    const techCount = userEvents.filter(e => ['workshop', 'seminar', 'conference', 'guest lecture', 'techfest'].includes((e.type || '').toLowerCase())).length;
                    const cultCount = userEvents.filter(e => (e.type || '').toLowerCase().includes('cultural')).length;
                    const sportsCount = userEvents.filter(e => (e.type || '').toLowerCase().includes('sport') || (e.type || '').toLowerCase().includes('athletic')).length;
                    const otherCount = total - (techCount + cultCount + sportsCount);

                    return (
                      <>
                        <div className="relative w-32 h-32 flex items-center justify-center">
                          <svg className="w-full h-full -rotate-90">
                            <circle cx="64" cy="64" r="58" fill="transparent" stroke="#f1f5f9" strokeWidth="12" />
                            <circle cx="64" cy="64" r="58" fill="transparent" stroke="#4f46e5" strokeWidth="12" strokeDasharray="364.4" strokeDashoffset={364.4 * (1 - approvedPercentage)} strokeLinecap="round" />
                          </svg>
                          <div className="absolute inset-0 flex flex-col items-center justify-center">
                            <span className="text-2xl font-black text-brand-navy">{total}</span>
                            <span className="text-[8px] font-black text-slate-400 uppercase tracking-widest">Events</span>
                          </div>
                        </div>
                        
                        <div className="grid grid-cols-2 gap-x-8 gap-y-3 mt-8 w-full">
                          {[
                            { label: 'Technical', color: 'bg-brand-indigo', count: techCount },
                            { label: 'Cultural', color: 'bg-emerald-500', count: cultCount },
                            { label: 'Sports', color: 'bg-amber-500', count: sportsCount },
                            { label: 'Other', color: 'bg-slate-400', count: otherCount },
                          ].map(cat => (
                            <div key={cat.label} className="flex items-center justify-between w-full">
                              <div className="flex items-center gap-2">
                                <div className={cn("w-2 h-2 rounded-full", cat.color)} />
                                <span className="text-[10px] font-bold text-slate-500">{cat.label}</span>
                              </div>
                              <span className="text-[10px] font-black text-brand-navy ml-1">{cat.count}</span>
                            </div>
                          ))}
                        </div>
                      </>
                    );
                  })()}
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Today's Tasks / My Proposals */}
        <div className="lg:col-span-12">
          {(user?.role === 'PRINCIPAL' || user?.role === 'ADMIN') ? (
            <div className="card-widget flex flex-col">
              <div className="flex items-center justify-between mb-6">
                <h3 className="font-black text-brand-navy flex items-center gap-2">
                  Today's Tasks
                  <span className="bg-slate-100 text-slate-500 text-[10px] px-2 py-0.5 rounded-full">
                    {stats.pending}
                  </span>
                </h3>
                <button 
                  onClick={() => onNavigate('checklist')}
                  className="text-[10px] font-black text-brand-indigo uppercase tracking-widest hover:underline"
                >
                  See All
                </button>
              </div>
              <div className="w-full">
                <InstitutionalChecklist isCompact onIncompleteClick={onIncompleteClick} />
              </div>
            </div>
          ) : (
            <FacultyEventManagement 
              events={userEvents} 
              onEditEvent={onEditEvent || (() => {})} 
            />
          )}
        </div>

        <div className="lg:col-span-12">
          <VenuesAtGlance events={userEvents} />
        </div>

        {/* Row 2: Upcoming Events & Alerts */}


        <div className="lg:col-span-8">
          <div className="card-widget">
            <div className="flex items-center justify-between mb-8">
              <div>
                <h3 className="text-xl font-black text-brand-navy tracking-tight">Institutional Schedule</h3>
                <p className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-1">Unified view of all approved events & academic notes</p>
              </div>
              <div className="flex gap-2">
                 <div className="px-3 py-1.5 bg-slate-50 rounded-xl border border-slate-100">
                    <span className="text-[10px] font-black text-slate-400 uppercase tracking-widest">Master Feed</span>
                 </div>
              </div>
            </div>
            <div className="rounded-[1.5rem] overflow-hidden border border-slate-50">
              <InstitutionalCalendar compact onProposeEvent={onCalendarPropose} />
            </div>
          </div>
        </div>

        <div className="lg:col-span-4">
          <div className="card-widget h-full">
            <div className="flex items-center justify-between mb-6">
              <h3 className="font-black text-brand-navy flex items-center gap-2">
                Recent Alerts
              </h3>
              <button className="text-[10px] font-black text-brand-indigo uppercase tracking-widest hover:underline">
                Clear All
              </button>
            </div>
            
            <div className="space-y-4">
              {alerts.map((alert, i) => (
                <div key={i} className="flex gap-4 group">
                  <div className={cn(
                    "w-1 h-8 rounded-full mt-1 shrink-0",
                    alert.type === 'success' ? 'bg-emerald-500' : 
                    alert.type === 'warning' ? 'bg-amber-500' :
                    alert.type === 'error' ? 'bg-red-500' : 'bg-brand-indigo'
                  )} />
                  <div>
                    <p className="text-xs font-bold text-brand-navy leading-snug group-hover:text-brand-indigo transition-colors">{alert.msg}</p>
                    <span className="text-[9px] font-bold text-slate-400 uppercase tracking-widest">{alert.time}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>


      </div>
    </div>
  );
};
