// @ts-nocheck
// TODO: Hook return type issues with useResponsiveColumns
'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import { format } from 'date-fns';
import { getDateFnsLocale } from '@alga-psa/ui';
import { IClientPortalConfig } from '@alga-psa/types';
import {
  Calendar,
  ChevronDown,
  ChevronRight,
  Ban,
  GitBranch,
  CheckSquare,
  Zap,
} from 'lucide-react';
import { Tooltip } from '@alga-psa/ui/components/Tooltip';
import { Alert, AlertDescription } from '@alga-psa/ui/components/Alert';
import TaskDocumentUpload from './TaskDocumentUpload';
import Spinner from '@alga-psa/ui/components/Spinner';
import UserAvatar from '@alga-psa/ui/components/UserAvatar';
import TeamAvatar from '@alga-psa/ui/components/TeamAvatar';
import { useResponsiveColumns, ColumnConfig } from '@alga-psa/ui/hooks';

interface Phase {
  phase_id: string;
  phase_name: string;
  description: string | null;
  start_date: Date | null;
  end_date: Date | null;
  completion_percentage?: number;
}

interface Task {
  task_id: string;
  phase_id: string;
  project_status_mapping_id: string;
  task_name?: string;
  description?: string;
  due_date?: Date | null;
  status_name?: string;
  custom_name?: string;
  display_order?: number;
  status_color?: string | null;
  assigned_to_id?: string;
  assigned_to_name?: string;
  assigned_to_avatar?: string | null;
  assigned_team_id?: string | null;
  assigned_team_name?: string | null;
  assigned_team_avatar?: string | null;
  estimated_hours?: number | null;
  actual_hours?: number | null;
  priority_id?: string | null;
  priority_name?: string | null;
  priority_color?: string | null;
  additional_agents?: Array<{ user_id: string; user_name: string; role: string | null; avatar_url?: string | null }>;
  checklist_total?: number;
  checklist_completed?: number;
  checklist_items?: Array<{ item_name: string; completed: boolean }>;
}

interface StatusGroup {
  project_status_mapping_id: string;
  status_name: string;
  status_color: string | null;
  display_order: number;
  tasks: Task[];
}

interface TaskDependency {
  dependency_id: string;
  predecessor_task_id: string;
  successor_task_id: string;
  dependency_type: 'blocks' | 'blocked_by' | 'related_to';
  predecessor_task?: { task_name: string };
  successor_task?: { task_name: string };
}

interface ClientTaskListViewProps {
  phases: Phase[];
  tasks: Task[];
  config: IClientPortalConfig;
  loading?: boolean;
  taskDependencies?: { [taskId: string]: { predecessors: TaskDependency[]; successors: TaskDependency[] } };
}

// Progress bar component
function ProgressBar({ percentage }: { percentage: number }) {
  return (
    <div className="w-full max-w-[200px] bg-gray-200 rounded-full h-1.5 overflow-hidden">
      <div
        className="bg-purple-600 h-1.5 rounded-full transition-all duration-300"
        style={{ width: `${Math.min(percentage, 100)}%` }}
      />
    </div>
  );
}

