'use client';

import React from 'react';
import { useTranslation } from '@alga-psa/ui/lib/i18n/client';
import { useTruncationDetection } from '@alga-psa/ui/hooks';
import { format, Locale } from 'date-fns';
import { getDateFnsLocale } from '@alga-psa/ui';
import { IClientPortalConfig } from '@alga-psa/types';
import { Calendar, Clock, CheckSquare, Ban, GitBranch } from 'lucide-react';
import { Tooltip } from '@alga-psa/ui/components/Tooltip';
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 { useTheme } from 'next-themes';
import { darkenColor } from '@alga-psa/ui/lib/colorUtils';

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

interface Status {
  project_status_mapping_id: string;
  name: string;
  display_order: number;
  is_closed: boolean;
  color: string | null;
}

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 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;
  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;
  is_closed?: boolean;
  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 ClientKanbanBoardProps {
  phases: Phase[];
  statuses: Status[];
  tasks: Task[];
  config: IClientPortalConfig;
  selectedPhaseId: string | null;
  onPhaseSelect: (phaseId: string) => void;
  loading?: boolean;
  taskDependencies?: { [taskId: string]: { predecessors: TaskDependency[]; successors: TaskDependency[] } };
}

// Lighten a hex color by a given amount (0-1)
function lightenColor(hex: string, amount: number): string {
  // Remove # if present
  const color = hex.replace('#', '');

  // Parse RGB values
  const r = parseInt(color.substring(0, 2), 16);
  const g = parseInt(color.substring(2, 4), 16);
  const b = parseInt(color.substring(4, 6), 16);

  // Lighten each component
  const newR = Math.round(r + (255 - r) * amount);
  const newG = Math.round(g + (255 - g) * amount);
  const newB = Math.round(b + (255 - b) * amount);

  // Convert back to hex
  return `#${((newR << 16) | (newG << 8) | newB).toString(16).padStart(6, '0')}`;
}

