import { useState, useEffect, useCallback, useRef } from 'react'
import api from '../services/api'
import { Comments } from './Comments'
import { TaskAttachments } from './TaskAttachments'
import { SubtaskList } from './SubtaskList'
import { UserSelect } from './UserSelect'
import { UserSearchResult } from '../services/collaboration'
import { customFieldsApi, CustomField, CustomValueResponse } from '../services/customFields'
import { CustomFieldInput } from './CustomFieldInput'
import { SkeletonList } from './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
  time_estimate: number | null
  subtask_count: number
  custom_values?: CustomValueResponse[]
}

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

interface TaskDetailModalProps {
  task: Task
  statuses: TaskStatus[]
  isOpen: boolean
  onClose: () => void
  onUpdate: () => void
  onSubtaskClick?: (subtaskId: string) => void
}

export function TaskDetailModal({
  task,
  statuses,
  isOpen,
  onClose,
  onUpdate,
  onSubtaskClick,
}: TaskDetailModalProps) {
  const [isEditing, setIsEditing] = useState(false)
  const [saving, setSaving] = useState(false)
  const [editForm, setEditForm] = useState({
    title: task.title,
    description: task.description || '',
    priority: task.priority,
    status_id: task.status_id || '',
    assignee_id: task.assignee_id || '',
    due_date: task.due_date ? task.due_date.split('T')[0] : '',
    time_estimate: task.time_estimate || '',
  })
  const [, setSelectedAssignee] = useState<UserSearchResult | null>(
    task.assignee_id && task.assignee_name
      ? { id: task.assignee_id, name: task.assignee_name, email: '' }
      : null
  )

  // Custom fields state
  const [customFields, setCustomFields] = useState<CustomField[]>([])
  const [customValues, setCustomValues] = useState<CustomValueResponse[]>([])
  const [editCustomValues, setEditCustomValues] = useState<Record<string, string | number | null>>({})
  const [loadingCustomFields, setLoadingCustomFields] = useState(false)

  const loadCustomFields = useCallback(async () => {
    setLoadingCustomFields(true)
    try {
      const response = await customFieldsApi.getCustomFields(task.project_id)
      setCustomFields(response.fields)
    } catch (err) {
      console.error('Failed to load custom fields:', err)
    } finally {
      setLoadingCustomFields(false)
    }
  }, [task.project_id])

  // Load custom fields for the project
  useEffect(() => {
    if (task.project_id) {
      loadCustomFields()
    }
  }, [task.project_id, loadCustomFields])

  // Initialize custom values from task
  useEffect(() => {
    setCustomValues(task.custom_values || [])
    // Build edit values map
    const valuesMap: Record<string, string | number | null> = {}
    if (task.custom_values) {
      task.custom_values.forEach((cv) => {
        valuesMap[cv.field_id] = cv.value
      })
    }
    setEditCustomValues(valuesMap)
  }, [task.custom_values])

  // Reset form when task changes
  useEffect(() => {
    setEditForm({
      title: task.title,
      description: task.description || '',
      priority: task.priority,
      status_id: task.status_id || '',
      assignee_id: task.assignee_id || '',
      due_date: task.due_date ? task.due_date.split('T')[0] : '',
      time_estimate: task.time_estimate || '',
    })
    setSelectedAssignee(
      task.assignee_id && task.assignee_name
        ? { id: task.assignee_id, name: task.assignee_name, email: '' }
        : null
    )
    setIsEditing(false)
  }, [task])

  // Reference to the modal overlay for focus management
  const overlayRef = useRef<HTMLDivElement>(null)

  // Handle Escape key to close modal
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && isOpen) {
        onClose()
      }
    }

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

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

  if (!isOpen) return null

  const handleSave = async () => {
    setSaving(true)
    try {
      const payload: Record<string, unknown> = {
        title: editForm.title,
        description: editForm.description || null,
        priority: editForm.priority,
      }

      if (editForm.status_id) {
        payload.status_id = editForm.status_id
      }
      if (editForm.assignee_id) {
        payload.assignee_id = editForm.assignee_id
      } else {
        payload.assignee_id = null
      }
      if (editForm.due_date) {
        payload.due_date = editForm.due_date
      } else {
        payload.due_date = null
      }
      if (editForm.time_estimate) {
        payload.time_estimate = Number(editForm.time_estimate)
      } else {
        payload.time_estimate = null
      }

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

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

      await api.patch(`/tasks/${task.id}`, payload)
      setIsEditing(false)
      onUpdate()
    } catch (err) {
      console.error('Failed to update task:', err)
    } finally {
      setSaving(false)
    }
  }

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

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

  const handleOverlayClick = (e: React.MouseEvent) => {
    if (e.target === e.currentTarget) {
      onClose()
    }
  }

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

  return (
    <div
      ref={overlayRef}
      style={styles.overlay}
      onClick={handleOverlayClick}
      tabIndex={-1}
      role="dialog"
      aria-modal="true"
      aria-labelledby="task-detail-title"
    >
      <div style={styles.modal}>
        <div style={styles.header}>
          <div style={styles.headerLeft}>
            <div
              style={{
                ...styles.priorityIndicator,
                backgroundColor: getPriorityColor(task.priority),
              }}
            />
            {isEditing ? (
              <input
                type="text"
                value={editForm.title}
                onChange={(e) => setEditForm({ ...editForm, title: e.target.value })}
                style={styles.titleInput}
                autoFocus
              />
            ) : (
              <h2 id="task-detail-title" style={styles.title}>{task.title}</h2>
            )}
          </div>
          <div style={styles.headerActions}>
            {!isEditing ? (
              <button onClick={() => setIsEditing(true)} style={styles.editButton}>
                Edit
              </button>
            ) : (
              <>
                <button
                  onClick={() => setIsEditing(false)}
                  style={styles.cancelButton}
                  disabled={saving}
                >
                  Cancel
                </button>
                <button
                  onClick={handleSave}
                  style={styles.saveButton}
                  disabled={saving || !editForm.title.trim()}
                >
                  {saving ? 'Saving...' : 'Save'}
                </button>
              </>
            )}
            <button onClick={onClose} style={styles.closeButton} aria-label="Close">
              X
            </button>
          </div>
        </div>

        <div style={styles.content}>
          <div style={styles.mainSection}>
            {/* Description */}
            <div style={styles.field}>
              <label style={styles.fieldLabel}>Description</label>
              {isEditing ? (
                <textarea
                  value={editForm.description}
                  onChange={(e) =>
                    setEditForm({ ...editForm, description: e.target.value })
                  }
                  style={styles.textarea}
                  placeholder="Add a description..."
                />
              ) : (
                <div style={styles.descriptionText}>
                  {task.description || 'No description'}
                </div>
              )}
            </div>

            {/* Comments Section */}
            <div style={styles.section}>
              <Comments taskId={task.id} />
            </div>

            {/* Attachments Section */}
            <div style={styles.section}>
              <TaskAttachments taskId={task.id} />
            </div>

            {/* Subtasks Section */}
            <div style={styles.section}>
              <SubtaskList
                taskId={task.id}
                projectId={task.project_id}
                onSubtaskClick={onSubtaskClick}
                onSubtaskCreated={onUpdate}
              />
            </div>
          </div>

          <div style={styles.sidebar}>
            {/* Status */}
            <div style={styles.sidebarField}>
              <label style={styles.sidebarLabel}>Status</label>
              {isEditing ? (
                <select
                  value={editForm.status_id}
                  onChange={(e) =>
                    setEditForm({ ...editForm, status_id: e.target.value })
                  }
                  style={styles.select}
                >
                  <option value="">No Status</option>
                  {statuses.map((status) => (
                    <option key={status.id} value={status.id}>
                      {status.name}
                    </option>
                  ))}
                </select>
              ) : (
                <div
                  style={{
                    ...styles.statusBadge,
                    backgroundColor: task.status_color || '#e0e0e0',
                  }}
                >
                  {task.status_name || 'No Status'}
                </div>
              )}
            </div>

            {/* Priority */}
            <div style={styles.sidebarField}>
              <label style={styles.sidebarLabel}>Priority</label>
              {isEditing ? (
                <select
                  value={editForm.priority}
                  onChange={(e) =>
                    setEditForm({ ...editForm, 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>
              ) : (
                <div
                  style={{
                    ...styles.priorityBadge,
                    borderColor: getPriorityColor(task.priority),
                    color: getPriorityColor(task.priority),
                  }}
                >
                  {task.priority.charAt(0).toUpperCase() + task.priority.slice(1)}
                </div>
              )}
            </div>

            {/* Assignee */}
            <div style={styles.sidebarField}>
              <label style={styles.sidebarLabel}>Assignee</label>
              {isEditing ? (
                <UserSelect
                  value={editForm.assignee_id}
                  onChange={handleAssigneeChange}
                  placeholder="Select assignee..."
                />
              ) : (
                <div style={styles.assigneeDisplay}>
                  {task.assignee_name || 'Unassigned'}
                </div>
              )}
            </div>

            {/* Due Date */}
            <div style={styles.sidebarField}>
              <label style={styles.sidebarLabel}>Due Date</label>
              {isEditing ? (
                <input
                  type="date"
                  value={editForm.due_date}
                  onChange={(e) =>
                    setEditForm({ ...editForm, due_date: e.target.value })
                  }
                  style={styles.dateInput}
                />
              ) : (
                <div style={styles.dueDateDisplay}>
                  {task.due_date
                    ? new Date(task.due_date).toLocaleDateString()
                    : 'No due date'}
                </div>
              )}
            </div>

            {/* Time Estimate */}
            <div style={styles.sidebarField}>
              <label style={styles.sidebarLabel}>Time Estimate (hours)</label>
              {isEditing ? (
                <input
                  type="number"
                  min="0"
                  step="0.5"
                  value={editForm.time_estimate}
                  onChange={(e) =>
                    setEditForm({ ...editForm, time_estimate: e.target.value })
                  }
                  style={styles.numberInput}
                  placeholder="e.g., 2.5"
                />
              ) : (
                <div style={styles.timeEstimateDisplay}>
                  {task.time_estimate ? `${task.time_estimate} hours` : 'Not estimated'}
                </div>
              )}
            </div>

            {/* Subtasks Info */}
            {task.subtask_count > 0 && (
              <div style={styles.sidebarField}>
                <label style={styles.sidebarLabel}>Subtasks</label>
                <div style={styles.subtaskInfo}>{task.subtask_count} subtask(s)</div>
              </div>
            )}

            {/* Custom Fields Section */}
            {customFields.length > 0 && (
              <>
                <div style={styles.customFieldsDivider} />
                <div style={styles.customFieldsHeader}>Custom Fields</div>
                {loadingCustomFields ? (
                  <SkeletonList count={3} showAvatar={false} />
                ) : (
                  customFields.map((field) => {
                    // Get the value for this field
                    const valueResponse = customValues.find(
                      (v) => v.field_id === field.id
                    ) || {
                      field_id: field.id,
                      field_name: field.name,
                      field_type: field.field_type,
                      value: editCustomValues[field.id] ?? null,
                      display_value: null,
                    }

                    // For editing mode, create a modified value response with edit values
                    const displayValue = isEditing
                      ? {
                          ...valueResponse,
                          value: editCustomValues[field.id] ?? valueResponse.value,
                        }
                      : valueResponse

                    return (
                      <div key={field.id} style={styles.sidebarField}>
                        <CustomFieldInput
                          field={field}
                          value={displayValue}
                          onChange={handleCustomFieldChange}
                          disabled={!isEditing || field.field_type === 'formula'}
                          showLabel={true}
                        />
                      </div>
                    )
                  })
                )}
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

const styles: Record<string, React.CSSProperties> = {
  overlay: {
    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',
    borderRadius: '12px',
    width: '90%',
    maxWidth: '900px',
    maxHeight: '90vh',
    overflow: 'hidden',
    display: 'flex',
    flexDirection: 'column',
    boxShadow: '0 8px 32px rgba(0, 0, 0, 0.2)',
  },
  header: {
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    padding: '20px 24px',
    borderBottom: '1px solid #eee',
  },
  headerLeft: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
    flex: 1,
  },
  priorityIndicator: {
    width: '6px',
    height: '32px',
    borderRadius: '3px',
  },
  title: {
    margin: 0,
    fontSize: '20px',
    fontWeight: 600,
  },
  titleInput: {
    fontSize: '20px',
    fontWeight: 600,
    border: '1px solid #ddd',
    borderRadius: '4px',
    padding: '8px 12px',
    flex: 1,
    marginRight: '12px',
  },
  headerActions: {
    display: 'flex',
    gap: '8px',
    alignItems: 'center',
  },
  editButton: {
    padding: '8px 16px',
    backgroundColor: '#f5f5f5',
    border: '1px solid #ddd',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  saveButton: {
    padding: '8px 16px',
    backgroundColor: '#0066cc',
    color: 'white',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  cancelButton: {
    padding: '8px 16px',
    backgroundColor: '#f5f5f5',
    border: '1px solid #ddd',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '14px',
  },
  closeButton: {
    width: '32px',
    height: '32px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
    border: 'none',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '16px',
    color: '#666',
    marginLeft: '8px',
  },
  content: {
    display: 'flex',
    flex: 1,
    overflow: 'hidden',
  },
  mainSection: {
    flex: 1,
    padding: '24px',
    overflowY: 'auto',
    borderRight: '1px solid #eee',
  },
  sidebar: {
    width: '280px',
    padding: '24px',
    backgroundColor: '#fafafa',
    overflowY: 'auto',
  },
  field: {
    marginBottom: '24px',
  },
  fieldLabel: {
    display: 'block',
    fontSize: '12px',
    fontWeight: 600,
    color: '#666',
    marginBottom: '8px',
    textTransform: 'uppercase',
  },
  textarea: {
    width: '100%',
    minHeight: '100px',
    padding: '12px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    resize: 'vertical',
    boxSizing: 'border-box',
  },
  descriptionText: {
    fontSize: '14px',
    lineHeight: 1.6,
    color: '#333',
    whiteSpace: 'pre-wrap',
  },
  section: {
    marginBottom: '24px',
  },
  sidebarField: {
    marginBottom: '20px',
  },
  sidebarLabel: {
    display: 'block',
    fontSize: '11px',
    fontWeight: 600,
    color: '#888',
    marginBottom: '6px',
    textTransform: 'uppercase',
  },
  select: {
    width: '100%',
    padding: '10px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    boxSizing: 'border-box',
    backgroundColor: 'white',
  },
  statusBadge: {
    display: 'inline-block',
    padding: '6px 12px',
    borderRadius: '4px',
    fontSize: '13px',
    fontWeight: 500,
    color: 'white',
  },
  priorityBadge: {
    display: 'inline-block',
    padding: '6px 12px',
    border: '2px solid',
    borderRadius: '4px',
    fontSize: '13px',
    fontWeight: 500,
  },
  assigneeDisplay: {
    fontSize: '14px',
    color: '#333',
  },
  dueDateDisplay: {
    fontSize: '14px',
    color: '#333',
  },
  timeEstimateDisplay: {
    fontSize: '14px',
    color: '#333',
  },
  subtaskInfo: {
    fontSize: '14px',
    color: '#666',
  },
  dateInput: {
    width: '100%',
    padding: '10px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  numberInput: {
    width: '100%',
    padding: '10px',
    border: '1px solid #ddd',
    borderRadius: '4px',
    fontSize: '14px',
    boxSizing: 'border-box',
  },
  customFieldsDivider: {
    height: '1px',
    backgroundColor: '#ddd',
    margin: '20px 0',
  },
  customFieldsHeader: {
    fontSize: '12px',
    fontWeight: 600,
    color: '#666',
    marginBottom: '16px',
    textTransform: 'uppercase',
  },
  loadingText: {
    fontSize: '13px',
    color: '#888',
    fontStyle: 'italic',
  },
}

export default TaskDetailModal
