import React from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { CheckCircle2, Circle, AlertCircle, Clock, XCircle, ShieldCheck, Flag } from 'lucide-react';
import { cn } from '../../lib/utils';

export type Event = {
  id: number;
  title: string;
  startDate: string;
  endDate: string;
  location: string;
  category: string;
  type: string;
  institution: string;
  department: string;
  status: 'REQUESTED' | 'APPROVED' | 'COMPLETED' | 'CANCELLED' | 'PENDING_PR' | 'HOD_REJECTED' | 'PRINCIPAL_REJECTED';
  rejectionReason?: string;
  guestName?: string;
  proposer?: {
    email: string;
    fullName: string;
  };
  createdAt?: string;
  updatedAt?: string;
}

export const StatusTimeline: React.FC<{ event: Event; compact?: boolean }> = ({ event, compact }) => {
  const stages = [
    { id: 'REQUESTED', label: 'Proposal Raised', icon: Clock },
    { id: 'PENDING_PR', label: 'HoD Review', icon: ShieldCheck },
    { id: 'APPROVED', label: 'Principal Approval', icon: CheckCircle2 },
    { id: 'COMPLETED', label: 'Event Success', icon: Flag }
  ];

  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 now = new Date();
  const endDate = parseDate(event.endDate);
  
  const isAutoCompleted = event.status === 'APPROVED' && endDate && now > endDate;
  const isManuallyCompleted = event.status === 'COMPLETED';
  const effectiveStatus = (isAutoCompleted || isManuallyCompleted) ? 'COMPLETED' : event.status;

  const isHODRejected = effectiveStatus === 'HOD_REJECTED';
  const isPRRejected = effectiveStatus === 'PRINCIPAL_REJECTED';
  const isCancelled = effectiveStatus === 'CANCELLED';
  const isRejected = isHODRejected || isPRRejected || isCancelled;

  let currentStageIdx = stages.findIndex(s => s.id === effectiveStatus);
  if (currentStageIdx === -1) {
    if (isHODRejected) currentStageIdx = 1;
    else if (isPRRejected) currentStageIdx = 2;
    else if (isCancelled) currentStageIdx = 0;
    else currentStageIdx = 0;
  }

  return (
    <div className={cn("w-full", compact ? "py-2 space-y-4" : "py-6 space-y-8")}>
      <div className="relative flex items-center justify-between w-full px-4">
        <div className="absolute left-10 right-10 h-[2px] bg-slate-100 top-[18px]" />
        
        {!isRejected && (
          <motion.div 
            initial={{ width: 0 }}
            animate={{ width: `calc(${(currentStageIdx / (stages.length - 1)) * 100}%)` }}
            className="absolute left-10 h-[2px] bg-emerald-500 top-[18px] origin-left transition-all duration-1000"
          />
        )}

        {stages.map((stage, i) => {
          const isPast = i < currentStageIdx;
          const isCurrent = i === currentStageIdx;
          const isFuture = i > currentStageIdx;
          
          const stageRejected = isRejected && isCurrent;
          const stageCompleted = isPast || (isCurrent && !isRejected);

          return (
            <div key={stage.id} className="relative z-10 flex flex-col items-center">
              <motion.div
                initial={false}
                animate={{
                  scale: isCurrent ? 1.1 : 1,
                  backgroundColor: stageRejected ? "#ef4444" : stageCompleted ? "#10b981" : "#f1f5f9",
                  borderColor: stageRejected ? "#fee2e2" : stageCompleted ? "#d1fae5" : "#fff"
                }}
                className={cn(
                  "w-9 h-9 rounded-full flex items-center justify-center border-4 shadow-sm transition-all duration-500",
                  stageRejected ? "text-white" : stageCompleted ? "text-white" : "text-slate-300"
                )}
              >
                {stageRejected ? <XCircle className="w-5 h-5" /> : 
                 stageCompleted ? <CheckCircle2 className="w-5 h-5" /> : 
                 <stage.icon className="w-4 h-4" />}
              </motion.div>

              {!compact && (
                <div className="absolute top-12 flex flex-col items-center min-w-[100px]">
                  <span className={cn(
                    "text-[8px] font-black uppercase tracking-[0.2em] whitespace-nowrap",
                    stageRejected ? "text-red-500" : stageCompleted ? "text-emerald-600" : "text-slate-400"
                  )}>
                    {stageRejected ? (isHODRejected ? 'HoD Rejected' : isPRRejected ? 'PR Rejected' : 'Cancelled') : stage.label}
                  </span>
                  
                  {isCurrent && !isRejected && (
                    <motion.span 
                      animate={{ opacity: [0.4, 1, 0.4] }}
                      transition={{ repeat: Infinity, duration: 2 }}
                      className="text-[6px] font-bold text-brand-indigo mt-1 uppercase tracking-tighter"
                    >
                      Current Phase
                    </motion.span>
                  )}
                </div>
              )}
            </div>
          );
        })}
      </div>

      {compact && (
        <div className="text-center pt-2">
          <span className={cn(
            "text-[9px] font-black uppercase tracking-[0.15em]",
            isRejected ? "text-red-500 bg-red-50 px-3 py-1 rounded-full border border-red-100" : "text-brand-indigo bg-brand-glow px-3 py-1 rounded-full border border-brand-indigo/10"
          )}>
            Status: {isRejected ? (isHODRejected ? 'HoD Rejected' : isPRRejected ? 'PR Rejected' : 'Cancelled') : stages[currentStageIdx]?.label}
          </span>
        </div>
      )}

      <AnimatePresence>
        {isRejected && event.rejectionReason && (
          <motion.div 
            initial={{ opacity: 0, y: 10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mt-16 p-6 bg-red-50/50 border border-red-100 rounded-[2rem] flex gap-4 items-start"
          >
            <div className="w-10 h-10 bg-red-500 rounded-xl flex items-center justify-center shrink-0 shadow-lg shadow-red-200">
              <AlertCircle className="w-5 h-5 text-white" />
            </div>
            <div>
              <p className="text-[10px] font-black uppercase tracking-widest text-red-500 mb-1">Feedback Message</p>
              <p className="text-sm font-bold text-red-700 leading-relaxed italic">"{event.rejectionReason}"</p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
};