export default function ClientTaskListView({
  phases,
  tasks,
  config,
  loading = false,
  taskDependencies
}: ClientTaskListViewProps) {
  const { t, i18n } = useTranslation('features/projects');
  const dateLocale = getDateFnsLocale(i18n.language);
  const [expandedPhases, setExpandedPhases] = useState<Set<string>>(
    new Set(phases.map(p => p.phase_id))
  );
  const [expandedStatuses, setExpandedStatuses] = useState<Set<string>>(new Set());

  const showPhases = config.show_phases ?? false;
  const showTasks = config.show_tasks ?? false;
  const showPhaseCompletion = config.show_phase_completion ?? false;
  const visibleFields = config.visible_task_fields ?? ['task_name', 'due_date', 'status'];
  const allowUploads = visibleFields.includes('document_uploads');
  const showDependencies = visibleFields.includes('dependencies');

  // Responsive column configuration - only name always shows in client portal
  const responsiveColumnConfig: ColumnConfig[] = useMemo(() => [
    { key: 'expand', minWidth: 40, priority: 0, alwaysShow: true },
    { key: 'task_name', minWidth: 200, priority: 1, alwaysShow: true },
    { key: 'assigned_to', minWidth: 220, priority: 2 },
    { key: 'due_date', minWidth: 110, priority: 3 },
    { key: 'checklist_progress', minWidth: 80, priority: 4 },
    { key: 'dependencies', minWidth: 70, priority: 5 },
    { key: 'estimated_hours', minWidth: 80, priority: 6 },
    { key: 'actual_hours', minWidth: 80, priority: 7 },
    { key: 'document_uploads', minWidth: 80, priority: 8 },
  ], []);

  const { containerRef, isColumnVisible: isResponsiveColumnVisible, hiddenColumnCount } = useResponsiveColumns({
    columns: responsiveColumnConfig,
    containerPadding: 80
  });

  // Check if column should be shown (both config-enabled AND fits in space)
  const shouldShowColumn = (key: string) => {
    // First check if it's enabled in config
    const isEnabledInConfig = key === 'expand' || key === 'task_name' ||
      (key === 'dependencies' && showDependencies) ||
      (key === 'document_uploads' && allowUploads) ||
      visibleFields.includes(key);

    // Then check if there's space for it
    return isEnabledInConfig && isResponsiveColumnVisible(key);
  };

  // Compute column configuration based on visible fields AND responsive visibility
  const columnConfig = useMemo(() => {
    const cols: Array<{ key: string; width: string }> = [
      { key: 'expand', width: '40px' },
    ];

    // Base percentages that will be adjusted
    const baseWidths: Record<string, number> = {
      task_name: 28,
      dependencies: 6,
      checklist_progress: 7,
      assigned_to: 18,
      estimated_hours: 8,
      actual_hours: 8,
      due_date: 10,
      document_uploads: 10,
    };

    // Calculate total percentage of visible columns (config + responsive)
    let totalPercent = 0;
    const visibleCols: string[] = [];

    // Only include columns that pass both config AND responsive checks
    const columnKeys = ['task_name', 'dependencies', 'checklist_progress', 'assigned_to', 'estimated_hours', 'actual_hours', 'due_date', 'document_uploads'];

    columnKeys.forEach(key => {
      // Check if enabled in config
      const isEnabledInConfig = key === 'task_name' ||
        (key === 'dependencies' && showDependencies) ||
        (key === 'document_uploads' && allowUploads) ||
        visibleFields.includes(key);

      // Check responsive visibility
      if (isEnabledInConfig && isResponsiveColumnVisible(key)) {
        visibleCols.push(key);
        totalPercent += baseWidths[key];
      }
    });

    // Scale percentages to fill available space (accounting for 40px expand column)
    const scale = totalPercent > 0 ? 94 / totalPercent : 1; // 94% available after 40px column

    visibleCols.forEach(col => {
      cols.push({ key: col, width: `${Math.round(baseWidths[col] * scale)}%` });
    });

    return cols;
  }, [visibleFields, showDependencies, allowUploads, isResponsiveColumnVisible]);

  // Group tasks by phase and status
  const phaseGroups = useMemo(() => {
    return phases.map(phase => {
      const phaseTasks = tasks.filter(task => task.phase_id === phase.phase_id);

      // Group by effective status label for the task's phase
      const statusMap = new Map<string, StatusGroup>();

      phaseTasks.forEach(task => {
        const statusName = task.custom_name || task.status_name || 'Unknown';
        if (!statusMap.has(statusName)) {
          statusMap.set(statusName, {
            project_status_mapping_id: task.project_status_mapping_id,
            status_name: statusName,
            status_color: task.status_color || null,
            display_order: task.display_order ?? Number.MAX_SAFE_INTEGER,
            tasks: []
          });
        }
        statusMap.get(statusName)!.tasks.push(task);
      });

      return {
        phase,
        statusGroups: Array.from(statusMap.values()).sort((a, b) => a.display_order - b.display_order),
        totalTasks: phaseTasks.length
      };
    });
  }, [phases, tasks]);

  // Auto-expand statuses that have tasks
  useEffect(() => {
    const statusesWithTasks = new Set<string>();
    phaseGroups.forEach(group => {
      group.statusGroups.forEach(statusGroup => {
        if (statusGroup.tasks.length > 0) {
          const statusKey = `${group.phase.phase_id}:${statusGroup.status_name}`;
          statusesWithTasks.add(statusKey);
        }
      });
    });
    setExpandedStatuses(statusesWithTasks);
  }, [phaseGroups]);

  const togglePhase = (phaseId: string) => {
    setExpandedPhases(prev => {
      const next = new Set(prev);
      if (next.has(phaseId)) {
        next.delete(phaseId);
      } else {
        next.add(phaseId);
      }
      return next;
    });
  };

  const toggleStatus = (phaseId: string, statusName: string) => {
    const key = `${phaseId}:${statusName}`;
    setExpandedStatuses(prev => {
      const next = new Set(prev);
      if (next.has(key)) {
        next.delete(key);
      } else {
        next.add(key);
      }
      return next;
    });
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Spinner size="lg" />
      </div>
    );
  }

  if (phases.length === 0 && tasks.length === 0) {
    return (
      <div className="text-center py-8 text-gray-500">
        {showTasks
          ? t('tasks.noTasks', 'No tasks to display')
          : t('phases.noPhases', 'No phases to display')}
      </div>
    );
  }

  // Helper to get column width from config
  const getColWidth = (key: string) => columnConfig.find(c => c.key === key)?.width || 'auto';

  return (
    <div ref={containerRef} className="bg-white rounded-lg border border-gray-200 overflow-hidden">
      {/* Hidden columns alert */}
      {hiddenColumnCount > 0 && (
        <Alert variant="info" className="rounded-none border-x-0 border-t-0">
          <AlertDescription className="flex items-center text-sm">
            <Zap className="h-4 w-4 mr-1" />
            {hiddenColumnCount} {t('columnsHidden', 'column(s) hidden due to limited space. Resize browser to see more.')}
          </AlertDescription>
        </Alert>
      )}
      {/* Column headers */}
      {showTasks && (
        <table className="w-full table-fixed">
          <colgroup>
            {columnConfig.map(col => (
              <col key={col.key} style={{ width: col.width }} />
            ))}
          </colgroup>
          <thead className="bg-white border-b border-gray-200">
            <tr>
              <th className="px-3 py-3" />
              {shouldShowColumn('task_name') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.taskName')}
                </th>
              )}
              {shouldShowColumn('dependencies') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.dependencies')}
                </th>
              )}
              {shouldShowColumn('checklist_progress') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.checklist')}
                </th>
              )}
              {shouldShowColumn('assigned_to') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.assignee')}
                </th>
              )}
              {shouldShowColumn('estimated_hours') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.estHours')}
                </th>
              )}
              {shouldShowColumn('actual_hours') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.hoursLogged')}
                </th>
              )}
              {shouldShowColumn('due_date') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.dueDate')}
                </th>
              )}
              {shouldShowColumn('document_uploads') && (
                <th className="px-3 py-3 text-left text-xs font-medium text-gray-500">
                  {t('tasks.attachments')}
                </th>
              )}
            </tr>
          </thead>
        </table>
      )}

      {/* Hierarchical rows */}
      <div className="divide-y divide-gray-200">
        {phaseGroups.map(({ phase, statusGroups, totalTasks }) => {
          const isPhaseExpanded = expandedPhases.has(phase.phase_id);

          return (
            <div key={phase.phase_id}>
              {/* Phase header row */}
              <div
                className="bg-white hover:bg-gray-50 cursor-pointer transition-colors"
                onClick={() => togglePhase(phase.phase_id)}
              >
                <div className="px-3 py-3">
                  <div className="flex items-start gap-2">
                    <div className="pt-0.5 text-gray-400">
                      {isPhaseExpanded ? (
                        <ChevronDown className="h-5 w-5" />
                      ) : (
                        <ChevronRight className="h-5 w-5" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center justify-between gap-4">
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 flex-wrap">
                            <span className="text-base font-semibold text-gray-900">{phase.phase_name}</span>
                            {showTasks && (
                              <span className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-purple-100 text-purple-700">
                                {totalTasks} {totalTasks === 1 ? t('task', 'task') : t('tasks.title', 'tasks').toLowerCase()}
                              </span>
                            )}
                          </div>

                          {/* Phase description - always show if available */}
                          {phase.description && (
                            <p className="text-sm text-gray-500 mt-1">{phase.description}</p>
                          )}

                          {/* Phase dates - always show if available */}
                          {(phase.start_date || phase.end_date) && (
                            <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
                              {phase.start_date && (
                                <span className="flex items-center gap-1">
                                  <Calendar className="w-3.5 h-3.5" />
                                  {t('startDate', 'Start')}: {format(new Date(phase.start_date), 'PP', { locale: dateLocale })}
                                </span>
                              )}
                              {phase.end_date && (
                                <span className="flex items-center gap-1">
                                  <Calendar className="w-3.5 h-3.5" />
                                  {t('endDate', 'End')}: {format(new Date(phase.end_date), 'PP', { locale: dateLocale })}
                                </span>
                              )}
                            </div>
                          )}
                        </div>

                        {/* Completion percentage */}
                        {showPhaseCompletion && phase.completion_percentage !== undefined && (
                          <div className="flex items-center gap-3 flex-shrink-0">
                            <ProgressBar percentage={phase.completion_percentage} />
                            <div className="text-right min-w-[60px]">
                              <span className="text-lg font-bold text-purple-600">
                                {phase.completion_percentage}%
                              </span>
                              <div className="text-xs text-gray-500">
                                {t('phases.completion', 'Complete')}
                              </div>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Status Groups */}
              {showTasks && isPhaseExpanded && statusGroups.length > 0 && (
                <div className="divide-y divide-gray-100">
                  {statusGroups.map((statusGroup) => {
                    const statusKey = `${phase.phase_id}:${statusGroup.status_name}`;
                    const isStatusExpanded = expandedStatuses.has(statusKey);
                    const statusColor = statusGroup.status_color || '#6B7280';

                    return (
                      <div key={statusGroup.status_name}>
                        {/* Status header row */}
                        <div
                          className="bg-gray-50 hover:bg-gray-100 cursor-pointer transition-colors py-2 px-3"
                          onClick={() => toggleStatus(phase.phase_id, statusGroup.status_name)}
                        >
                          <div className="flex items-center gap-2 pl-6">
                            {isStatusExpanded ? (
                              <ChevronDown className="h-4 w-4 text-gray-400" />
                            ) : (
                              <ChevronRight className="h-4 w-4 text-gray-400" />
                            )}
                            <span
                              className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-xs font-medium"
                              style={{
                                backgroundColor: `${statusColor}20`,
                                color: statusColor,
                                border: `1px solid ${statusColor}40`
                              }}
                            >
                              <span
                                className="w-2 h-2 rounded-full"
                                style={{ backgroundColor: statusColor }}
                              />
                              {statusGroup.status_name}
                            </span>
                            <span className="text-xs text-gray-500">
                              ({statusGroup.tasks.length})
                            </span>
                          </div>
                        </div>

                        {/* Task rows */}
                        {isStatusExpanded && (
                          <table className="w-full table-fixed">
                            <colgroup>
                              {columnConfig.map(col => (
                                <col key={col.key} style={{ width: col.width }} />
                              ))}
                            </colgroup>
                            <tbody className="divide-y divide-gray-100">
                              {statusGroup.tasks.map((task, index) => (
                                <tr
                                  key={task.task_id}
                                  className={`${index % 2 === 0 ? 'bg-gray-50' : 'bg-white'} hover:bg-primary/10 transition-colors`}
                                >
                                  <td className="px-3 py-3" />

                                  {/* Task Name */}
                                  {shouldShowColumn('task_name') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      <div className="pl-6 truncate">
                                        <div className="flex items-center gap-2">
                                          <span className="font-medium text-gray-900">{task.task_name}</span>
                                          {visibleFields.includes('priority') && task.priority_name && (
                                            <Tooltip content={`${t('tasks.priorityLevel', 'Priority level')}: ${task.priority_name}`}>
                                              <div
                                                className="w-2.5 h-2.5 rounded-full shrink-0"
                                                style={{ backgroundColor: task.priority_color || '#6B7280' }}
                                              />
                                            </Tooltip>
                                          )}
                                        </div>
                                        {visibleFields.includes('description') && task.description && (
                                          <p className="text-xs text-gray-500 mt-0.5 line-clamp-1">{task.description}</p>
                                        )}
                                      </div>
                                    </td>
                                  )}

                                  {/* Dependencies */}
                                  {shouldShowColumn('dependencies') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      {(() => {
                                        const deps = taskDependencies?.[task.task_id];
                                        if (!deps || (deps.predecessors.length === 0 && deps.successors.length === 0)) {
                                          return null;
                                        }
                                        const hasBlockingDeps = deps.predecessors.some(d => d.dependency_type === 'blocks' || d.dependency_type === 'blocked_by') ||
                                                               deps.successors.some(d => d.dependency_type === 'blocks' || d.dependency_type === 'blocked_by');
                                        const count = deps.predecessors.length + deps.successors.length;
                                        return (
                                          <Tooltip
                                            content={
                                              <div className="text-xs space-y-2">
                                                {deps.predecessors.length > 0 && (
                                                  <div>
                                                    <div className="font-medium text-gray-300 mb-1">{t('dependencies.dependsOn', 'Depends on')}:</div>
                                                    {deps.predecessors.map((d, i) => {
                                                      const isBlocking = d.dependency_type === 'blocks' || d.dependency_type === 'blocked_by';
                                                      return (
                                                        <div key={i} className="flex items-center gap-1.5 ml-2">
                                                          <span className={isBlocking ? 'text-orange-400' : 'text-blue-400'}>
                                                            {isBlocking ? <Ban className="h-3 w-3" /> : <GitBranch className="h-3 w-3" />}
                                                          </span>
                                                          <span>{d.predecessor_task?.task_name || t('dependencies.unknownTask', 'Unknown task')}</span>
                                                        </div>
                                                      );
                                                    })}
                                                  </div>
                                                )}
                                                {deps.successors.length > 0 && (
                                                  <div>
                                                    <div className="font-medium text-gray-300 mb-1">{t('dependencies.blocks', 'Blocks')}:</div>
                                                    {deps.successors.map((d, i) => {
                                                      const isBlocking = d.dependency_type === 'blocks' || d.dependency_type === 'blocked_by';
                                                      return (
                                                        <div key={i} className="flex items-center gap-1.5 ml-2">
                                                          <span className={isBlocking ? 'text-red-400' : 'text-blue-400'}>
                                                            {isBlocking ? <Ban className="h-3 w-3" /> : <GitBranch className="h-3 w-3" />}
                                                          </span>
                                                          <span>{d.successor_task?.task_name || t('dependencies.unknownTask', 'Unknown task')}</span>
                                                        </div>
                                                      );
                                                    })}
                                                  </div>
                                                )}
                                              </div>
                                            }
                                          >
                                            <div className={`flex items-center gap-1 ${hasBlockingDeps ? 'text-red-500' : 'text-blue-500'}`}>
                                              {hasBlockingDeps ? <Ban className="w-3.5 h-3.5" /> : <GitBranch className="w-3.5 h-3.5" />}
                                              <span>{count}</span>
                                            </div>
                                          </Tooltip>
                                        );
                                      })()}
                                    </td>
                                  )}

                                  {/* Checklist Progress */}
                                  {shouldShowColumn('checklist_progress') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      {task.checklist_total != null && task.checklist_total > 0 && (
                                        <Tooltip
                                          content={
                                            task.checklist_items && task.checklist_items.length > 0 ? (
                                              <div className="text-xs space-y-1 max-w-xs">
                                                <div className="font-medium text-gray-300 mb-1">{t('tasks.checklistItems', 'Checklist Items')}:</div>
                                                {task.checklist_items.map((item: { item_name: string; completed: boolean }, i: number) => (
                                                  <div key={i} className="flex items-center gap-1.5">
                                                    <CheckSquare className={`h-3 w-3 ${item.completed ? 'text-green-400' : 'text-gray-400'}`} />
                                                    <span className={item.completed ? 'line-through text-gray-400' : ''}>{item.item_name}</span>
                                                  </div>
                                                ))}
                                              </div>
                                            ) : (
                                              <span>{task.checklist_completed ?? 0} {t('tasks.of', 'of')} {task.checklist_total} {t('tasks.complete', 'complete')}</span>
                                            )
                                          }
                                        >
                                          <div className="flex items-center gap-1 cursor-help">
                                            <CheckSquare className={`h-3.5 w-3.5 ${(task.checklist_completed ?? 0) === task.checklist_total ? 'text-green-500' : 'text-gray-400'}`} />
                                            <span>{task.checklist_completed ?? 0}/{task.checklist_total}</span>
                                          </div>
                                        </Tooltip>
                                      )}
                                    </td>
                                  )}

                                  {/* Assignee */}
                                  {shouldShowColumn('assigned_to') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      <div className="flex items-center gap-2 min-w-0">
                                        {task.assigned_to_name && task.assigned_to_id ? (
                                          <UserAvatar
                                            userId={task.assigned_to_id}
                                            userName={task.assigned_to_name}
                                            avatarUrl={task.assigned_to_avatar || null}
                                            size="sm"
                                          />
                                        ) : (
                                          <div className="h-8 w-8 shrink-0" />
                                        )}
                                        <span className="truncate">
                                          {task.assigned_to_name || (
                                            <span className="text-gray-400">{t('tasks.unassigned', 'Unassigned')}</span>
                                          )}
                                        </span>
                                        {task.assigned_team_id && task.assigned_team_name && (
                                          <Tooltip content={task.assigned_team_name}>
                                            <span className="inline-flex items-center cursor-help">
                                              <TeamAvatar
                                                teamId={task.assigned_team_id}
                                                teamName={task.assigned_team_name}
                                                avatarUrl={task.assigned_team_avatar || null}
                                                size="xs"
                                              />
                                            </span>
                                          </Tooltip>
                                        )}
                                        {task.additional_agents && task.additional_agents.length > 0 && (
                                          <Tooltip
                                            content={
                                              <div className="text-xs space-y-1.5">
                                                <div className="font-medium text-gray-300 mb-1">{t('tasks.additionalAgents', 'Additional Agents')}:</div>
                                                {task.additional_agents.map((agent, i) => (
                                                  <div key={i} className="flex items-center gap-2">
                                                    <UserAvatar
                                                      userId={agent.user_id}
                                                      userName={agent.user_name}
                                                      avatarUrl={agent.avatar_url || null}
                                                      size="xs"
                                                    />
                                                    <span>
                                                      {agent.user_name}
                                                      {agent.role && <span className="text-gray-400"> ({agent.role})</span>}
                                                    </span>
                                                  </div>
                                                ))}
                                              </div>
                                            }
                                          >
                                            <span
                                              className="text-xs font-medium cursor-help px-1.5 py-0.5 rounded shrink-0"
                                              style={{
                                                color: 'rgb(var(--color-primary-500))',
                                                backgroundColor: 'rgb(var(--color-primary-50))'
                                              }}
                                            >
                                              +{task.additional_agents.length}
                                            </span>
                                          </Tooltip>
                                        )}
                                      </div>
                                    </td>
                                  )}

                                  {/* Estimated Hours */}
                                  {shouldShowColumn('estimated_hours') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      {task.estimated_hours != null && (task.estimated_hours / 60).toFixed(1)}
                                    </td>
                                  )}

                                  {/* Actual Hours */}
                                  {shouldShowColumn('actual_hours') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      {task.actual_hours != null && (task.actual_hours / 60).toFixed(1)}
                                    </td>
                                  )}

                                  {/* Due Date */}
                                  {shouldShowColumn('due_date') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      {task.due_date && format(new Date(task.due_date), 'PP', { locale: dateLocale })}
                                    </td>
                                  )}

                                  {/* Document Upload */}
                                  {shouldShowColumn('document_uploads') && (
                                    <td className="px-3 py-3 text-sm text-gray-700">
                                      <TaskDocumentUpload taskId={task.task_id} compact />
                                    </td>
                                  )}
                                </tr>
                              ))}
                            </tbody>
                          </table>
                        )}
                      </div>
                    );
                  })}
                </div>
              )}

              {/* Empty state for phase */}
              {showTasks && isPhaseExpanded && totalTasks === 0 && (
                <div className="py-4 text-center text-sm text-gray-400 bg-gray-50">
                  {t('tasks.noTasks', 'No tasks in this phase')}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}
