import { API_BASE_URL } from '../../lib/config';
import React, { useEffect, useState, useMemo } from 'react';
import { 
  CheckCircle2, 
  Circle, 
  Loader2, 
  Users, 
  AlertTriangle, 
  PlusCircle, 
  ChevronRight,
  ShieldCheck,
  Split,
  Globe,
  Layers,
  ArrowUpRight,
  Calendar,
  ChevronDown
} from 'lucide-react';
import { cn } from '../../lib/utils';
import { motion, AnimatePresence } from 'framer-motion';
import { useAuth } from '../../context/AuthContext';

interface Event {
  id: number;
  title: string;
  type: string;
  status: string;
  department: string;
  institution: string;
  academicYears: string[];
  targetedSections: string[];
  category: string;
  createdAt?: string;
  updatedAt?: string;
  targetedBatch?: string;
}

interface ClassMapping {
  institution: string;
  department: string;
  academicYear: string;
  sections: string[];
}

const CATEGORIES = [
  { id: 'GUEST_LECTURE', label: 'Guest Lectures', matchTypes: ['Guest Lecture', 'Workshop', 'Seminar'] },
  { id: 'ALUMNI_LECTURE', label: 'Alumni Lectures', matchTypes: ['Alumni Lecture'] },
  { id: 'CONFERENCE', label: 'Conference', matchTypes: ['Conference'] },
  { id: 'INDUSTRIAL_VISIT', label: 'Industrial Visit', matchTypes: ['Industrial Visit'] },
  { id: 'TECHFEST', label: 'Techfest', matchTypes: ['Techfest'] },
  { id: 'PROF_SOCIETY', label: 'Prof. Society Activities', matchTypes: ['Club', 'Professional Society'] },
  { id: 'INSTITUTIONAL', label: 'Institutional Events', matchTypes: ['Institutional'] },
];

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

