import { useState, useEffect, useCallback, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import api from '../services/api'
import { KanbanBoard } from '../components/KanbanBoard'
import { CalendarView } from '../components/CalendarView'
import { GanttChart } from '../components/GanttChart'
import { TaskDetailModal } from '../components/TaskDetailModal'
import { UserSelect } from '../components/UserSelect'
import { UserSearchResult } from '../services/collaboration'
import { useProjectSync, TaskEvent } from '../contexts/ProjectSyncContext'
import { customFieldsApi, CustomField, CustomValueResponse } from '../services/customFields'
import { CustomFieldInput } from '../components/CustomFieldInput'
import { SkeletonTable, SkeletonKanban, Skeleton } from '../components/Skeleton'
import { logger } from '../utils/logger'

interface Task {
  id: string
  project_id: string
  title: string
  description: string | null
  priority: string
  status_id: string | null
  status_name: string | null
  status_color: string | null
  assignee_id: string | null
  assignee_name: string | null
  due_date: string | null
  start_date: string | null
  time_estimate: number | null
  subtask_count: number
  parent_task_id: string | null
  custom_values?: CustomValueResponse[]
  version?: number
}

interface TaskStatus {
  id: string
  name: string
  color: string
  is_done: boolean
}

interface Project {
  id: string
  title: string
  space_id: string
}

type ViewMode = 'list' | 'kanban' | 'calendar' | 'gantt'

const VIEW_MODE_STORAGE_KEY = 'tasks-view-mode'
const COLUMN_VISIBILITY_STORAGE_KEY = 'tasks-column-visibility'
const MOBILE_BREAKPOINT = 768

// Get column visibility settings from localStorage
const getColumnVisibility = (projectId: string): Record<string, boolean> => {
  try {
    const saved = localStorage.getItem(`${COLUMN_VISIBILITY_STORAGE_KEY}-${projectId}`)
    return saved ? JSON.parse(saved) : {}
  } catch {
    return {}
  }
}

// Save column visibility settings to localStorage
const saveColumnVisibility = (projectId: string, visibility: Record<string, boolean>) => {
  localStorage.setItem(`${COLUMN_VISIBILITY_STORAGE_KEY}-${projectId}`, JSON.stringify(visibility))
}

export default function Tasks() {
  const { t, i18n } = useTranslation('tasks')
  const { projectId } = useParams()
  const navigate = useNavigate()
  const { subscribeToProject, unsubscribeFromProject, addTaskEventListener, isConnected } = useProjectSync()
  const [project, setProject] = useState<Project | null>(null)
  const [tasks, setTasks] = useState<Task[]>([])
  const [statuses, setStatuses] = useState<TaskStatus[]>([])
  const [loading, setLoading] = useState(true)
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [isMobile, setIsMobile] = useState(false)
  const [viewMode, setViewMode] = useState<ViewMode>(() => {
    const saved = localStorage.getItem(VIEW_MODE_STORAGE_KEY)
    return (saved === 'kanban' || saved === 'list' || saved === 'calendar' || saved === 'gantt') ? saved : 'list'
  })
  const [newTask, setNewTask] = useState({
    title: '',
    description: '',
    priority: 'medium',
    assignee_id: '',
    start_date: '',
    due_date: '',
    time_estimate: '',
  })
  const [, setSelectedAssignee] = useState<UserSearchResult | null>(null)
  const [creating, setCreating] = useState(false)
  const [selectedTask, setSelectedTask] = useState<Task | null>(null)
  const [showDetailModal, setShowDetailModal] = useState(false)

  // Custom fields state
  const [customFields, setCustomFields] = useState<CustomField[]>([])
  const [newTaskCustomValues, setNewTaskCustomValues] = useState<Record<string, string | number | null>>({})

  // Column visibility state
  const [columnVisibility, setColumnVisibility] = useState<Record<string, boolean>>(() => {
    return projectId ? getColumnVisibility(projectId) : {}
  })
  const [showColumnMenu, setShowColumnMenu] = useState(false)
  const columnMenuRef = useRef<HTMLDivElement>(null)
  const createModalOverlayRef = useRef<HTMLDivElement>(null)

  // Detect mobile viewport
  useEffect(() => {
    const checkMobile = () => {
      setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    }

    checkMobile()
    window.addEventListener('resize', checkMobile)
    return () => window.removeEventListener('resize', checkMobile)
  }, [])

  useEffect(() => {
    loadData()
  }, [projectId])

  // Load custom fields when project changes
  useEffect(() => {
    if (projectId) {
      loadCustomFields()
    }
  }, [projectId])

  const loadCustomFields = async () => {
    try {
      const response = await customFieldsApi.getCustomFields(projectId!)
      setCustomFields(response.fields)
    } catch (err) {
      logger.error('Failed to load custom fields:', err)
    }
  }

  // Subscribe to project WebSocket when project changes
  // Use isMounted ref to handle React StrictMode's double-mount behavior
  const isMountedRef = useRef(true)
  useEffect(() => {
    isMountedRef.current = true
    if (projectId) {
      // Small delay to avoid race conditions with StrictMode's rapid mount/unmount
      const timeoutId = setTimeout(() => {
        if (isMountedRef.current) {
          subscribeToProject(projectId)
        }
      }, 100)
      return () => {
        clearTimeout(timeoutId)
        isMountedRef.current = false
        unsubscribeFromProject()
      }
    }
    return () => {
      isMountedRef.current = false
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId])

  // Handle real-time task events from WebSocket
  const handleTaskEvent = useCallback((event: TaskEvent) => {
    switch (event.type) {
      case 'task_created':
        // Add new task to list
        setTasks((prev) => {
          // Check if task already exists (avoid duplicates)
          if (prev.some((t) => t.id === event.data.task_id)) {
            return prev
          }
          const newTask: Task = {
            id: event.data.task_id,
            project_id: projectId!,
            title: event.data.title || '',
            description: event.data.description ?? null,
            priority: event.data.priority || 'medium',
            status_id: event.data.status_id ?? null,
            status_name: event.data.status_name ?? null,
            status_color: event.data.status_color ?? null,
            assignee_id: event.data.assignee_id ?? null,
            assignee_name: event.data.assignee_name ?? null,
            due_date: event.data.due_date ?? null,
            start_date: (event.data.start_date as string) ?? null,
            time_estimate: event.data.time_estimate ?? event.data.original_estimate ?? null,
            subtask_count: event.data.subtask_count ?? 0,
            parent_task_id: (event.data.parent_task_id as string) ?? null,
          }
          return [...prev, newTask]
        })
        break

      case 'task_updated':
      case 'task_status_changed':
      case 'task_assigned':
        // Update existing task
        setTasks((prev) =>
          prev.map((task) => {
            if (task.id !== event.data.task_id) return task
            // Merge event data into existing task
            return {
              ...task,
              ...(event.data.title !== undefined && { title: event.data.title }),
              ...(event.data.description !== undefined && { description: event.data.description ?? null }),
              ...(event.data.priority !== undefined && { priority: event.data.priority }),
              ...(event.data.status_id !== undefined && { status_id: event.data.status_id ?? null }),
              ...(event.data.status_name !== undefined && { status_name: event.data.status_name ?? null }),
              ...(event.data.status_color !== undefined && { status_color: event.data.status_color ?? null }),
              ...(event.data.new_status_id !== undefined && { status_id: event.data.new_status_id ?? null }),
              ...(event.data.new_status_name !== undefined && { status_name: event.data.new_status_name ?? null }),
              ...(event.data.new_status_color !== undefined && { status_color: event.data.new_status_color ?? null }),
              ...(event.data.assignee_id !== undefined && { assignee_id: event.data.assignee_id ?? null }),
              ...(event.data.assignee_name !== undefined && { assignee_name: event.data.assignee_name ?? null }),
              ...(event.data.new_assignee_id !== undefined && { assignee_id: event.data.new_assignee_id ?? null }),
              ...(event.data.new_assignee_name !== undefined && { assignee_name: event.data.new_assignee_name ?? null }),
              ...(event.data.due_date !== undefined && { due_date: event.data.due_date ?? null }),
              ...(event.data.start_date !== undefined && { start_date: (event.data.start_date as string) ?? null }),
              ...(event.data.time_estimate !== undefined && { time_estimate: event.data.time_estimate ?? null }),
              ...(event.data.original_estimate !== undefined && event.data.time_estimate === undefined && { time_estimate: event.data.original_estimate ?? null }),
              ...(event.data.subtask_count !== undefined && { subtask_count: event.data.subtask_count }),
            }
          })
        )
        break

      case 'task_deleted':
        // Remove task from list
        setTasks((prev) => prev.filter((task) => task.id !== event.data.task_id))
        break
    }
  }, [])

  useEffect(() => {
    const unsubscribe = addTaskEventListener(handleTaskEvent)
    return unsubscribe
  }, [addTaskEventListener, handleTaskEvent])

  // Persist view mode
  useEffect(() => {
    localStorage.setItem(VIEW_MODE_STORAGE_KEY, viewMode)
  }, [viewMode])

  // Load column visibility when projectId changes
  useEffect(() => {
    if (projectId) {
      setColumnVisibility(getColumnVisibility(projectId))
    }
  }, [projectId])

  // Check if a custom field column is visible (default to true if not set)
  const isColumnVisible = (fieldId: string): boolean => {
    return columnVisibility[fieldId] !== false
  }

  // Toggle column visibility
  const toggleColumnVisibility = (fieldId: string) => {
    const newVisibility = {
      ...columnVisibility,
      [fieldId]: !isColumnVisible(fieldId),
    }
    setColumnVisibility(newVisibility)
    if (projectId) {
      saveColumnVisibility(projectId, newVisibility)
    }
  }

  // Close column menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (columnMenuRef.current && !columnMenuRef.current.contains(event.target as Node)) {
        setShowColumnMenu(false)
      }
    }

    if (showColumnMenu) {
      document.addEventListener('mousedown', handleClickOutside)
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside)
    }
  }, [showColumnMenu])

  // Handle Escape key to close create modal - document-level listener
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && showCreateModal) {
        setShowCreateModal(false)
      }
    }

    if (showCreateModal) {
      document.addEventListener('keydown', handleKeyDown)
      // Focus the overlay for accessibility
      createModalOverlayRef.current?.focus()
    }

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
    }
  }, [showCreateModal])

  const loadData = async () => {
    try {
      const [projectRes, tasksRes, statusesRes] = await Promise.all([
        api.get(`/projects/${projectId}`),
        api.get(`/projects/${projectId}/tasks`),
        api.get(`/projects/${projectId}/statuses`),
      ])
      setProject(projectRes.data)
      setTasks(tasksRes.data.tasks)
      setStatuses(statusesRes.data)
    } catch (err) {
      logger.error('Failed to load data:', err)
    } finally {
      setLoading(false)
    }
  }

  const handleCreateTask = async () => {
    if (!newTask.title.trim()) return

    setCreating(true)
    try {
      const payload: Record<string, unknown> = {
        title: newTask.title,
        description: newTask.description || null,
        priority: newTask.priority,
      }

      if (newTask.assignee_id) {
        payload.assignee_id = newTask.assignee_id
      }
      if (newTask.start_date) {
        // Convert date string to datetime format for Pydantic
        payload.start_date = `${newTask.start_date}T00:00:00`
      }
      if (newTask.due_date) {
        // Convert date string to datetime format for Pydantic
        payload.due_date = `${newTask.due_date}T00:00:00`
      }
      if (newTask.time_estimate) {
        payload.original_estimate = Number(newTask.time_estimate)
      }

      // Include custom field values (only non-formula fields)
      const customValuesPayload = Object.entries(newTaskCustomValues)
        .filter(([fieldId, value]) => {
          const field = customFields.find((f) => f.id === fieldId)
          return field && field.field_type !== 'formula' && value !== null
        })
        .map(([fieldId, value]) => ({
          field_id: fieldId,
          value: value,
        }))

      if (customValuesPayload.length > 0) {
        payload.custom_values = customValuesPayload
      }

      await api.post(`/projects/${projectId}/tasks`, payload)
      setShowCreateModal(false)
      setNewTask({
        title: '',
        description: '',
        priority: 'medium',
        assignee_id: '',
        start_date: '',
        due_date: '',
        time_estimate: '',
      })
      setNewTaskCustomValues({})
      setSelectedAssignee(null)
      loadData()
    } catch (err) {
      logger.error('Failed to create task:', err)
    } finally {
      setCreating(false)
    }
  }

  const handleNewTaskCustomFieldChange = (fieldId: string, value: string | number | null) => {
    setNewTaskCustomValues((prev) => ({
      ...prev,
      [fieldId]: value,
    }))
  }

  const handleStatusChange = async (taskId: string, statusId: string) => {
    // Save original state for rollback
    const originalTasks = [...tasks]

    // Find the target status for optimistic update
    const targetStatus = statuses.find((s) => s.id === statusId)

    // Optimistic update
    setTasks((prev) =>
      prev.map((task) =>
        task.id === taskId
          ? {
              ...task,
              status_id: statusId,
              status_name: targetStatus?.name ?? null,
              status_color: targetStatus?.color ?? null,
            }
          : task
      )
    )

    try {
      await api.patch(`/tasks/${taskId}/status`, { status_id: statusId })
      // Success - real-time event from WebSocket will be ignored (triggered_by check)
    } catch (err) {
      // Rollback on error
      setTasks(originalTasks)
      logger.error('Failed to update status:', err)
      // Could add toast notification here for better UX
    }
  }

  const handleTaskClick = (task: Task) => {
    // Ensure task has project_id for custom fields loading
    const taskWithProject = {
      ...task,
      project_id: projectId!,
    }
    setSelectedTask(taskWithProject)
    setShowDetailModal(true)
  }

  const handleAssigneeChange = (userId: string | null, user: UserSearchResult | null) => {
    setNewTask({ ...newTask, assignee_id: userId || '' })
    setSelectedAssignee(user)
  }

  const handleCloseDetailModal = () => {
    setShowDetailModal(false)
    setSelectedTask(null)
  }

  const handleTaskUpdate = async () => {
    await loadData()
    // If a task is selected (modal is open), re-fetch its data to show updated values
    if (selectedTask) {
      try {
        const response = await api.get(`/tasks/${selectedTask.id}`)
        const updatedTask = response.data
        setSelectedTask({
          ...updatedTask,
          project_id: projectId!,
          time_estimate: updatedTask.original_estimate,
        })
      } catch (err) {
        logger.error('Failed to refresh selected task:', err)
      }
    }
  }

  const handleSubtaskClick = async (subtaskId: string) => {
    try {
      const response = await api.get(`/tasks/${subtaskId}`)
      const subtask = response.data
      // Ensure subtask has project_id for custom fields loading
      const subtaskWithProject = {
        ...subtask,
        project_id: projectId!,
        // Map API response fields to frontend Task interface
        time_estimate: subtask.original_estimate,
      }
      setSelectedTask(subtaskWithProject)
      // Modal is already open, just update the task
    } catch (err) {
      logger.error('Failed to load subtask:', err)
    }
  }

  const getPriorityColor = (priority: string): string => {
    const colors: { [key: string]: string } = {
      low: '#808080',
      medium: '#0066cc',
      high: '#ff9800',
      urgent: '#f44336',
    }
    return colors[priority] || colors.medium
  }

  const getPriorityStyle = (priority: string): React.CSSProperties => {
    return {
      width: '4px',
      backgroundColor: getPriorityColor(priority),
      borderRadius: '2px',
    }
  }

  // Format date according to locale
  const formatDate = (dateString: string): string => {
    const date = new Date(dateString)
    return date.toLocaleDateString(i18n.language, {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
    })
  }

  // Render task card for mobile view
  const renderTaskCard = (task: Task) => (
    <div
      key={task.id}
      style={styles.taskCard}
      onClick={() => handleTaskClick(task)}
    >
      <div style={styles.taskCardHeader}>
        <div
          style={{
            ...styles.taskCardPriority,
            backgroundColor: getPriorityColor(task.priority),
          }}
        />
        <h3 style={styles.taskCardTitle}>{task.title}</h3>
      </div>

      {task.description && (
        <p style={styles.taskCardDescription}>
          {task.description.length > 100
            ? task.description.substring(0, 100) + '...'
            : task.description}
        </p>
      )}

      <div style={styles.taskCardMeta}>
        {task.assignee_name && (
          <span style={styles.taskCardAssignee}>{task.assignee_name}</span>
        )}
        {task.due_date && (
          <span style={styles.taskCardDueDate}>
            {t('fields.dueDate')}: {formatDate(task.due_date)}
          </span>
        )}
      </div>

      <div style={styles.taskCardFooter}>
        <div
          style={{
            ...styles.taskCardStatus,
            backgroundColor: task.status_color || '#e0e0e0',
          }}
        >
          {task.status_name || t('status.noStatus')}
        </div>
        {task.subtask_count > 0 && (
          <span style={styles.taskCardSubtasks}>
            {t('subtasks.count', { count: task.subtask_count })}
          </span>
        )}
        {task.time_estimate && (
          <span style={styles.taskCardEstimate}>
            {t('fields.hours', { count: task.time_estimate })}
          </span>
        )}
      </div>

      {/* Mobile status change action */}
      <div style={styles.taskCardActions}>
        <select
          value={task.status_id || ''}
          onChange={(e) => {
            e.stopPropagation()
            handleStatusChange(task.id, e.target.value)
          }}
          onClick={(e) => e.stopPropagation()}
          style={styles.taskCardStatusSelect}
        >
          {statuses.map((status) => (
            <option key={status.id} value={status.id}>
              {status.name}
            </option>
          ))}
        </select>
      </div>
    </div>
  )

  if (loading) {
    return (
      <div style={styles.container}>
        <div style={styles.header}>
          <Skeleton variant="text" width={200} height={32} />
          <div style={{ display: 'flex', gap: '8px' }}>
            <Skeleton variant="rect" width={100} height={36} />
            <Skeleton variant="rect" width={100} height={36} />
          </div>
        </div>
        {viewMode === 'kanban' ? <SkeletonKanban columns={4} /> : <SkeletonTable rows={8} columns={5} />}
      </div>
    )
  }

  return (
    <div style={isMobile ? styles.containerMobile : styles.container}>
      <div style={styles.breadcrumb}>
        <span onClick={() => navigate('/spaces')} style={styles.breadcrumbLink}>
          {t('common:nav.spaces')}
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span
          onClick={() => navigate(`/spaces/${project?.space_id}`)}
          style={styles.breadcrumbLink}
        >
          {t('common:nav.projects')}
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span>{project?.title}</span>
      </div>

      <div style={isMobile ? styles.headerMobile : styles.header}>
        <div style={styles.titleContainer}>
          <h1 style={isMobile ? styles.titleMobile : styles.title}>{t('title')}</h1>
          {isConnected ? (
            <span style={styles.liveIndicator} title={t('common:labels.active')}>
              {'\u25CF'} {t('common:labels.live')}
            </span>
          ) : projectId ? (
            <span style={styles.offlineIndicator} title={t('common:labels.inactive')}>
              {'\u25CB'} {t('common:labels.offline')}
            </span>
          ) : null}
        </div>
        <div style={isMobile ? styles.headerActionsMobile : styles.headerActions}>
          {/* View Toggle */}
          <div style={isMobile ? styles.viewToggleMobile : styles.viewToggle}>
            <button
              onClick={() => setViewMode('list')}
              style={{
                ...styles.viewButton,
                ...(isMobile ? styles.viewButtonMobile : {}),
                ...(viewMode === 'list' ? styles.viewButtonActive : {}),
              }}
              aria-label={t('views.list')}
            >
              {isMobile ? '\u2630' : t('views.list')}
            </button>
            <button
              onClick={() => setViewMode('kanban')}
              style={{
                ...styles.viewButton,
                ...(isMobile ? styles.viewButtonMobile : {}),
                ...(viewMode === 'kanban' ? styles.viewButtonActive : {}),
              }}
              aria-label={t('views.kanban')}
            >
              {isMobile ? '\u25A6' : t('views.kanban')}
            </button>
            <button
              onClick={() => setViewMode('calendar')}
              style={{
                ...styles.viewButton,
                ...(isMobile ? styles.viewButtonMobile : {}),
                ...(viewMode === 'calendar' ? styles.viewButtonActive : {}),
              }}
              aria-label={t('views.calendar')}
            >
              {isMobile ? '\u25A1' : t('views.calendar')}
            </button>
            {!isMobile && (
              <button
                onClick={() => setViewMode('gantt')}
                style={{
                  ...styles.viewButton,
                  ...(viewMode === 'gantt' ? styles.viewButtonActive : {}),
                }}
                aria-label={t('views.gantt')}
              >
                {t('views.gantt')}
              </button>
            )}
          </div>
          {/* Column Visibility Toggle - only show when there are custom fields and in list view */}
          {!isMobile && viewMode === 'list' && customFields.length > 0 && (
            <div style={styles.columnMenuContainer} ref={columnMenuRef}>
              <button
                onClick={() => setShowColumnMenu(!showColumnMenu)}
                style={styles.columnMenuButton}
                aria-label={t('settings:customFields.title')}
              >
                {t('settings:customFields.title')}
              </button>
              {showColumnMenu && (
                <div style={styles.columnMenuDropdown}>
                  <div style={styles.columnMenuHeader}>{t('settings:customFields.title')}</div>
                  {customFields.map((field) => (
                    <label key={field.id} style={styles.columnMenuItem}>
                      <input
                        type="checkbox"
                        checked={isColumnVisible(field.id)}
                        onChange={() => toggleColumnVisibility(field.id)}
                        style={styles.columnCheckbox}
                      />
                      <span style={styles.columnLabel}>{field.name}</span>
                    </label>
                  ))}
                  {customFields.length === 0 && (
                    <div style={styles.columnMenuEmpty}>{t('common:labels.noData')}</div>
                  )}
                </div>
              )}
            </div>
          )}
          {!isMobile && (
            <button
              onClick={() => navigate(`/projects/${projectId}/settings`)}
              style={styles.settingsButton}
              aria-label={t('common:nav.settings')}
            >
              {t('common:nav.settings')}
            </button>
          )}
          <button
            onClick={() => setShowCreateModal(true)}
            style={isMobile ? styles.createButtonMobile : styles.createButton}
          >
            {isMobile ? '+' : `+ ${t('createTask')}`}
          </button>
        </div>
      </div>

      {/* Conditional rendering based on view mode */}
      {viewMode === 'list' && (
        isMobile ? (
          // Mobile card view
          <div style={styles.taskCardList}>
            {tasks.map(renderTaskCard)}
            {tasks.length === 0 && (
              <div style={styles.empty}>
                <p>{t('empty.description')}</p>
              </div>
            )}
          </div>
        ) : (
          // Desktop list view with horizontal scroll for wide tables
          <div style={styles.tableWrapper}>
            <div style={styles.taskList}>
              {tasks.map((task) => (
                <div
                  key={task.id}
                  style={styles.taskRow}
                  onClick={() => handleTaskClick(task)}
                >
                  <div style={getPriorityStyle(task.priority)} />
                  <div style={styles.taskContent}>
                    <div style={styles.taskTitle}>{task.title}</div>
                    <div style={styles.taskMeta}>
                      {task.assignee_name && (
                        <span style={styles.assignee}>{task.assignee_name}</span>
                      )}
                      {task.due_date && (
                        <span style={styles.dueDate}>
                          {t('fields.dueDate')}: {formatDate(task.due_date)}
                        </span>
                      )}
                      {task.time_estimate && (
                        <span style={styles.timeEstimate}>
                          {t('fields.hours', { count: task.time_estimate })}
                        </span>
                      )}
                      {task.subtask_count > 0 && (
                        <span style={styles.subtaskCount}>
                          {t('subtasks.count', { count: task.subtask_count })}
                        </span>
                      )}
                      {/* Display visible custom field values */}
                      {task.custom_values &&
                        task.custom_values
                          .filter((cv) => isColumnVisible(cv.field_id))
                          .map((cv) => (
                            <span key={cv.field_id} style={styles.customValueBadge}>
                              {cv.field_name}: {cv.display_value || cv.value || '-'}
                            </span>
                          ))}
                    </div>
                  </div>
                  <select
                    value={task.status_id || ''}
                    onChange={(e) => {
                      e.stopPropagation()
                      handleStatusChange(task.id, e.target.value)
                    }}
                    onClick={(e) => e.stopPropagation()}
                    style={{
                      ...styles.statusSelect,
                      backgroundColor: task.status_color || '#f5f5f5',
                    }}
                  >
                    {statuses.map((status) => (
                      <option key={status.id} value={status.id}>
                        {status.name}
                      </option>
                    ))}
                  </select>
                </div>
              ))}

              {tasks.length === 0 && (
                <div style={styles.empty}>
                  <p>{t('empty.description')}</p>
                </div>
              )}
            </div>
          </div>
        )
      )}

      {viewMode === 'kanban' && (
        <div style={styles.kanbanWrapper}>
          <KanbanBoard
            tasks={tasks}
            statuses={statuses}
            onStatusChange={handleStatusChange}
            onTaskClick={handleTaskClick}
          />
        </div>
      )}

      {viewMode === 'calendar' && projectId && (
        <CalendarView
          projectId={projectId}
          statuses={statuses}
          onTaskClick={handleTaskClick}
          onTaskUpdate={handleTaskUpdate}
        />
      )}

      {viewMode === 'gantt' && projectId && !isMobile && (
        <GanttChart
          projectId={projectId}
          tasks={tasks}
          statuses={statuses}
          onTaskClick={handleTaskClick}
          onTaskUpdate={handleTaskUpdate}
        />
      )}

      {/* Create Task Modal */}
      {showCreateModal && (
        <div
          ref={createModalOverlayRef}
          style={styles.modalOverlay}
          tabIndex={-1}
          role="dialog"
          aria-modal="true"
          aria-labelledby="create-task-title"
        >
          <div style={isMobile ? styles.modalMobile : styles.modal}>
            <h2 id="create-task-title" style={styles.modalTitle}>{t('createTask')}</h2>
            <label htmlFor="task-title" style={styles.visuallyHidden}>
              {t('fields.title')}
            </label>
            <input
              id="task-title"
              type="text"
              placeholder={t('fields.titlePlaceholder')}
              value={newTask.title}
              onChange={(e) => setNewTask({ ...newTask, title: e.target.value })}
              style={styles.input}
              autoFocus
            />
            <label htmlFor="task-description" style={styles.visuallyHidden}>
              {t('fields.description')}
            </label>
            <textarea
              id="task-description"
              placeholder={t('fields.descriptionPlaceholder')}
              value={newTask.description}
              onChange={(e) => setNewTask({ ...newTask, description: e.target.value })}
              style={styles.textarea}
            />

            <label style={styles.label}>{t('fields.priority')}</label>
            <select
              value={newTask.priority}
              onChange={(e) => setNewTask({ ...newTask, priority: e.target.value })}
              style={styles.select}
            >
              <option value="low">{t('priority.low')}</option>
              <option value="medium">{t('priority.medium')}</option>
              <option value="high">{t('priority.high')}</option>
              <option value="urgent">{t('priority.urgent')}</option>
            </select>

            <label style={styles.label}>{t('fields.assignee')}</label>
            <UserSelect
              value={newTask.assignee_id}
              onChange={handleAssigneeChange}
              placeholder={t('common:labels.selectAssignee')}
            />
            <div style={styles.fieldSpacer} />

            <label style={styles.label}>{t('fields.startDate')}</label>
            <input
              type="date"
              value={newTask.start_date}
              onChange={(e) => setNewTask({ ...newTask, start_date: e.target.value })}
              style={styles.input}
            />

            <label style={styles.label}>{t('fields.dueDate')}</label>
            <input
              type="date"
              value={newTask.due_date}
              onChange={(e) => setNewTask({ ...newTask, due_date: e.target.value })}
              style={styles.input}
            />

            <label style={styles.label}>{t('fields.estimatedHours')}</label>
            <input
              type="number"
              min="0"
              step="0.5"
              placeholder={t('fields.estimatedHours')}
              value={newTask.time_estimate}
              onChange={(e) => setNewTask({ ...newTask, time_estimate: e.target.value })}
              style={styles.input}
            />

            {/* Custom Fields */}
            {customFields.filter((f) => f.field_type !== 'formula').length > 0 && (
              <>
                <div style={styles.customFieldsDivider} />
                <div style={styles.customFieldsTitle}>{t('settings:customFields.title')}</div>
                {customFields
                  .filter((field) => field.field_type !== 'formula')
                  .map((field) => (
                    <div key={field.id} style={styles.customFieldContainer}>
                      <CustomFieldInput
                        field={field}
                        value={
                          newTaskCustomValues[field.id] !== undefined
                            ? {
                                field_id: field.id,
                                field_name: field.name,
                                field_type: field.field_type,
                                value: newTaskCustomValues[field.id],
                                display_value: null,
                              }
                            : null
                        }
                        onChange={handleNewTaskCustomFieldChange}
                        disabled={false}
                        showLabel={true}
                      />
                    </div>
                  ))}
              </>
            )}

            <div style={styles.modalActions}>
              <button onClick={() => setShowCreateModal(false)} style={styles.cancelButton}>
                {t('common:buttons.cancel')}
              </button>
              <button
                onClick={handleCreateTask}
                disabled={creating || !newTask.title.trim()}
                style={styles.submitButton}
              >
                {creating ? t('common:labels.loading') : t('common:buttons.create')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Task Detail Modal */}
      {selectedTask && (
        <TaskDetailModal
          task={selectedTask}
          statuses={statuses}
          isOpen={showDetailModal}
          onClose={handleCloseDetailModal}
          onUpdate={handleTaskUpdate}
          onSubtaskClick={handleSubtaskClick}
        />
      )}
    </div>
  )
}

const styles: { [key: string]: React.CSSProperties } = {
  container: {
    padding: '24px',
    maxWidth: '1200px',
    margin: '0 auto',
  },
  containerMobile: {
    padding: '16px',
    maxWidth: '100%',
    margin: '0 auto',
  },
  breadcrumb: {
    marginBottom: '16px',
    fontSize: '14px',
    color: '#666',
    overflowX: 'auto',
    whiteSpace: 'nowrap',
  },
  breadcrumbLink: {
    color: '#0066cc',
    cursor: 'pointer',
    padding: '4px',
  },
  breadcrumbSeparator: {
    margin: '0 8px',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '24px',
    flexWrap: 'wrap',
    gap: '12px',
  },
  headerMobile: {
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
    marginBottom: '16px',
  },
  titleContainer: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
  },
  title: {
    fontSize: '24px',
    fontWeight: 600,
    margin: 0,
  },
  titleMobile: {
    fontSize: '20px',
    fontWeight: 600,
    margin: 0,
  },
  liveIndicator: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: '4px',
    fontSize: '12px',
    color: '#22c55e',
    fontWeight: 500,
    padding: '2px 8px',
    backgroundColor: '#f0fdf4',
    borderRadius: '10px',
    border: '1px solid #bbf7d0',
  },
  offlineIndicator: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: '4px',
    padding: '2px 8px',
    fontSize: '11px',
    color: '#f44336',
    backgroundColor: '#ffebee',
    borderRadius: '4px',
    marginLeft: '8px',
  },
  headerActions: {
    display: 'flex',
    gap: '12px',
    alignItems: 'center',
    flexWrap: 'wrap',
  },
  headerActionsMobile: {
    display: 'flex',
    gap: '8px',
    alignItems: 'center',
    justifyContent: 'space-between',
    width: '100%',
  },
  viewToggle: {
    display: 'flex',
    border: '1px solid #ddd',
    borderRadius: '6px',
    overflow: 'hidden',
  },
  viewToggleMobile: {
    display: 'flex',
    border: '1px solid #ddd',
    borderRadius: '6px',
    overflow: 'hidden',
    flex: 1,
  },
  viewButton: {
    padding: '10px 16px',
    backgroundColor: 'white',
    border: 'none',
    cursor: 'pointer',
    fontSize: '14px',
    color: '#666',
    transition: 'background-color 0.2s, color 0.2s',
    minHeight: '44px',
    minWidth: '44px',
  },
  viewButtonMobile: {
    flex: 1,
    padding: '12px 8px',
    fontSize: '16px',
  },
  viewButtonActive: {
    backgroundColor: '#0066cc',
    color: 'white',
  },
  settingsButton: {
    padding: '10px 16px',
    backgroundColor: '#f5f5f5',
    color: '#333',
    border: '1px solid #ddd',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    minHeight: '44px',
    minWidth: '44px',
  },
  createButton: {
    padding: '10px 20px',
    backgroundColor: '#0066cc',
    color: 'white',
    border: 'none',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    fontWeight: 500,
    minHeight: '44px',
    minWidth: '44px',
  },
  createButtonMobile: {
    padding: '12px 20px',
    backgroundColor: '#0066cc',
    color: 'white',
    border: 'none',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '18px',
    fontWeight: 600,
    minHeight: '48px',
    minWidth: '48px',
  },
  // Table wrapper for horizontal scroll
  tableWrapper: {
    overflowX: 'auto',
    WebkitOverflowScrolling: 'touch',
  },
  taskList: {
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
    overflow: 'hidden',
    minWidth: '600px', // Ensure minimum width for horizontal scroll
  },
  // Kanban wrapper for horizontal scroll
  kanbanWrapper: {
    overflowX: 'auto',
    WebkitOverflowScrolling: 'touch',
    paddingBottom: '16px',
  },
  taskRow: {
    display: 'flex',
    alignItems: 'center',
    padding: '16px',
    borderBottom: '1px solid #eee',
    gap: '12px',
    cursor: 'pointer',
    transition: 'background-color 0.15s ease',
    minHeight: '60px',
  },
  taskContent: {
    flex: 1,
    minWidth: 0, // Enable text truncation
  },
  taskTitle: {
    fontSize: '14px',
    fontWeight: 500,
    marginBottom: '4px',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  },
  taskMeta: {
    display: 'flex',
    gap: '12px',
    fontSize: '12px',
    color: '#666',
    flexWrap: 'wrap',
  },
  assignee: {
    backgroundColor: '#f0f0f0',
    padding: '2px 6px',
    borderRadius: '4px',
  },
  dueDate: {},
  timeEstimate: {
    color: '#0066cc',
  },
  subtaskCount: {
    color: '#767676', // WCAG AA compliant
  },
  statusSelect: {
    padding: '8px 12px',
    border: 'none',
    borderRadius: '4px',
    fontSize: '12px',
    cursor: 'pointer',
    color: 'white',
    minHeight: '36px',
    minWidth: '100px',
  },
  // Mobile card view styles
  taskCardList: {
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  },
  taskCard: {
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
    padding: '16px',
    cursor: 'pointer',
  },
  taskCardHeader: {
    display: 'flex',
    alignItems: 'flex-start',
    gap: '12px',
    marginBottom: '8px',
  },
  taskCardPriority: {
    width: '4px',
    height: '24px',
    borderRadius: '2px',
    flexShrink: 0,
  },
  taskCardTitle: {
    margin: 0,
    fontSize: '16px',
    fontWeight: 500,
    lineHeight: 1.4,
    flex: 1,
  },
  taskCardDescription: {
    margin: '0 0 12px 0',
    fontSize: '14px',
    color: '#666',
    lineHeight: 1.4,
  },
  taskCardMeta: {
    display: 'flex',
    flexWrap: 'wrap',
    gap: '8px',
    marginBottom: '12px',
    fontSize: '13px',
  },
  taskCardAssignee: {
    backgroundColor: '#e3f2fd',
    color: '#1565c0',
    padding: '4px 8px',
    borderRadius: '4px',
  },
  taskCardDueDate: {
    color: '#666',
  },
  taskCardFooter: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px',
    flexWrap: 'wrap',
  },
  taskCardStatus: {
    padding: '4px 10px',
    borderRadius: '4px',
    fontSize: '12px',
    fontWeight: 500,
    color: 'white',
  },
  taskCardSubtasks: {
    fontSize: '12px',
    color: '#767676',
  },
  taskCardEstimate: {
    fontSize: '12px',
    color: '#0066cc',
  },
  taskCardActions: {
    marginTop: '12px',
    paddingTop: '12px',
    borderTop: '1px solid #eee',
  },
  taskCardStatusSelect: {
    width: '100%',
    padding: '12px',
    border: '1px solid #ddd',
    borderRadius: '6px',
    fontSize: '14px',
    backgroundColor: 'white',
    minHeight: '48px',
  },
  empty: {
    textAlign: 'center',
    padding: '48px',
    color: '#666',
  },
  loading: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    height: '200px',
  },
  modalOverlay: {
    position: 'fixed',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    zIndex: 1000,
    padding: '16px',
  },
  modal: {
    backgroundColor: 'white',
    padding: '24px',
    borderRadius: '8px',
    width: '450px',
    maxWidth: '100%',
    maxHeight: '90vh',
    overflowY: 'auto',
  },
  modalMobile: {
    backgroundColor: 'white',
    padding: '20px',
    borderRadius: '12px',
    width: '100%',
    maxWidth: '100%',
    maxHeight: '85vh',
    overflowY: 'auto',
  },
  modalTitle: {
    marginBottom: '16px',
  },
  input: {
    width: '100%',
    padding: '12px',
    marginBottom: '12px',
    border: '1px solid #ddd',
    borderRadius: '6px',
    fontSize: '16px',
    boxSizing: 'border-box',
    minHeight: '48px',
  },
  textarea: {
    width: '100%',
    padding: '12px',
    marginBottom: '12px',
    border: '1px solid #ddd',
    borderRadius: '6px',
    fontSize: '16px',
    minHeight: '100px',
    resize: 'vertical',
    boxSizing: 'border-box',
  },
  label: {
    display: 'block',
    marginBottom: '4px',
    fontSize: '14px',
    fontWeight: 500,
  },
  select: {
    width: '100%',
    padding: '12px',
    marginBottom: '12px',
    border: '1px solid #ddd',
    borderRadius: '6px',
    fontSize: '16px',
    boxSizing: 'border-box',
    minHeight: '48px',
  },
  fieldSpacer: {
    height: '12px',
  },
  modalActions: {
    display: 'flex',
    justifyContent: 'flex-end',
    gap: '12px',
    marginTop: '16px',
  },
  cancelButton: {
    padding: '12px 20px',
    backgroundColor: '#f5f5f5',
    border: '1px solid #ddd',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    minHeight: '48px',
    minWidth: '80px',
  },
  submitButton: {
    padding: '12px 20px',
    backgroundColor: '#0066cc',
    color: 'white',
    border: 'none',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    minHeight: '48px',
    minWidth: '80px',
  },
  customFieldsDivider: {
    height: '1px',
    backgroundColor: '#eee',
    margin: '16px 0',
  },
  customFieldsTitle: {
    fontSize: '13px',
    fontWeight: 600,
    color: '#666',
    marginBottom: '12px',
    textTransform: 'uppercase',
  },
  customFieldContainer: {
    marginBottom: '12px',
  },
  customValueBadge: {
    backgroundColor: '#e3f2fd',
    color: '#1976d2',
    padding: '2px 8px',
    borderRadius: '4px',
    fontSize: '11px',
    maxWidth: '150px',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  },
  columnMenuContainer: {
    position: 'relative',
  },
  columnMenuButton: {
    padding: '10px 16px',
    backgroundColor: '#f5f5f5',
    color: '#333',
    border: '1px solid #ddd',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    display: 'flex',
    alignItems: 'center',
    gap: '6px',
    minHeight: '44px',
  },
  columnMenuDropdown: {
    position: 'absolute',
    top: '100%',
    right: 0,
    marginTop: '4px',
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
    border: '1px solid #e0e0e0',
    minWidth: '200px',
    zIndex: 100,
    overflow: 'hidden',
  },
  columnMenuHeader: {
    padding: '12px 16px',
    fontSize: '12px',
    fontWeight: 600,
    color: '#666',
    textTransform: 'uppercase',
    borderBottom: '1px solid #eee',
    backgroundColor: '#fafafa',
  },
  columnMenuItem: {
    display: 'flex',
    alignItems: 'center',
    padding: '12px 16px',
    cursor: 'pointer',
    transition: 'background-color 0.15s',
    gap: '10px',
    minHeight: '44px',
  },
  columnCheckbox: {
    width: '18px',
    height: '18px',
    cursor: 'pointer',
  },
  columnLabel: {
    fontSize: '14px',
    color: '#333',
  },
  columnMenuEmpty: {
    padding: '16px',
    textAlign: 'center',
    color: '#888',
    fontSize: '13px',
  },
  visuallyHidden: {
    position: 'absolute',
    width: '1px',
    height: '1px',
    padding: 0,
    margin: '-1px',
    overflow: 'hidden',
    clip: 'rect(0, 0, 0, 0)',
    whiteSpace: 'nowrap',
    border: 0,
  },
}
