trello_fake/components/gantt/gantt-page.tsx

549 lines
24 KiB
TypeScript

"use client";
import { useState, useEffect, useMemo, useRef, useCallback } from "react";
import { useRouter } from "next/navigation";
import {
GanttChart as GanttIcon,
AlertCircle,
ChevronLeft,
ChevronRight,
Calendar,
History,
Clock,
Filter,
} from "lucide-react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { getProjects } from "@/lib/projectsService";
import { Project, ProjectStatus } from "@/types/project";
// Paleta de colores para proyectos
const PROJECT_COLORS = [
{ bg: "bg-blue-500", light: "bg-blue-100 dark:bg-blue-900/40", hex: "#3b82f6" },
{ bg: "bg-violet-500", light: "bg-violet-100 dark:bg-violet-900/40", hex: "#8b5cf6" },
{ bg: "bg-cyan-500", light: "bg-cyan-100 dark:bg-cyan-900/40", hex: "#06b6d4" },
{ bg: "bg-emerald-500", light: "bg-emerald-100 dark:bg-emerald-900/40", hex: "#10b981" },
{ bg: "bg-amber-500", light: "bg-amber-100 dark:bg-amber-900/40", hex: "#f59e0b" },
{ bg: "bg-rose-500", light: "bg-rose-100 dark:bg-rose-900/40", hex: "#f43f5e" },
{ bg: "bg-pink-500", light: "bg-pink-100 dark:bg-pink-900/40", hex: "#ec4899" },
{ bg: "bg-indigo-500", light: "bg-indigo-100 dark:bg-indigo-900/40", hex: "#6366f1" },
{ bg: "bg-teal-500", light: "bg-teal-100 dark:bg-teal-900/40", hex: "#14b8a6" },
{ bg: "bg-orange-500", light: "bg-orange-100 dark:bg-orange-900/40", hex: "#f97316" },
];
const STATUS_LABELS: Record<ProjectStatus, string> = {
"0": "Borrador",
"1": "Abierto",
"2": "Cerrado",
};
const MONTH_WIDTH_PX = 120; // Ancho fijo por mes en modo scroll
type ViewMode = "month" | "quarter" | "year";
type TimeRange = "future" | "past" | "all";
function getProjectColor(index: number) {
return PROJECT_COLORS[index % PROJECT_COLORS.length];
}
function formatDate(dateStr: string): string {
const date = new Date(dateStr);
return date.toLocaleDateString("es-ES", { day: "2-digit", month: "short", year: "numeric" });
}
function getDaysBetween(start: Date, end: Date): number {
return Math.ceil((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
}
function getMonthsBetween(start: Date, end: Date): { month: number; year: number; label: string }[] {
const months: { month: number; year: number; label: string }[] = [];
const current = new Date(start.getFullYear(), start.getMonth(), 1);
const endMonth = new Date(end.getFullYear(), end.getMonth(), 1);
while (current <= endMonth) {
months.push({
month: current.getMonth(),
year: current.getFullYear(),
label: current.toLocaleDateString("es-ES", { month: "short", year: "numeric" }),
});
current.setMonth(current.getMonth() + 1);
}
return months;
}
export default function GanttPage() {
const router = useRouter();
const [projects, setProjects] = useState<Project[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [viewMode, setViewMode] = useState<ViewMode>("month");
const [statusFilter, setStatusFilter] = useState<string>("all");
const [timeRange, setTimeRange] = useState<TimeRange>("all");
const [viewOffset, setViewOffset] = useState(0);
// Refs para sincronizar scroll vertical entre nombres y timeline
const namesRef = useRef<HTMLDivElement>(null);
const timelineRef = useRef<HTMLDivElement>(null);
const isSyncing = useRef(false);
const syncScroll = useCallback((source: "names" | "timeline") => {
if (isSyncing.current) return;
isSyncing.current = true;
const from = source === "names" ? namesRef.current : timelineRef.current;
const to = source === "names" ? timelineRef.current : namesRef.current;
if (from && to) {
to.scrollTop = from.scrollTop;
}
requestAnimationFrame(() => { isSyncing.current = false; });
}, []);
useEffect(() => {
async function loadProjects() {
try {
setLoading(true);
const data = await getProjects();
setProjects(data);
setError(null);
} catch (err) {
console.error("Error loading projects:", err);
setError("Error al cargar los proyectos");
} finally {
setLoading(false);
}
}
loadProjects();
}, []);
// Filtrar proyectos por estado
const statusFiltered = useMemo(() => {
if (statusFilter === "all") return projects;
return projects.filter(p => p.status === statusFilter);
}, [projects, statusFilter]);
// Filtrar por rango temporal
const filteredProjects = useMemo(() => {
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
if (timeRange === "future") {
return statusFiltered.filter(p => new Date(p.endDate) >= today);
} else if (timeRange === "past") {
return statusFiltered.filter(p => new Date(p.endDate) < today);
}
return statusFiltered; // "all"
}, [statusFiltered, timeRange]);
// Calcular meses del timeline completo
const allMonths = useMemo(() => {
if (filteredProjects.length === 0) {
const now = new Date();
const start = new Date(now.getFullYear(), now.getMonth() - 3, 1);
const end = new Date(now.getFullYear(), now.getMonth() + 3, 0);
return getMonthsBetween(start, end);
}
const allStartDates = filteredProjects.map(p => new Date(p.startDate));
const allEndDates = filteredProjects.map(p => new Date(p.endDate));
const minStart = new Date(Math.min(...allStartDates.map(d => d.getTime())));
const maxEnd = new Date(Math.max(...allEndDates.map(d => d.getTime())));
const now = new Date();
const currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1);
const currentMonthEnd = new Date(now.getFullYear(), now.getMonth() + 1, 0);
if (timeRange === "future") {
return getMonthsBetween(currentMonthStart, new Date(maxEnd.getFullYear(), maxEnd.getMonth() + 1, 0));
} else if (timeRange === "past") {
return getMonthsBetween(new Date(minStart.getFullYear(), minStart.getMonth(), 1), currentMonthEnd);
}
// "all": desde el primer proyecto hasta el último
return getMonthsBetween(
new Date(minStart.getFullYear(), minStart.getMonth(), 1),
new Date(maxEnd.getFullYear(), maxEnd.getMonth() + 1, 0)
);
}, [filteredProjects, timeRange]);
// Meses visibles: en modo "all" se muestran todos (scroll), en otros modos se pagina
const visibleMonths = useMemo(() => {
if (timeRange === "all") return allMonths;
const monthsToShow = viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12;
if (timeRange === "past") {
const maxOff = Math.max(0, allMonths.length - monthsToShow);
const startIdx = Math.max(0, maxOff - viewOffset);
return allMonths.slice(startIdx, startIdx + monthsToShow);
}
const startIdx = Math.max(0, Math.min(viewOffset, allMonths.length - monthsToShow));
return allMonths.slice(startIdx, startIdx + monthsToShow);
}, [allMonths, viewMode, viewOffset, timeRange]);
// Rango visible en días
const { totalDays, visibleStart, visibleEnd } = useMemo(() => {
if (visibleMonths.length === 0) {
return { totalDays: 30, visibleStart: new Date(), visibleEnd: new Date() };
}
const first = visibleMonths[0];
const last = visibleMonths[visibleMonths.length - 1];
const start = new Date(first.year, first.month, 1);
const end = new Date(last.year, last.month + 1, 0);
return { totalDays: getDaysBetween(start, end), visibleStart: start, visibleEnd: end };
}, [visibleMonths]);
// Navegación (solo para modos paginados, no "all")
const monthsToShow = viewMode === "month" ? 3 : viewMode === "quarter" ? 6 : 12;
const maxOffset = Math.max(0, allMonths.length - monthsToShow);
const canGoBack = timeRange !== "all" && viewOffset > 0;
const canGoForward = timeRange !== "all" && viewOffset < maxOffset;
const goBack = () => {
const step = viewMode === "month" ? 1 : viewMode === "quarter" ? 3 : 6;
setViewOffset(Math.max(0, viewOffset - step));
};
const goForward = () => {
const step = viewMode === "month" ? 1 : viewMode === "quarter" ? 3 : 6;
setViewOffset(Math.min(maxOffset, viewOffset + step));
};
const goToToday = () => setViewOffset(0);
// ¿El timeline usa ancho fijo (scroll horizontal) o flexible (fill)?
const useFixedWidth = timeRange === "all";
const timelineInnerWidth = useFixedWidth ? visibleMonths.length * MONTH_WIDTH_PX : undefined;
if (error) {
return (
<div className="min-h-screen bg-background flex items-center justify-center">
<div className="text-center">
<AlertCircle className="w-16 h-16 text-red-400 dark:text-red-500 mx-auto mb-4" />
<p className="text-red-600 dark:text-red-400 text-lg">{error}</p>
<button
onClick={() => window.location.reload()}
className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
Reintentar
</button>
</div>
</div>
);
}
return (
<div className="h-screen flex flex-col bg-background">
{/* Header */}
<header className="bg-card border-b flex-shrink-0 z-10">
<div className="px-4 sm:px-6 lg:px-8 py-4">
<div className="flex items-center justify-between flex-wrap gap-4">
<div className="flex items-center gap-3">
<div className="p-2 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg">
<GanttIcon className="w-6 h-6 text-white" />
</div>
<div>
<h1 className="text-2xl font-bold text-foreground">Diagrama de Gantt</h1>
<p className="text-sm text-muted-foreground">
Timeline de {filteredProjects.length} proyecto{filteredProjects.length !== 1 ? "s" : ""}
</p>
</div>
</div>
{/* Controles */}
<div className="flex items-center gap-3 flex-wrap">
{/* Filtro de estado */}
<Select value={statusFilter} onValueChange={(v) => { setStatusFilter(v); setViewOffset(0); }}>
<SelectTrigger className="w-40">
<Filter className="w-4 h-4 mr-2" />
<SelectValue placeholder="Estado" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Todos</SelectItem>
<SelectItem value="0">Borrador</SelectItem>
<SelectItem value="1">Abierto</SelectItem>
<SelectItem value="2">Cerrado</SelectItem>
</SelectContent>
</Select>
{/* Selector de rango temporal */}
<div className="flex items-center gap-1 border rounded-lg p-1">
<Button
variant={timeRange === "past" ? "default" : "ghost"}
size="sm"
onClick={() => { setTimeRange("past"); setViewOffset(0); }}
>
<History className="w-4 h-4 mr-1" />
Pasado
</Button>
<Button
variant={timeRange === "future" ? "default" : "ghost"}
size="sm"
onClick={() => { setTimeRange("future"); setViewOffset(0); }}
>
<Clock className="w-4 h-4 mr-1" />
Futuro
</Button>
<Button
variant={timeRange === "all" ? "default" : "ghost"}
size="sm"
onClick={() => { setTimeRange("all"); setViewOffset(0); }}
>
<Calendar className="w-4 h-4 mr-1" />
Todos
</Button>
</div>
{/* Selector de vista y navegación - solo en modos paginados */}
{timeRange !== "all" && (
<>
<Select value={viewMode} onValueChange={(v: ViewMode) => { setViewMode(v); setViewOffset(0); }}>
<SelectTrigger className="w-32">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="month">3 meses</SelectItem>
<SelectItem value="quarter">6 meses</SelectItem>
<SelectItem value="year">12 meses</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center gap-1">
<Button variant="outline" size="icon" onClick={goBack} disabled={!canGoBack}>
<ChevronLeft className="w-4 h-4" />
</Button>
<Button variant="outline" size="sm" onClick={goToToday} disabled={viewOffset === 0}>
<Calendar className="w-4 h-4 mr-1" />
Inicio
</Button>
<Button variant="outline" size="icon" onClick={goForward} disabled={!canGoForward}>
<ChevronRight className="w-4 h-4" />
</Button>
</div>
</>
)}
</div>
</div>
</div>
</header>
{/* Content */}
<main className="flex-1 overflow-hidden px-4 sm:px-6 lg:px-8 py-6">
{loading ? (
<GanttSkeleton />
) : filteredProjects.length === 0 ? (
<Card className="border">
<CardContent className="py-16 text-center">
<GanttIcon className="w-16 h-16 text-muted-foreground/50 mx-auto mb-4" />
<h3 className="text-xl font-semibold text-foreground">No hay proyectos</h3>
<p className="text-muted-foreground mt-2">No se encontraron proyectos con los filtros seleccionados</p>
</CardContent>
</Card>
) : (
<Card className="border h-full flex flex-col overflow-hidden">
<CardContent className="p-0 flex-1 overflow-hidden">
<div className="flex h-full overflow-hidden">
{/* Columna de nombres - fija, scroll vertical */}
<div className="w-56 flex-shrink-0 border-r bg-muted/50 flex flex-col">
{/* Header nombres */}
<div className="h-12 border-b flex items-center px-4 flex-shrink-0">
<span className="font-semibold text-sm text-foreground">Proyecto</span>
</div>
{/* Lista nombres - scroll vertical */}
<div
ref={namesRef}
className="flex-1 overflow-y-auto overflow-x-hidden"
onScroll={() => syncScroll("names")}
>
{filteredProjects.map((project, index) => {
const color = getProjectColor(index);
return (
<div
key={project.id}
className="h-12 border-b flex items-center px-4 hover:bg-muted transition-colors cursor-pointer"
onClick={() => router.push(`/proyectos/${project.id}`)}
>
<div className="flex items-center gap-2.5 min-w-0">
<div className={`w-2.5 h-2.5 rounded-full ${color.bg} flex-shrink-0`} />
<div className="min-w-0">
<p className="text-sm font-medium text-foreground truncate" title={project.name}>
{project.name}
</p>
<p className="text-[11px] text-muted-foreground">{STATUS_LABELS[project.status]} · {project.progress}%</p>
</div>
</div>
</div>
);
})}
</div>
</div>
{/* Timeline - scroll horizontal (en modo "all") + scroll vertical sincronizado */}
<div
ref={timelineRef}
className="flex-1 min-w-0 overflow-auto"
onScroll={() => syncScroll("timeline")}
>
<div style={{ width: timelineInnerWidth ? `${timelineInnerWidth}px` : "100%", minWidth: useFixedWidth ? undefined : "100%" }}>
{/* Header meses */}
<div className="h-12 border-b flex sticky top-0 z-10 bg-card">
{visibleMonths.map((month) => {
const isCurrentMonth = new Date().getMonth() === month.month && new Date().getFullYear() === month.year;
return (
<div
key={`${month.year}-${month.month}`}
className={`border-r flex items-center justify-center ${
isCurrentMonth ? "bg-blue-50 dark:bg-blue-950/30" : "bg-card"
}`}
style={{ width: useFixedWidth ? `${MONTH_WIDTH_PX}px` : undefined, flex: useFixedWidth ? "none" : 1 }}
>
<span className={`text-xs font-medium ${isCurrentMonth ? "text-blue-700 dark:text-blue-400" : "text-muted-foreground"}`}>
{month.label}
</span>
</div>
);
})}
</div>
{/* Barras del Gantt */}
<TooltipProvider>
{filteredProjects.map((project, index) => {
const color = getProjectColor(index);
const projectStart = new Date(project.startDate);
const projectEnd = new Date(project.endDate);
const startOffset = Math.max(0, getDaysBetween(visibleStart, projectStart));
const endOffset = Math.min(totalDays, getDaysBetween(visibleStart, projectEnd));
const leftPercent = (startOffset / totalDays) * 100;
const widthPercent = Math.max(0.5, ((endOffset - startOffset) / totalDays) * 100);
const isVisible = projectEnd >= visibleStart && projectStart <= visibleEnd;
const isOverdue = projectEnd < new Date() && project.progress < 100 && project.status === "1";
return (
<div key={project.id} className="h-12 border-b relative">
{/* Grid de meses */}
<div className="absolute inset-0 flex">
{visibleMonths.map((month) => {
const isCurrentMonth = new Date().getMonth() === month.month && new Date().getFullYear() === month.year;
return (
<div
key={`grid-${month.year}-${month.month}`}
className={`border-r ${isCurrentMonth ? "bg-blue-50/30 dark:bg-blue-950/20" : ""}`}
style={{ width: useFixedWidth ? `${MONTH_WIDTH_PX}px` : undefined, flex: useFixedWidth ? "none" : 1 }}
/>
);
})}
</div>
{/* Barra del proyecto */}
{isVisible && (
<Tooltip>
<TooltipTrigger asChild>
<div
className={`absolute top-1.5 h-9 rounded-md cursor-pointer transition-all hover:scale-[1.02] hover:shadow-md ${
isOverdue ? "ring-2 ring-red-400" : ""
}`}
style={{
left: `${leftPercent}%`,
width: `${widthPercent}%`,
minWidth: "16px",
}}
onClick={() => router.push(`/proyectos/${project.id}`)}
>
<div className={`absolute inset-0 ${color.light} rounded-md`} />
<div
className={`absolute inset-y-0 left-0 ${color.bg} rounded-md transition-all`}
style={{ width: `${project.progress}%` }}
/>
<div className="relative h-full flex items-center px-2 z-10">
<span className="text-xs font-medium text-white truncate drop-shadow-sm">
{project.progress >= 30 ? `${project.progress}%` : ""}
</span>
</div>
</div>
</TooltipTrigger>
<TooltipContent side="top" className="max-w-xs">
<div className="space-y-1">
<p className="font-semibold">{project.name}</p>
<div className="text-xs space-y-0.5">
<p><span className="text-muted-foreground">Estado:</span> {STATUS_LABELS[project.status]}</p>
<p><span className="text-muted-foreground">Progreso:</span> {project.progress}%</p>
<p><span className="text-muted-foreground">Inicio:</span> {formatDate(project.startDate)}</p>
<p><span className="text-muted-foreground">Fin:</span> {formatDate(project.endDate)}</p>
<p><span className="text-muted-foreground">Cliente:</span> {project.client}</p>
{isOverdue && (
<p className="text-red-500 font-medium">Proyecto retrasado</p>
)}
</div>
</div>
</TooltipContent>
</Tooltip>
)}
</div>
);
})}
</TooltipProvider>
</div>
</div>
</div>
</CardContent>
</Card>
)}
</main>
</div>
);
}
function GanttSkeleton() {
return (
<Card className="border h-full">
<CardContent className="p-0 h-full">
<div className="flex h-full">
<div className="w-56 flex-shrink-0 border-r bg-muted/50">
<div className="h-12 border-b flex items-center px-4">
<Skeleton className="h-4 w-20" />
</div>
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="h-12 border-b flex items-center px-4">
<div className="flex items-center gap-2.5">
<Skeleton className="w-2.5 h-2.5 rounded-full" />
<div>
<Skeleton className="h-3.5 w-28 mb-1" />
<Skeleton className="h-2.5 w-16" />
</div>
</div>
</div>
))}
</div>
<div className="flex-1">
<div className="h-12 border-b flex">
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="flex-1 border-r flex items-center justify-center">
<Skeleton className="h-3.5 w-16" />
</div>
))}
</div>
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="h-12 border-b px-4 flex items-center">
<Skeleton className="h-7 w-full max-w-md rounded-md" />
</div>
))}
</div>
</div>
</CardContent>
</Card>
);
}