const DepartmentCard: React.FC<{ 
  deptName: string; 
  events: Event[]; 
  selectedBatch: string;
  index: number;
  isApplicable: boolean;
  sections: string[];
  batches: any[];
  onIncompleteClick?: (data: any) => void;
  isCompact?: boolean;
}> = ({ deptName, events, selectedBatch, index, isApplicable, sections, batches, onIncompleteClick, isCompact }) => {
  const activeBatchesForYear = useMemo(() => {
    return batches.filter(b => 
      b.department === deptName && 
      b.classes?.some((cls: string) => cls.startsWith(selectedBatch))
    );
  }, [batches, deptName, selectedBatch]);

  const hasCustomBatches = activeBatchesForYear.length > 0;

  const departmentEvents = events.filter(e => {
    const status = e.status?.toUpperCase();
    const isDeptMatch = e.department?.trim().toLowerCase() === deptName.trim().toLowerCase();
    const isInstitutional = e.category?.toUpperCase() === 'INSTITUTIONAL';
    
    return (isDeptMatch || isInstitutional) && 
           (status === 'APPROVED' || status === 'COMPLETED' || status === 'PENDING_PR');
  });

  // Base requirement is 1 event per category per batch, or 1 if no custom batches exist
  const getRequiredCount = (catId: string) => {
    return 1;
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.05, duration: 0.5 }}
      className={cn(
        "bg-white rounded-[2rem] flex flex-col h-full relative group transition-all",
        isCompact ? "border-none shadow-none p-0" : "border border-slate-100 overflow-hidden premium-shadow p-0"
      )}
    >
      <div className={cn("p-6 border-b border-slate-50", isCompact ? "bg-white p-0 pb-4 border-none" : "bg-slate-50/30 p-8")}>
        <div className="flex items-center justify-between gap-4 mb-2">
          <h3 className={cn("font-black text-text-dark group-hover:text-brand-indigo transition-colors", isCompact ? "text-lg" : "text-2xl tracking-tight")}>{deptName}</h3>
          <div className="flex items-center gap-2">
            {!isApplicable ? (
              <span className="px-3 py-1 bg-amber-50 text-amber-600 rounded-full border border-amber-100 text-[8px] font-black uppercase tracking-widest">Inert Batch</span>
            ) : hasCustomBatches ? (
              <span className="px-3 py-1 bg-brand-glow text-brand-indigo rounded-full border border-brand-indigo/10 text-[8px] font-black uppercase tracking-widest flex items-center gap-1.5">
                <Layers className="w-2.5 h-2.5" />
                {activeBatchesForYear.length} Batches
              </span>
            ) : (
              <span className="px-3 py-1 bg-brand-glow text-brand-indigo rounded-full border border-brand-indigo/10 text-[8px] font-black uppercase tracking-widest flex items-center gap-1.5">
                <Users className="w-2.5 h-2.5" />
                {sections.length} Sections
              </span>
            )}
          </div>
        </div>
        <p className="text-[10px] font-black uppercase tracking-[0.2em] text-text-muted">
          Academic Year Profile: <span className="text-brand-indigo">{selectedBatch}</span>
        </p>
      </div>
      
      <div className={cn("space-y-6 flex-1 bg-white", isCompact ? "p-0" : "p-8")}>
        {CATEGORIES.map((cat) => {
          const matchingEvents = departmentEvents.filter(event => {
            const matchesType = cat.matchTypes.some(mt => mt.toLowerCase() === event.type?.toLowerCase());
            const eventBatches = event.academicYears?.map(y => y.trim().toLowerCase()) || [];
            const isInstitutional = event.category?.toUpperCase() === 'INSTITUTIONAL';
            const batchMatches = eventBatches.length === 0 || eventBatches.includes(selectedBatch.trim().toLowerCase());
            
            return matchesType && (isInstitutional ? batchMatches : eventBatches.includes(selectedBatch.trim().toLowerCase()));
          });

          const currentCount = matchingEvents.length;
          
          let coveredSections = new Set<string>();
          matchingEvents.forEach(e => {
            if (e.category === 'INSTITUTIONAL' || !e.targetedSections || e.targetedSections.length === 0) {
              sections.forEach(s => coveredSections.add(s));
            } else {
              e.targetedSections.forEach(s => coveredSections.add(s));
            }
          });

          const eventsRequired = hasCustomBatches ? activeBatchesForYear.length : getRequiredCount(cat.id);
          const missingSections = sections.filter(s => !coveredSections.has(s));
          
          const coveredBatches = activeBatchesForYear.filter(b => 
            matchingEvents.some(e => e.category === 'INSTITUTIONAL' || !e.targetedBatch || e.targetedBatch === b.name)
          );
          const missingBatches = activeBatchesForYear.filter(b => !coveredBatches.includes(b));
          
          const isFullyCovered = hasCustomBatches 
            ? (missingBatches.length === 0 && matchingEvents.length > 0)
            : (missingSections.length === 0 && currentCount > 0) || (currentCount >= eventsRequired);
          
          return (
            <div 
              key={cat.id} 
              className="group/item relative"
              onClick={() => !isFullyCovered && onIncompleteClick?.({
                department: deptName,
                eventType: cat.matchTypes[0],
                academicYears: [selectedBatch]
              })}
            >
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-4">
                  <div className={cn(
                    "w-10 h-10 rounded-xl flex items-center justify-center transition-all border shadow-sm",
                    isFullyCovered ? "bg-emerald-500 border-emerald-400 text-white" : currentCount > 0 ? "bg-brand-indigo border-brand-indigo text-white" : "bg-white border-slate-100 text-slate-300"
                  )}>
                    {isFullyCovered ? <ShieldCheck className="w-5 h-5" /> : currentCount > 0 ? <Layers className="w-5 h-5" /> : <Circle className="w-5 h-5" />}
                  </div>
                  <div>
                    <span className={cn(
                      "text-sm font-black tracking-tight",
                      isFullyCovered ? "text-text-dark" : currentCount > 0 ? "text-brand-indigo" : "text-text-muted"
                    )}>
                      {cat.label}
                    </span>
                    <div className="flex items-center gap-2 mt-0.5">
                      <span className={cn(
                        "text-[8px] font-black uppercase tracking-[0.1em]",
                        isFullyCovered ? "text-emerald-500" : currentCount > 0 ? "text-brand-indigo" : "text-slate-400"
                      )}>
                        {isFullyCovered ? 'Complete Coverage' : missingSections.length > 0 && currentCount > 0 ? 'Partial Coverage' : 'Awaiting Proposals'}
                      </span>
                    </div>
                  </div>
                </div>
                <div className="flex flex-col items-end">
                   <div className={cn(
                    "px-3 py-1.5 rounded-xl text-[10px] font-black tracking-widest border transition-all",
                    isFullyCovered ? "bg-emerald-50 text-emerald-600 border-emerald-100" : currentCount > 0 ? "bg-brand-glow text-brand-indigo border-brand-indigo/10" : "bg-slate-50 text-text-muted border-slate-100"
                  )}>
                    {currentCount}/{eventsRequired}
                  </div>
                </div>
              </div>

              <div className="h-1.5 bg-slate-100 rounded-full overflow-hidden mb-3">
                <motion.div 
                  initial={{ width: 0 }}
                  animate={{ width: `${Math.min((currentCount / eventsRequired) * 100, 100)}%` }}
                  className={cn(
                    "h-full rounded-full transition-all duration-1000",
                    isFullyCovered ? "bg-emerald-500" : "bg-brand-indigo"
                  )}
                />
              </div>

              {hasCustomBatches && missingBatches.length > 0 && currentCount > 0 && (
                <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="flex items-start gap-2 p-3 bg-red-50 rounded-xl border border-red-100 mt-2">
                  <AlertTriangle className="w-3.5 h-3.5 text-red-500 shrink-0" />
                  <div>
                    <p className="text-[9px] font-black text-red-600 uppercase tracking-widest">Batches Left Out</p>
                    <p className="text-[10px] font-bold text-red-700">{missingBatches.map(b => b.name).join(', ')}</p>
                  </div>
                </motion.div>
              )}

              {!hasCustomBatches && missingSections.length > 0 && currentCount > 0 && (
                <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: 'auto' }} className="flex items-start gap-2 p-3 bg-red-50 rounded-xl border border-red-100 mt-2">
                  <AlertTriangle className="w-3.5 h-3.5 text-red-500 shrink-0" />
                  <div>
                    <p className="text-[9px] font-black text-red-600 uppercase tracking-widest">Sections Left Out</p>
                    <p className="text-[10px] font-bold text-red-700">{missingSections.join(', ')}</p>
                  </div>
                </motion.div>
              )}
            </div>
          );
        })}
      </div>
    </motion.div>
  );
};

