import React from 'react';
import { format } from 'date-fns';
import { Circle, Clock, Edit2, Trash2, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { useAuth } from '@/contexts/AuthContext';
import { parseLocalDate } from '@/lib/dateUtils';

export default function ViolationTimelineManager({ entries = [], onEdit, onDelete }) {
  const { userRole } = useAuth();
  const canManage = ['admin', 'manager', 'employee'].includes(userRole?.role);

  const sortedEntries = [...entries].sort((a, b) => parseLocalDate(b.date || b.created_at) - parseLocalDate(a.date || a.created_at));

  const getStageColor = (stage) => {
    switch (stage) {
      case 'First Notice': return 'bg-blue-100 text-blue-700 border-blue-200';
      case 'Second Notice': return 'bg-orange-100 text-orange-700 border-orange-200';
      case 'Third & Final Notice': return 'bg-red-100 text-red-700 border-red-200';
      case 'Fined': return 'bg-slate-800 text-white border-slate-700';
      case 'Resolved': return 'bg-green-100 text-green-700 border-green-200';
      case 'Escalated': return 'bg-purple-100 text-purple-700 border-purple-200';
      default: return 'bg-muted text-muted-foreground';
    }
  };

  if (sortedEntries.length === 0) {
    return (<div className="flex flex-col items-center justify-center py-12 text-center text-muted-foreground bg-muted/30 rounded-lg border border-dashed"><Clock className="w-10 h-10 mb-2 opacity-50" /><p className="text-sm font-medium">No timeline entries yet</p></div>);
  }

  return (
    <div className="space-y-0 relative pl-4 border-l ml-3 py-2">
      {sortedEntries.map((entry) => {
        const rawDate = entry.date || entry.created_at;
        const parsedDate = rawDate ? parseLocalDate(rawDate) : null;
        const isValidDate = parsedDate && !isNaN(parsedDate.getTime());
        const eventLabel = entry.stage || entry.status || entry.action;
        const description = entry.description || entry.details || 'No description';
        const recordedBy = entry.recorded_by_name || entry.created_by || entry.metadata?.performed_by_name;
        return (
        <div key={entry.id} className="relative pb-8 last:pb-0 group">
          <div className="absolute -left-[21px] top-1 bg-card p-1 rounded-full border shadow-sm"><Circle className="w-2.5 h-2.5 fill-primary text-primary" /></div>
          <div className="flex flex-col gap-2">
            <div className="flex items-start justify-between">
              <div className="flex flex-wrap items-center gap-2">
                <span className="text-sm font-medium">{isValidDate ? format(parsedDate, 'MMM d, yyyy') : 'No date'}</span>
                {eventLabel && <Badge variant="outline" className={cn("text-[10px]", getStageColor(eventLabel))}>{eventLabel}</Badge>}
              </div>
              {canManage && (
                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  {onEdit && <Button variant="ghost" size="icon" className="h-7 w-7" onClick={() => onEdit(entry)}><Edit2 className="w-3.5 h-3.5" /></Button>}
                  {onDelete && <Button variant="ghost" size="icon" className="h-7 w-7 text-destructive" onClick={() => onDelete(entry.id)}><Trash2 className="w-3.5 h-3.5" /></Button>}
                </div>
              )}
            </div>
            <p className="text-sm text-muted-foreground whitespace-pre-wrap">{description}</p>
            {recordedBy && <div className="flex items-center text-xs text-muted-foreground"><User className="w-3 h-3 mr-1" />{typeof recordedBy === 'object' ? recordedBy.email : recordedBy}</div>}
          </div>
        </div>
        );
      })}
    </div>
  );
}