// Task card component
function TaskCard({
  task,
  config,
  dateLocale,
  dependencies
}: {
  task: Task;
  config: IClientPortalConfig;
  dateLocale: Locale;
  dependencies?: { predecessors: TaskDependency[]; successors: TaskDependency[] };
}) {
  const { t } = useTranslation('features/projects');
  const [isDescriptionExpanded, setIsDescriptionExpanded] = React.useState(false);
  const { ref: descriptionRef, isTruncated: isDescriptionTruncated } = useTruncationDetection<HTMLParagraphElement>();
  const visibleFields = config.visible_task_fields ?? ['task_name', 'due_date', 'status'];
  const allowUploads = visibleFields.includes('document_uploads');
  const showDependencies = visibleFields.includes('dependencies');

  const hasDependencies = dependencies && (dependencies.predecessors.length > 0 || dependencies.successors.length > 0);
  const hasBlockingDeps = dependencies && (
    dependencies.predecessors.some(d => d.dependency_type === 'blocks' || d.dependency_type === 'blocked_by') ||
    dependencies.successors.some(d => d.dependency_type === 'blocks' || d.dependency_type === 'blocked_by')
  );

  return (
    <div className="bg-white dark:bg-[rgb(var(--color-card))] rounded-lg border border-gray-200 dark:border-[rgb(var(--color-border-200))] p-3 shadow-sm hover:shadow-md transition-shadow">
      {/* Task Name with Priority */}
      {visibleFields.includes('task_name') && task.task_name && (
        <div className="flex items-start gap-2 mb-2">
          <h4 className="font-semibold text-gray-900 dark:text-gray-100 text-lg flex-1">{task.task_name}</h4>
          {visibleFields.includes('priority') && task.priority_name && (
            <Tooltip content={`${t('tasks.priorityLevel', 'Priority level')}: ${task.priority_name}`}>
              <div
                className="w-3 h-3 rounded-full shrink-0 mt-1.5"
                style={{ backgroundColor: task.priority_color || '#6B7280' }}
              />
            </Tooltip>
          )}
        </div>
      )}

      {/* Task Description - Expandable */}
      {visibleFields.includes('description') && task.description && (
        <div className="mb-2">
          <p
            ref={descriptionRef}
            className={`text-sm text-[rgb(var(--color-text-600))] ${!isDescriptionExpanded ? 'line-clamp-2' : ''}`}
          >
            {task.description}
          </p>
          {(isDescriptionTruncated || isDescriptionExpanded) && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                setIsDescriptionExpanded(!isDescriptionExpanded);
              }}
              className="text-xs text-purple-600 hover:text-purple-700 font-medium mt-1"
            >
              {isDescriptionExpanded
                ? t('tasks.seeLess', 'See less')
                : t('tasks.seeMore', 'See more')}
            </button>
          )}
        </div>
      )}

      {/* Task Details */}
      <div className="space-y-1.5 text-sm text-gray-600 dark:text-gray-400">
        {/* Due Date row with badges inline */}
        {(visibleFields.includes('due_date') || visibleFields.includes('checklist_progress') || showDependencies) && (
          <div className="flex items-center justify-between gap-2">
            {/* Left side: Due Date */}
            {visibleFields.includes('due_date') && task.due_date ? (
              <div className="flex items-center gap-1.5">
                <Calendar className="w-3 h-3 text-[rgb(var(--color-text-400))]" />
                <span>{format(new Date(task.due_date), 'PP', { locale: dateLocale })}</span>
              </div>
            ) : (
              <div />
            )}

            {/* Right side: Badges */}
            <div className="flex items-center gap-1.5">
              {/* Checklist Progress Badge */}
              {visibleFields.includes('checklist_progress') && 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, i) => (
                          <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 px-1.5 py-0.5 rounded cursor-help ${
                    (task.checklist_completed ?? 0) === task.checklist_total ? 'bg-success/10 text-success' : 'bg-[rgb(var(--color-border-50))] text-[rgb(var(--color-text-500))]'
                  }`}>
                    <CheckSquare className="w-3 h-3" />
                    <span>{task.checklist_completed ?? 0}/{task.checklist_total}</span>
                  </div>
                </Tooltip>
              )}

              {/* Dependencies Badge */}
              {showDependencies && hasDependencies && (
                <Tooltip
                  content={
                    <div className="text-xs space-y-2">
                      {dependencies!.predecessors.length > 0 && (
                        <div>
                          <div className="font-medium text-gray-300 mb-1">{t('dependencies.dependsOn', 'Depends on')}:</div>
                          {dependencies!.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>
                      )}
                      {dependencies!.successors.length > 0 && (
                        <div>
                          <div className="font-medium text-gray-300 mb-1">{t('dependencies.blocks', 'Blocks')}:</div>
                          {dependencies!.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 px-1.5 py-0.5 rounded ${
                    hasBlockingDeps ? 'bg-destructive/10 text-destructive' : 'bg-primary/10 text-primary'
                  }`}>
                    {hasBlockingDeps ? <Ban className="w-3 h-3" /> : <GitBranch className="w-3 h-3" />}
                    <span>{dependencies!.predecessors.length + dependencies!.successors.length}</span>
                  </div>
                </Tooltip>
              )}
            </div>
          </div>
        )}

        {/* Assigned To */}
        {visibleFields.includes('assigned_to') && task.assigned_to_name && task.assigned_to_id && (
          <div className="flex items-center gap-2">
            <UserAvatar
              userId={task.assigned_to_id}
              userName={task.assigned_to_name}
              avatarUrl={task.assigned_to_avatar || null}
              size="sm"
            />
            <span>{task.assigned_to_name}</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"
                  style={{
                    color: 'rgb(var(--color-primary-500))',
                    backgroundColor: 'rgb(var(--color-primary-50))'
                  }}
                >
                  +{task.additional_agents.length}
                </span>
              </Tooltip>
            )}
          </div>
        )}

        {/* Estimated Hours */}
        {visibleFields.includes('estimated_hours') && task.estimated_hours != null && (
          <div className="flex items-center gap-1.5">
            <Clock className="w-3 h-3 text-[rgb(var(--color-text-400))]" />
            <span>{t('tasks.estimatedHours', 'Est')}: {(task.estimated_hours / 60).toFixed(1)}</span>
          </div>
        )}

        {/* Actual Hours (Hours Logged) */}
        {visibleFields.includes('actual_hours') && task.actual_hours != null && (
          <div className="flex items-center gap-1.5">
            <Clock className="w-3 h-3 text-[rgb(var(--color-text-400))]" />
            <span>{t('fields.hoursLogged', 'Logged')}: {(task.actual_hours / 60).toFixed(1)}</span>
          </div>
        )}
      </div>

      {/* Document Upload Section */}
      {allowUploads && (
        <div className="mt-3 pt-2 border-t border-gray-100 dark:border-[rgb(var(--color-border-200))]">
          <TaskDocumentUpload taskId={task.task_id} compact />
        </div>
      )}
    </div>
  );
}

