import { useState, useEffect, useCallback, useRef } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
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'

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
  custom_values?: CustomValueResponse[]
}

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'

// 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 { 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 [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: '',
    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)

  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) {
      console.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,
          }
          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) {
      console.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.due_date) {
        payload.due_date = newTask.due_date
      }
      if (newTask.time_estimate) {
        payload.time_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: '',
        due_date: '',
        time_estimate: '',
      })
      setNewTaskCustomValues({})
      setSelectedAssignee(null)
      loadData()
    } catch (err) {
      console.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)
      console.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 = () => {
    loadData()
  }

  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) {
      console.error('Failed to load subtask:', err)
    }
  }

  const getPriorityStyle = (priority: string): React.CSSProperties => {
    const colors: { [key: string]: string } = {
      low: '#808080',
      medium: '#0066cc',
      high: '#ff9800',
      urgent: '#f44336',
    }
    return {
      width: '4px',
      backgroundColor: colors[priority] || colors.medium,
      borderRadius: '2px',
    }
  }

  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={styles.container}>
      <div style={styles.breadcrumb}>
        <span onClick={() => navigate('/spaces')} style={styles.breadcrumbLink}>
          Spaces
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span
          onClick={() => navigate(`/spaces/${project?.space_id}`)}
          style={styles.breadcrumbLink}
        >
          Projects
        </span>
        <span style={styles.breadcrumbSeparator}>/</span>
        <span>{project?.title}</span>
      </div>

      <div style={styles.header}>
        <div style={styles.titleContainer}>
          <h1 style={styles.title}>Tasks</h1>
          {isConnected ? (
            <span style={styles.liveIndicator} title="Real-time sync active">
              ● Live
            </span>
          ) : projectId ? (
            <span style={styles.offlineIndicator} title="Real-time sync disconnected. Changes may not appear automatically.">
              ○ Offline
            </span>
          ) : null}
        </div>
        <div style={styles.headerActions}>
          {/* View Toggle */}
          <div style={styles.viewToggle}>
            <button
              onClick={() => setViewMode('list')}
              style={{
                ...styles.viewButton,
                ...(viewMode === 'list' ? styles.viewButtonActive : {}),
              }}
              aria-label="List view"
            >
              List
            </button>
            <button
              onClick={() => setViewMode('kanban')}
              style={{
                ...styles.viewButton,
                ...(viewMode === 'kanban' ? styles.viewButtonActive : {}),
              }}
              aria-label="Kanban view"
            >
              Kanban
            </button>
            <button
              onClick={() => setViewMode('calendar')}
              style={{
                ...styles.viewButton,
                ...(viewMode === 'calendar' ? styles.viewButtonActive : {}),
              }}
              aria-label="Calendar view"
            >
              Calendar
            </button>
            <button
              onClick={() => setViewMode('gantt')}
              style={{
                ...styles.viewButton,
                ...(viewMode === 'gantt' ? styles.viewButtonActive : {}),
              }}
              aria-label="Gantt view"
            >
              Gantt
            </button>
          </div>
          {/* Column Visibility Toggle - only show when there are custom fields and in list view */}
          {viewMode === 'list' && customFields.length > 0 && (
            <div style={styles.columnMenuContainer} ref={columnMenuRef}>
              <button
                onClick={() => setShowColumnMenu(!showColumnMenu)}
                style={styles.columnMenuButton}
                aria-label="Toggle columns"
              >
                Columns
              </button>
              {showColumnMenu && (
                <div style={styles.columnMenuDropdown}>
                  <div style={styles.columnMenuHeader}>Show Custom Fields</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}>No custom fields</div>
                  )}
                </div>
              )}
            </div>
          )}
          <button
            onClick={() => navigate(`/projects/${projectId}/settings`)}
            style={styles.settingsButton}
            aria-label="Project settings"
          >
            Settings
          </button>
          <button onClick={() => setShowCreateModal(true)} style={styles.createButton}>
            + New Task
          </button>
        </div>
      </div>

      {/* Conditional rendering based on view mode */}
      {viewMode === 'list' && (
        <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}>
                      Due: {new Date(task.due_date).toLocaleDateString()}
                    </span>
                  )}
                  {task.time_estimate && (
                    <span style={styles.timeEstimate}>
                      Est: {task.time_estimate}h
                    </span>
                  )}
                  {task.subtask_count > 0 && (
                    <span style={styles.subtaskCount}>
                      {task.subtask_count} subtasks
                    </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>No tasks yet. Create your first task!</p>
            </div>
          )}
        </div>
      )}

      {viewMode === 'kanban' && (
        <KanbanBoard
          tasks={tasks}
          statuses={statuses}
          onStatusChange={handleStatusChange}
          onTaskClick={handleTaskClick}
        />
      )}

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

      {viewMode === 'gantt' && projectId && (
        <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={styles.modal}>
            <h2 id="create-task-title" style={styles.modalTitle}>Create New Task</h2>
            <label htmlFor="task-title" style={styles.visuallyHidden}>
              Task title
            </label>
            <input
              id="task-title"
              type="text"
              placeholder="Task title"
              value={newTask.title}
              onChange={(e) => setNewTask({ ...newTask, title: e.target.value })}
              style={styles.input}
              autoFocus
            />
            <label htmlFor="task-description" style={styles.visuallyHidden}>
              Description
            </label>
            <textarea
              id="task-description"
              placeholder="Description (optional)"
              value={newTask.description}
              onChange={(e) => setNewTask({ ...newTask, description: e.target.value })}
              style={styles.textarea}
            />

            <label style={styles.label}>Priority</label>
            <select
              value={newTask.priority}
              onChange={(e) => setNewTask({ ...newTask, priority: e.target.value })}
              style={styles.select}
            >
              <option value="low">Low</option>
              <option value="medium">Medium</option>
              <option value="high">High</option>
              <option value="urgent">Urgent</option>
            </select>

            <label style={styles.label}>Assignee</label>
            <UserSelect
              value={newTask.assignee_id}
              onChange={handleAssigneeChange}
              placeholder="Select assignee..."
            />
            <div style={styles.fieldSpacer} />

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

            <label style={styles.label}>Time Estimate (hours)</label>
            <input
              type="number"
              min="0"
              step="0.5"
              placeholder="e.g., 2.5"
              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}>Custom Fields</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}>
                Cancel
              </button>
              <button
                onClick={handleCreateTask}
                disabled={creating || !newTask.title.trim()}
                style={styles.submitButton}
              >
                {creating ? 'Creating...' : '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',
  },
  breadcrumb: {
    marginBottom: '16px',
    fontSize: '14px',
    color: '#666',
  },
  breadcrumbLink: {
    color: '#0066cc',
    cursor: 'pointer',
  },
  breadcrumbSeparator: {
    margin: '0 8px',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: '24px',
  },
  titleContainer: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
  },
  title: {
    fontSize: '24px',
    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',
  },
  viewToggle: {
    display: 'flex',
    border: '1px solid #ddd',
    borderRadius: '6px',
    overflow: 'hidden',
  },
  viewButton: {
    padding: '8px 16px',
    backgroundColor: 'white',
    border: 'none',
    cursor: 'pointer',
    fontSize: '14px',
    color: '#666',
    transition: 'background-color 0.2s, color 0.2s',
  },
  viewButtonActive: {
    backgroundColor: '#0066cc',
    color: 'white',
  },
  settingsButton: {
    padding: '10px 16px',
    backgroundColor: '#f5f5f5',
    color: '#333',
    border: '1px solid #ddd',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  createButton: {
    padding: '10px 20px',
    backgroundColor: '#0066cc',
    color: 'white',
    border: 'none',
    borderRadius: '6px',
    cursor: 'pointer',
    fontSize: '14px',
    fontWeight: 500,
  },
  taskList: {
    backgroundColor: 'white',
    borderRadius: '8px',
    boxShadow: '0 1px 3px rgba(0, 0, 0, 0.1)',
    overflow: 'hidden',
  },
  taskRow: {
    display: 'flex',
    alignItems: 'center',
    padding: '16px',
    borderBottom: '1px solid #eee',
    gap: '12px',
    cursor: 'pointer',
    transition: 'background-color 0.15s ease',
  },
  taskContent: {
    flex: 1,
  },
  taskTitle: {
    fontSize: '14px',
    fontWeight: 500,
    marginBottom: '4px',
  },
  taskMeta: {
    display: 'flex',
    gap: '12px',
    fontSize: '12px',
    color: '#666',
  },
  assignee: {
    backgroundColor: '#f0f0f0',
    padding: '2px 6px',
    borderRadius: '4px',
  },
  dueDate: {},
  timeEstimate: {
    color: '#0066cc',
  },
  subtaskCount: {
    color: '#767676', // WCAG AA compliant
  },
  statusSelect: {
    padding: '6px 12px',
    border: 'none',
    borderRadius: '4px',
    fontSize: '12px',
    cursor: 'pointer',
    color: 'white',
  },
  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,
  },
  modal: {
    backgroundColor: 'white',
    padding: '24px',
    borderRadius: '8px',
    width: '450px',
    maxWidth: '90%',
    maxHeight: '90vh',
    overflowY: 'auto',
  },
  modalTitle: {
    marginBottom: '16px',
  },
  input: {
    width: '100%',
    padding: '10px',
    marginBottom: '12px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  textarea: {
    width: '100%',
    padding: '10px',
    marginBottom: '12px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    minHeight: '80px',
    resize: 'vertical',
    boxSizing: 'border-box',
  },
  label: {
    display: 'block',
    marginBottom: '4px',
    fontSize: '14px',
    fontWeight: 500,
  },
  select: {
    width: '100%',
    padding: '10px',
    marginBottom: '12px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  fieldSpacer: {
    height: '12px',
  },
  modalActions: {
    display: 'flex',
    justifyContent: 'flex-end',
    gap: '12px',
    marginTop: '16px',
  },
  cancelButton: {
    padding: '10px 20px',
    backgroundColor: '#f5f5f5',
    border: '1px solid #ddd',
    borderRadius: '4px',
    cursor: 'pointer',
  },
  submitButton: {
    padding: '10px 20px',
    backgroundColor: '#0066cc',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
  },
  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',
  },
  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: '10px 16px',
    cursor: 'pointer',
    transition: 'background-color 0.15s',
    gap: '10px',
  },
  columnCheckbox: {
    width: '16px',
    height: '16px',
    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,
  },
}
