"use client";

import { Skeleton } from "@/components/ui/skeleton";
import { format } from "date-fns";
import type { ComplaintHistoryRecord } from "@/types/modules/complaint";

type ComplaintTimelineProps = {
  histories: ComplaintHistoryRecord[];
  showContextSkeleton: boolean;
};

export function ComplaintTimeline({ histories, showContextSkeleton }: ComplaintTimelineProps) {
  return (
    <div className="rounded-xl border border-blue-100 bg-blue-50/40 p-4 shadow-sm">
      <h3 className="mb-4 text-sm font-semibold text-blue-900">Historial del Reclamo</h3>
      
      {showContextSkeleton ? (
        <div className="space-y-4 pl-2">
          <Skeleton className="h-12 w-full" />
          <Skeleton className="h-12 w-full" />
        </div>
      ) : !histories || histories.length === 0 ? (
        <div className="py-2 text-center text-xs text-slate-500 italic">
          No hay movimientos registrados.
        </div>
      ) : (
        <div className="relative pl-6">
          <div className="absolute left-2 top-1 bottom-1 w-0.5 rounded-full bg-blue-200" />
          
          <ul className="space-y-6">
            {histories.map((entry, idx) => {
              const label = entry.old_status 
                ? `Cambio: ${entry.old_status.name} ➜ ${entry.new_status.name}`
                : `Estado inicial: ${entry.new_status.name}`;
              
              const body = entry.comment || "";
              
              const when = entry.created_at; 

              const author = typeof entry.changed_by === 'object' 
                ? entry.changed_by?.name 
                : entry.changed_by || "Sistema";

              return (
                <li key={entry.id || idx} className="relative flex gap-3">
                  <span
                    className={`absolute -left-[1.2rem] top-1.5 flex h-3 w-3 rounded-full border-2 border-blue-500 ${
                      idx === 0 ? "bg-blue-600" : "bg-white"
                    }`}
                  />
                  <div className="flex-1 rounded-lg bg-white/80 px-3 py-2 shadow-sm border border-white">
                    <p className="text-sm font-medium text-slate-900">{label}</p>
                    
                    {body && (
                      <p className="mt-1 text-xs text-slate-600 italic">
                        "{body}"
                      </p>
                    )}
                    
                    <p className="mt-2 text-[10px] text-blue-800/80 font-medium uppercase tracking-tight">
                      {when} {author ? ` · POR: ${author}` : ""}
                    </p>
                  </div>
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </div>
  );
}