// Phase card component for left pane
function PhaseCard({
  phase,
  isSelected,
  onClick,
  showCompletion,
  dateLocale
}: {
  phase: Phase;
  isSelected: boolean;
  onClick: () => void;
  showCompletion: boolean;
  dateLocale: Locale;
}) {
  const { t } = useTranslation('features/projects');

  return (
    <div
      onClick={onClick}
      className={`p-3 rounded-lg cursor-pointer transition-all ${
        isSelected
          ? 'bg-[rgb(var(--color-primary-50))] dark:bg-primary-500/10'
          : 'hover:bg-[rgb(var(--color-border-50))]'
      }`}
    >
      <div className="flex flex-col gap-1">
        {/* Phase name */}
        <div className="flex items-start justify-between gap-2">
          <span className={`text-lg font-bold ${isSelected ? 'text-purple-600' : 'text-[rgb(var(--color-text-900))]'}`}>
            {phase.phase_name}
          </span>
        </div>
        {showCompletion && phase.completion_percentage !== undefined && (
          <span className={`text-xs font-medium ${isSelected ? 'text-purple-600' : 'text-[rgb(var(--color-text-500))]'}`}>
            {phase.completion_percentage}%
          </span>
        )}

        {/* Phase dates */}
        {(phase.start_date || phase.end_date) && (
          <div className="flex items-center gap-1 text-xs text-[rgb(var(--color-text-500))]">
            <Calendar className="w-3 h-3" />
            {phase.start_date && format(new Date(phase.start_date), 'MMM d', { locale: dateLocale })}
            {phase.start_date && phase.end_date && ' - '}
            {phase.end_date && format(new Date(phase.end_date), 'MMM d, yyyy', { locale: dateLocale })}
          </div>
        )}

        {/* Phase description */}
        {phase.description && (
          <p className="text-sm text-[rgb(var(--color-text-600))]">
            {phase.description}
          </p>
        )}
      </div>
    </div>
  );
}

