'use client'

import { useState } from 'react'
import { Delivery, Driver } from '@/lib/types'
import { calcDistance } from '@/lib/algorithm'
import AddressPickerModal from './AddressPickerModal'

interface Props {
  deliveries: Delivery[]
  currentTarget: Delivery | null
  driver: Driver
  onDelete: (id: string) => void
  onEdit: (id: string, updated: { recipient: string; address: string; lat: number; lng: number }) => void
}

export default function DeliveryList({ deliveries, currentTarget, driver, onDelete, onEdit }: Props) {
  const [isCollapsed, setIsCollapsed] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editRecipient, setEditRecipient] = useState('')
  const [showMapPicker, setShowMapPicker] = useState(false)
  const [editLocation, setEditLocation] = useState<{ address: string; lat: number; lng: number } | null>(null)

  const sorted = [...deliveries].sort((a, b) => {
    if (a.status === 'in-progress') return -1
    if (b.status === 'in-progress') return 1
    if (a.status === 'completed' && b.status !== 'completed') return 1
    if (b.status === 'completed' && a.status !== 'completed') return -1
    if (a.status === 'completed' && b.status === 'completed') {
      return (a.completedAt ?? 0) - (b.completedAt ?? 0)
    }
    return calcDistance(driver, a) - calcDistance(driver, b)
  })

  const startEdit = (delivery: Delivery) => {
    if (delivery.status === 'completed') return
    setEditingId(delivery.id)
    setEditRecipient(delivery.recipient)
    setEditLocation({
      address: delivery.address,
      lat: delivery.lat,
      lng: delivery.lng,
    })
  }

  const cancelEdit = () => {
    setEditingId(null)
    setEditRecipient('')
    setEditLocation(null)
    setShowMapPicker(false)
  }

  const saveEdit = () => {
    if (editingId && editRecipient && editLocation) {
      onEdit(editingId, {
        recipient: editRecipient,
        address: editLocation.address,
        lat: editLocation.lat,
        lng: editLocation.lng,
      })
      cancelEdit()
    }
  }

  const handleLocationConfirm = (address: string, lat: number, lng: number) => {
    setEditLocation({ address, lat, lng })
    setShowMapPicker(false)
  }

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 flex flex-col h-full">
      <div
        className="px-3 py-2 sm:px-4 sm:py-3 border-b border-gray-700 cursor-pointer select-none hover:bg-gray-750 transition-colors"
        onClick={() => setIsCollapsed(!isCollapsed)}
      >
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-sm font-semibold text-gray-200">Daftar Pengantaran</h2>
            <p className="text-xs text-gray-400 mt-0.5">
              {deliveries.filter((d) => d.status === 'completed').length} / {deliveries.length} selesai
            </p>
          </div>
          <button
            className="text-gray-400 hover:text-gray-200 text-lg transition-colors"
            aria-label={isCollapsed ? "Expand list" : "Collapse list"}
          >
            {isCollapsed ? '▼' : '▲'}
          </button>
        </div>
      </div>

      {!isCollapsed && (
        <div className="overflow-y-auto flex-1 divide-y divide-gray-700">
          {sorted.map((delivery) => {
            const isTarget = currentTarget?.id === delivery.id
            const isCompleted = delivery.status === 'completed'
            const isEditing = editingId === delivery.id
            const dist = calcDistance(driver, delivery)

            if (isEditing && editLocation) {
              return (
                <div
                  key={delivery.id}
                  className="px-3 py-3 sm:px-4 sm:py-3 bg-blue-950/30 border-l-2 border-blue-400"
                >
                  <div className="space-y-2">
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Nama Penerima</label>
                      <input
                        type="text"
                        value={editRecipient}
                        onChange={(e) => setEditRecipient(e.target.value)}
                        className="w-full px-2 py-1.5 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                      />
                    </div>
                    <div>
                      <label className="block text-xs text-gray-400 mb-1">Lokasi</label>
                      <button
                        type="button"
                        onClick={() => setShowMapPicker(true)}
                        className="w-full px-2 py-1.5 bg-gray-900 border border-gray-700 rounded-lg text-white text-sm hover:border-blue-500 transition-colors text-left"
                      >
                        <span className="text-xs">📍 {editLocation.address.substring(0, 50)}...</span>
                      </button>
                    </div>
                    <div className="flex gap-2 pt-1">
                      <button
                        onClick={cancelEdit}
                        className="flex-1 px-2 py-1.5 bg-gray-700 hover:bg-gray-600 text-white rounded-lg transition-colors text-xs"
                      >
                        Batal
                      </button>
                      <button
                        onClick={saveEdit}
                        className="flex-1 px-2 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors text-xs font-semibold"
                      >
                        Simpan
                      </button>
                    </div>
                  </div>
                </div>
              )
            }

            return (
              <div
                key={delivery.id}
                className={`px-3 py-2 sm:px-4 sm:py-3 transition-colors ${
                  isTarget
                    ? 'bg-yellow-950/40 border-l-2 border-yellow-400'
                    : isCompleted
                    ? 'opacity-50'
                    : 'hover:bg-gray-700/30'
                }`}
              >
                <div className="flex items-start gap-3">
                  {/* Status badge */}
                  <div
                    className={`mt-0.5 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold shrink-0 ${
                      isCompleted
                        ? 'bg-green-700 text-green-200'
                        : isTarget
                        ? 'bg-yellow-400 text-black'
                        : 'bg-red-800 text-red-200'
                    }`}
                  >
                    {isCompleted ? '✓' : delivery.id}
                  </div>

                  <div className="flex-1 min-w-0">
                    <div className="flex items-center justify-between gap-2">
                      <span
                        className={`text-sm font-medium truncate ${
                          isCompleted ? 'text-gray-400 line-through' : isTarget ? 'text-yellow-300' : 'text-gray-200'
                        }`}
                      >
                        {delivery.recipient}
                      </span>
                      {isTarget && (
                        <span className="text-xs bg-yellow-400 text-black px-2 py-0.5 rounded-full font-semibold shrink-0">
                          Berikutnya
                        </span>
                      )}
                    </div>
                    <p className="text-xs text-gray-400 truncate mt-0.5">{delivery.address}</p>
                    {!isCompleted && (
                      <p className={`text-xs mt-1 ${isTarget ? 'text-yellow-400' : 'text-gray-500'}`}>
                        Jarak: {dist.toFixed(2)} km
                      </p>
                    )}
                    {isCompleted && delivery.completedAt !== undefined && (
                      <p className="text-xs text-green-600 mt-1">Urutan ke-{delivery.completedAt}</p>
                    )}

                    {/* Edit and Delete buttons - only for non-completed */}
                    {!isCompleted && (
                      <div className="flex gap-2 mt-2">
                        <button
                          onClick={() => startEdit(delivery)}
                          className="text-xs text-blue-400 hover:text-blue-300 transition-colors flex items-center gap-1"
                        >
                          <span>✏️</span>
                          <span>Edit</span>
                        </button>
                        <button
                          onClick={() => onDelete(delivery.id)}
                          className="text-xs text-red-400 hover:text-red-300 transition-colors flex items-center gap-1"
                        >
                          <span>🗑️</span>
                          <span>Hapus</span>
                        </button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            )
          })}
        </div>
      )}

      <AddressPickerModal
        isOpen={showMapPicker}
        onClose={() => setShowMapPicker(false)}
        onConfirm={handleLocationConfirm}
      />
    </div>
  )
}
