import React from 'react';
import {
  MdTwoWheeler,
  MdLocationOn,
  MdRestaurant,
  MdMyLocation,
  MdAccessTime,
  MdInventory2
} from 'react-icons/md';
import dayjs from 'dayjs';
import { getStatusStyle, getActiveOrder } from './dispatchShared';

const ActiveSection = ({
  visibleRiders,
  riders,
  focusedStop,
  handleRiderFocus,
  setFocusedStop,
  calculateEstMeters,
  getRiderColor,
  formatMeters
}) => {
  const activeDeliveries = visibleRiders
    .map((r) => getActiveOrder(r.orders))
    .filter(Boolean)
    .sort((a, b) =>
      String(a.rider_name || a.ridername || '').localeCompare(
        String(b.rider_name || b.ridername || '')
      )
    );

  if (activeDeliveries.length === 0) {
    return (
      <div className="empty-slot">
        <div className="empty-slot-icon">
          <MdInventory2 />
        </div>
        <div className="empty-slot-title">No active deliveries</div>
        <div className="empty-slot-sub">
          No deliveries are currently in progress for this slot
        </div>
      </div>
    );
  }

  const renderActiveDeliveryCard = (o, i) => {
    const rid = o.rider_id;
    const rider = riders.find((r) => String(r.id) === String(rid));
    const color = getRiderColor(rid);
    const statusStyle = getStatusStyle(o.orderstatus);
    const lat = parseFloat(o.droplat || o.deliverylat);
    const lon = parseFloat(o.droplon || o.deliverylong);
    const canFocus = Number.isFinite(lat) && Number.isFinite(lon);
    const estMeters = calculateEstMeters(rid, o);
    const customer = o.deliverycustomer || o.customername || `Order #${o.orderid}`;
    const dropArea = o.deliverysuburb || o.deliveryaddress || o.zone_name || '';
    const riderName = o.rider_name || o.ridername || 'Unassigned';
    const isActive = canFocus && focusedStop && String(focusedStop.orderid) === String(o.orderid);
    const initials =
      riderName
        .split(/\s+/)
        .filter(Boolean)
        .slice(0, 2)
        .map((w) => w[0])
        .join('')
        .toUpperCase() || '•';

    return (
      <div
        key={o.orderid}
        className={`adcard${isActive ? ' is-active' : ''}`}
        style={{ '--ad-accent': color, animationDelay: `${i * 0.05}s` }}
        onClick={() => {
          if (rider) handleRiderFocus(rider);
          if (canFocus) setFocusedStop({ orderid: o.orderid, lat, lon });
        }}
      >
        <div className="adcard-top">
          <div className="adcard-avatar" style={{ background: color }}>{initials}</div>
          <div className="adcard-titles">
            <div className="adcard-customer" title={customer}>{customer}</div>
            <div className="adcard-rider" title={riderName}>
              <MdTwoWheeler style={{ fontSize: 13, flexShrink: 0 }} />
              <span className="adcard-tx">{riderName}</span>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: '4px' }}>
            <span
              className="adcard-status"
              style={{ background: `${statusStyle.bg}1a`, color: statusStyle.bg }}
              title={statusStyle.label}
            >
              {statusStyle.label}
            </span>
            {o.deliverytime && (
              <span className="adcard-time" style={{ fontSize: '11px', color: '#64748b' }}>
                {dayjs(o.deliverytime).isValid() ? dayjs(o.deliverytime).format('HH:mm:ss') : String(o.deliverytime)}
              </span>
            )}
          </div>
        </div>

        {dropArea && (
          <div className="adcard-addr">
            <span className="adcard-ic"><MdLocationOn /></span>
            <span className="adcard-tx adcard-addr-tx" title={dropArea}>{dropArea}</span>
          </div>
        )}

        <div className="adcard-foot">
          {o.pickupcustomer ? (
            <span className="adcard-pickup" title={o.pickupcustomer}>
              <span className="adcard-ic"><MdRestaurant /></span>
              <span className="adcard-tx">{o.pickupcustomer}</span>
            </span>
          ) : (
            <span />
          )}
          <span className="adcard-metrics">
            {estMeters !== null && (
              <>
                <span className="adcard-m adcard-m-eta" title="Distance to drop">
                  <span className="adcard-ic"><MdMyLocation /></span>
                  {formatMeters(estMeters)}
                </span>
                <span className="adcard-m adcard-m-time" title="Estimated time to drop">
                  <span className="adcard-ic"><MdAccessTime /></span>
                  {(() => {
                    const etaMin = estMeters / 1000 / 20 * 60;
                    return etaMin < 1 ? '< 1 min' : `${Math.ceil(etaMin)} min`;
                  })()}
                </span>
              </>
            )}
          </span>
        </div>
      </div>
    );
  };

  return <div className="adcard-list">{activeDeliveries.map(renderActiveDeliveryCard)}</div>;
};

export default ActiveSection;