export default function ClientKanbanBoard({
  phases,
  statuses,
  tasks,
  config,
  selectedPhaseId,
  onPhaseSelect,
  loading = false,
  taskDependencies
}: ClientKanbanBoardProps) {
  const { t, i18n } = useTranslation('features/projects');
  const { resolvedTheme } = useTheme();
  const isDark = resolvedTheme === 'dark';
  const dateLocale = getDateFnsLocale(i18n.language);
  const showPhases = config.show_phases ?? false;
  const showPhaseCompletion = config.show_phase_completion ?? false;
  const orderedStatuses = React.useMemo(
    () => [...statuses].sort((a, b) => a.display_order - b.display_order),
    [statuses]
  );

  // Filter tasks by selected phase for display in columns
  const phaseTasks = selectedPhaseId
    ? tasks.filter(t => t.phase_id === selectedPhaseId)
    : tasks;

  // Group filtered tasks by status for display
  const tasksByStatus = phaseTasks.reduce((acc, task) => {
    const statusId = task.project_status_mapping_id;
    if (!acc[statusId]) {
      acc[statusId] = [];
    }
    acc[statusId].push(task);
    return acc;
  }, {} as Record<string, Task[]>);

  // Default fallback colors for columns without configured colors
  const fallbackColors = ['#6B7280', '#6366F1', '#10B981', '#F59E0B', '#EF4444'];

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

  if (orderedStatuses.length === 0) {
    return (
      <div className="text-center py-8 text-[rgb(var(--color-text-500))]">
        {t('tasks.noTasks', 'No tasks to display')}
      </div>
    );
  }

  return (
    <div className="flex gap-4">
      {/* Left Pane - Phase Cards */}
      {showPhases && phases.length > 0 && (
        <div className="w-56 flex-shrink-0 space-y-2">
          <h4 className="text-xs font-medium text-[rgb(var(--color-text-500))] px-1 mb-3">
            {t('phases.title', 'Phases')}
          </h4>
          {phases.map((phase) => (
              <PhaseCard
                key={phase.phase_id}
                phase={phase}
                isSelected={selectedPhaseId === phase.phase_id}
                onClick={() => onPhaseSelect(phase.phase_id)}
                showCompletion={showPhaseCompletion}
                dateLocale={dateLocale}
              />
            ))}
        </div>
      )}

      {/* Right Pane - Kanban Columns */}
      <div className="flex-1 flex gap-4 overflow-x-auto pb-4">
        {orderedStatuses.map((status, index) => {
          const statusTasks = tasksByStatus[status.project_status_mapping_id] || [];
          const statusColor = status.color || fallbackColors[index % fallbackColors.length];

          return (
            <div
              key={status.project_status_mapping_id}
              className="flex-shrink-0 w-80 rounded-lg border-2"
              style={{
                backgroundColor: isDark ? darkenColor(statusColor, 0.75) : lightenColor(statusColor, 0.90),
                borderColor: isDark ? darkenColor(statusColor, 0.60) : lightenColor(statusColor, 0.70)
              }}
            >
              {/* Column Header */}
              <div className="p-3">
                <div className="flex items-center justify-between">
                  <div
                    className="flex items-center gap-2 px-3 py-1.5 rounded-2xl border-2"
                    style={{
                      backgroundColor: isDark ? darkenColor(statusColor, 0.60) : lightenColor(statusColor, 0.75),
                      borderColor: isDark ? darkenColor(statusColor, 0.40) : lightenColor(statusColor, 0.50)
                    }}
                  >
                    <div
                      className="w-2.5 h-2.5 rounded-full"
                      style={{ backgroundColor: statusColor }}
                    />
                    <h3 className="font-medium text-gray-900 dark:text-gray-100 text-sm">{status.name}</h3>
                  </div>
                  <span
                    className="text-xs font-medium px-2 py-0.5 rounded-full"
                    style={{
                      backgroundColor: isDark ? darkenColor(statusColor, 0.60) : lightenColor(statusColor, 0.70),
                      color: isDark ? lightenColor(statusColor, 0.40) : statusColor
                    }}
                  >
                    {statusTasks.length}
                  </span>
                </div>
              </div>

              {/* Tasks */}
              <div className="px-2 pb-2 space-y-2 max-h-[calc(100vh-400px)] overflow-y-auto">
                {statusTasks.length === 0 ? (
                  <div className="text-center py-4 text-xs text-[rgb(var(--color-text-400))]">
                    {t('tasks.noTasks', 'No tasks')}
                  </div>
                ) : (
                  statusTasks.map((task) => (
                    <TaskCard
                      key={task.task_id}
                      task={task}
                      config={config}
                      dateLocale={dateLocale}
                      dependencies={taskDependencies?.[task.task_id]}
                    />
                  ))
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
