import { DragDropContext, Droppable, Draggable, type DropResult } from '@hello-pangea/dnd'
import { useTranslation } from 'react-i18next'
import type { FlightPoint, CalculatedPointInfo } from './types'

interface Props {
  points: FlightPoint[]
  calculatedPointInfo: CalculatedPointInfo[]
  onReorder: (points: FlightPoint[]) => void
  onEdit: (point: FlightPoint) => void
  onRemove: (id: string) => void
}

export default function WaypointList({ points, calculatedPointInfo, onReorder, onEdit, onRemove }: Props) {
  const { t } = useTranslation()

  const handleDragEnd = (result: DropResult) => {
    if (!result.destination) return
    const items = Array.from(points)
    const [moved] = items.splice(result.source.index, 1)
    items.splice(result.destination.index, 0, moved)
    onReorder(items)
  }

  const formatInfo = (info: CalculatedPointInfo | undefined, alt: number) => {
    if (!info) return `${alt}${t('flights.planner.metres')}`
    const hours = Math.floor(info.time)
    const mins = Math.floor((info.time - hours) * 60)
    const timeStr = hours >= 1 ? `${hours}${t('flights.planner.hour')}${mins}${t('flights.planner.minutes')}` : `${mins}${t('flights.planner.minutes')}`
    return `${alt}${t('flights.planner.metres')} ${Math.floor(info.bat)}%${t('flights.planner.battery')} ${timeStr}`
  }

  const renderMarker = (index: number) => {
    if (index === 0) {
      return (
        <span
          style={{
            width: 10,
            height: 10,
            background: 'var(--accent-green)',
            transform: 'rotate(45deg)',
            flexShrink: 0,
            display: 'inline-block',
          }}
        />
      )
    }
    if (index === points.length - 1 && points.length > 1) {
      return (
        <span
          style={{
            width: 10,
            height: 10,
            background: 'var(--accent-red)',
            clipPath: 'polygon(30% 0,70% 0,100% 30%,100% 70%,70% 100%,30% 100%,0 70%,0 30%)',
            flexShrink: 0,
            display: 'inline-block',
          }}
        />
      )
    }
    return (
      <span
        style={{
          width: 10,
          height: 10,
          background: 'transparent',
          border: '1.5px solid var(--accent-cyan)',
          flexShrink: 0,
          display: 'inline-block',
        }}
      />
    )
  }

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="waypoints">
        {(provided) => (
          <div ref={provided.innerRef} {...provided.droppableProps} className="space-y-0">
            {points.map((point, index) => (
              <Draggable key={point.id} draggableId={point.id} index={index}>
                {(provided) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                    className="flex items-center gap-2.5 border-b border-border-hair mono group"
                    style={{ height: 30, padding: '0 4px', ...provided.draggableProps.style }}
                  >
                    <span
                      className="mono text-[11px]"
                      style={{ color: 'var(--text-secondary)', width: 28, flexShrink: 0 }}
                    >
                      {String(index + 1).padStart(2, '0')}
                    </span>

                    {renderMarker(index)}

                    <span className="text-[11px] text-text-primary truncate flex-1">
                      {formatInfo(calculatedPointInfo[index], point.altitude)}
                    </span>

                    <span className="ml-auto flex gap-1 opacity-0 group-hover:opacity-100">
                      <button
                        onClick={() => onEdit(point)}
                        className="ibtn edit"
                        style={{ width: 22, height: 22 }}
                        title={t('flights.planner.edit')}
                      >
                        &#9998;
                      </button>
                      <button
                        onClick={() => onRemove(point.id)}
                        className="ibtn danger"
                        style={{ width: 22, height: 22 }}
                        title={t('flights.planner.remove')}
                      >
                        &#215;
                      </button>
                    </span>
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  )
}