export const InstitutionalChecklist: React.FC<{ 
  isCompact?: boolean;
  isGlobalView?: boolean;
  onIncompleteClick?: (data: any) => void;
}> = ({ isCompact, isGlobalView, onIncompleteClick }) => {
  const { user } = useAuth();
  const [events, setEvents] = useState<Event[]>([]);
  const [classes, setClasses] = useState<ClassMapping[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedBatch, setSelectedBatch] = useState<string>('');
  const [batches, setBatches] = useState<any[]>([]);

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

  const fetchData = async () => {
    try {
      const [eventsRes, classesRes, batchesRes] = await Promise.all([
        fetch(API_BASE_URL + '/api/events'),
        fetch(API_BASE_URL + '/api/classes'),
        fetch(API_BASE_URL + '/api/batches')
      ]);

      if (eventsRes.ok && classesRes.ok) {
        const [eventsData, classesData] = await Promise.all([
          eventsRes.json(),
          classesRes.json()
        ]);
        const batchesData = batchesRes.ok ? await batchesRes.json() : [];
        setEvents(eventsData);
        setClasses(classesData);
        setBatches(batchesData);
        
        const yearBatches = Array.from(new Set(classesData.map((c: any) => c.academicYear.trim()))).sort().reverse();
        if (yearBatches.length > 0 && !selectedBatch) {
          setSelectedBatch(yearBatches[0] as string);
        }
      }
    } catch (error) {
      console.error('Failed to fetch checklist data:', error);
    } finally {
      setLoading(false);
    }
  };

  const allBatches = useMemo(() => {
    return Array.from(new Set(classes.map(c => c.academicYear.trim()))).sort().reverse();
  }, [classes]);

  const filteredDepartments = useMemo(() => {
    let depts = ALL_DEPARTMENTS;
    if (user?.role === 'PRINCIPAL' || user?.role === 'ADMIN') depts = ALL_DEPARTMENTS;
    else if (isGlobalView && user?.role === 'HOD') depts = ALL_DEPARTMENTS;
    else {
      const userDepts = user?.department ? user.department.split(',').map(d => d.trim().toLowerCase()) : [];
      depts = ALL_DEPARTMENTS.filter(d => userDepts.includes(d.toLowerCase()));
    }

    // Recent items at top logic: Sort departments by the date of their latest event
    return [...depts].sort((a, b) => {
      const latestA = events.filter(e => e.department === a || e.category === 'INSTITUTIONAL').reduce((max, e) => Math.max(max, new Date(e.updatedAt || e.createdAt || 0).getTime()), 0);
      const latestB = events.filter(e => e.department === b || e.category === 'INSTITUTIONAL').reduce((max, e) => Math.max(max, new Date(e.updatedAt || e.createdAt || 0).getTime()), 0);
      return latestB - latestA;
    });
  }, [user, isGlobalView, events]);

  if (loading) {
    return (
      <div className="flex items-center justify-center p-20">
        <Loader2 className="w-8 h-8 text-brand-indigo animate-spin" />
      </div>
    );
  }

  return (
    <div className={cn("space-y-8", isCompact ? "space-y-4" : "space-y-8")}>
      {!isCompact && (
        <div className="bg-white p-8 rounded-[3rem] border border-slate-100 premium-shadow flex flex-col md:flex-row md:items-center justify-between gap-8 relative overflow-hidden">
          {/* Adjusted Badge Position to prevent overlapping with dropdown */}
          <div className="absolute top-4 left-4">
            <div className="px-3 py-1 bg-emerald-50 text-emerald-600 rounded-full border border-emerald-100 flex items-center gap-2">
              <div className="w-1.5 h-1.5 bg-emerald-500 rounded-full animate-pulse" />
              <span className="text-[8px] font-black uppercase tracking-widest whitespace-nowrap">Audit Engine Live</span>
            </div>
          </div>

          <div className="pt-6 md:pt-0">
            <h2 className="text-3xl font-black text-text-dark tracking-tight mb-2">Academic Audit</h2>
            <p className="text-xs font-bold text-text-muted flex items-center gap-2">
              <ShieldCheck className="w-4 h-4 text-emerald-500" />
              Monitoring department-wide compliance and session coverage.
            </p>
          </div>

          <div className="flex items-center gap-4 bg-slate-50 p-4 rounded-3xl group relative min-w-[240px]">
            <div className="flex flex-col flex-1">
              <span className="text-[9px] font-black uppercase tracking-widest text-text-muted mb-1 ml-2">Audit Year</span>
              <div className="relative">
                <select 
                  value={selectedBatch}
                  onChange={(e) => setSelectedBatch(e.target.value)}
                  className="w-full bg-transparent text-brand-indigo font-black text-lg outline-none cursor-pointer appearance-none relative z-10 pr-10"
                >
                  {allBatches.map(batch => <option key={batch} value={batch}>{batch}</option>)}
                </select>
                <ChevronDown className="absolute right-2 top-1/2 -translate-y-1/2 w-5 h-5 text-brand-indigo pointer-events-none transition-transform group-hover:translate-y-[-40%]" />
              </div>
            </div>
            <div className="w-12 h-12 bg-brand-indigo text-white rounded-xl flex items-center justify-center shadow-lg group-hover:scale-110 transition-all shrink-0">
              <Calendar className="w-6 h-6" />
            </div>
          </div>
        </div>
      )}

      <div className={cn(
        "grid",
        isCompact 
          ? "grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6" 
          : "grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-10"
      )}>
        {filteredDepartments.map((deptName, idx) => {
          const deptClasses = classes.filter(c => c.department === deptName && c.academicYear.trim() === selectedBatch.trim());
          const sections = deptClasses.reduce((acc, c) => [...acc, ...c.sections], [] as string[]);
          
          return (
            <DepartmentCard 
              key={`${deptName}-${selectedBatch}`} 
              deptName={deptName} 
              events={events} 
              selectedBatch={selectedBatch}
              index={idx}
              isApplicable={deptClasses.length > 0}
              sections={sections}
              batches={batches}
              onIncompleteClick={onIncompleteClick}
              isCompact={isCompact}
            />
          );
        })}
      </div>
    </div>
  );
};
