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}`
  }

  return (
    <DragDropContext onDragEnd={handleDragEnd}>
      <Droppable droppableId="waypoints">
        {(provided) => (
          <div ref={provided.innerRef} {...provided.droppableProps} className="space-y-0.5">
            {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 justify-between bg-az-bg rounded px-1.5 py-1 text-[10px] text-az-text group">
                    <span>
                      <span className="text-az-orange font-bold mr-1">
                        {String(index + 1).padStart(2, '0')}
                      </span>
                      {formatInfo(calculatedPointInfo[index], point.altitude)}
                    </span>
                    <span className="flex gap-1 opacity-0 group-hover:opacity-100">
                      <button onClick={() => onEdit(point)} className="hover:text-az-orange">&#9998;</button>
                      <button onClick={() => onRemove(point.id)} className="hover:text-az-red">&#215;</button>
                    </span>
                  </div>
                )}
              </Draggable>
            ))}
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    </DragDropContext>
  )
}
