'use client';

/**
 * Swipeable Delivery Item Component
 * 
 * Delivery list item with swipe-to-delete/edit actions
 */

import { useState, useRef } from 'react';
import { useSwipeActions, useHaptic } from '../../hooks/use-ux-enhancements';
import { Package, MapPin, Calendar, Trash2, Edit, Eye, AlertTriangle, Check } from 'lucide-react';

interface DeliveryItemProps {
  id: number;
  schoolName: string;
  commodityName: string;
  quantity: number;
  unit: string;
  deliveryDate: string;
  status?: 'OK' | 'PENDING_REVIEW' | 'APPROVED' | 'REJECTED';
  isFlagged?: boolean;
  onView?: () => void;
  onEdit?: () => void;
  onDelete?: () => void;
}

export function SwipeableDeliveryItem({
  id,
  schoolName,
  commodityName,
  quantity,
  unit,
  deliveryDate,
  status = 'OK',
  isFlagged = false,
  onView,
  onEdit,
  onDelete,
}: DeliveryItemProps) {
  const [isDeleting, setIsDeleting] = useState(false);
  const haptic = useHaptic();

  const handleSwipeLeft = () => {
    if (onDelete) {
      haptic.warning();
      setIsDeleting(true);
    }
  };

  const handleSwipeRight = () => {
    if (onEdit) {
      haptic.light();
      onEdit();
    }
  };

  const { swipeOffset, isSwipingLeft, isSwipingRight, handlers } = useSwipeActions({
    onSwipeLeft: handleSwipeLeft,
    onSwipeRight: handleSwipeRight,
    threshold: 80,
  });

  const confirmDelete = () => {
    haptic.success();
    onDelete?.();
    setIsDeleting(false);
  };

  const cancelDelete = () => {
    setIsDeleting(false);
  };

  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', {
      month: 'short',
      day: 'numeric',
    });
  };

  const getStatusColor = () => {
    switch (status) {
      case 'APPROVED':
        return 'bg-emerald-100 text-emerald-700';
      case 'PENDING_REVIEW':
        return 'bg-amber-100 text-amber-700';
      case 'REJECTED':
        return 'bg-red-100 text-red-700';
      default:
        return 'bg-slate-100 text-slate-600';
    }
  };

  if (isDeleting) {
    return (
      <div className="rounded-xl border border-red-200 bg-red-50 p-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Trash2 className="h-5 w-5 text-red-500" />
            <span className="text-sm font-medium text-red-700">Delete this delivery?</span>
          </div>
          <div className="flex gap-2">
            <button
              onClick={cancelDelete}
              className="rounded-lg px-3 py-1 text-sm font-medium text-slate-600 hover:bg-white"
            >
              Cancel
            </button>
            <button
              onClick={confirmDelete}
              className="rounded-lg bg-red-500 px-3 py-1 text-sm font-medium text-white hover:bg-red-600"
            >
              Delete
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="relative overflow-hidden rounded-xl">
      {/* Background actions */}
      <div className="absolute inset-y-0 left-0 flex items-center justify-start pl-4 bg-blue-500 w-full">
        <Edit className="h-5 w-5 text-white" />
        <span className="ml-2 text-sm font-medium text-white">Edit</span>
      </div>
      <div className="absolute inset-y-0 right-0 flex items-center justify-end pr-4 bg-red-500 w-full">
        <span className="mr-2 text-sm font-medium text-white">Delete</span>
        <Trash2 className="h-5 w-5 text-white" />
      </div>

      {/* Main content */}
      <div
        {...handlers}
        onClick={() => onView?.()}
        className="relative bg-white border border-slate-100 rounded-xl p-4 cursor-pointer transition-transform"
        style={{
          transform: `translateX(${swipeOffset}px)`,
        }}
      >
        <div className="flex items-start justify-between gap-3">
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              <Package className="h-4 w-4 text-emerald-600 flex-shrink-0" />
              <h3 className="font-semibold text-slate-900 truncate">{commodityName}</h3>
              {isFlagged && (
                <AlertTriangle className="h-4 w-4 text-amber-500 flex-shrink-0" />
              )}
            </div>
            
            <div className="mt-1 flex items-center gap-2 text-sm text-slate-500">
              <MapPin className="h-3 w-3" />
              <span className="truncate">{schoolName}</span>
            </div>
          </div>

          <div className="text-right flex-shrink-0">
            <div className="text-lg font-bold text-slate-900">
              {quantity.toLocaleString()}
              <span className="text-xs font-normal text-slate-500 ml-1">{unit}</span>
            </div>
            <div className="flex items-center justify-end gap-2 mt-1">
              <span className={`text-xs px-2 py-0.5 rounded-full ${getStatusColor()}`}>
                {status === 'OK' ? 'Recorded' : status.replace('_', ' ')}
              </span>
            </div>
          </div>
        </div>

        <div className="mt-2 flex items-center justify-between text-xs text-slate-400">
          <div className="flex items-center gap-1">
            <Calendar className="h-3 w-3" />
            {formatDate(deliveryDate)}
          </div>
          <span>Swipe for actions</span>
        </div>

        {/* Swipe indicators */}
        {isSwipingRight && (
          <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
            <div className="flex items-center gap-1 text-blue-500">
              <Edit className="h-4 w-4" />
              <span className="text-xs font-medium">Edit</span>
            </div>
          </div>
        )}
        {isSwipingLeft && (
          <div className="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
            <div className="flex items-center gap-1 text-red-500">
              <span className="text-xs font-medium">Delete</span>
              <Trash2 className="h-4 w-4" />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Simple delivery item without swipe (for read-only lists)
export function DeliveryItem({
  schoolName,
  commodityName,
  quantity,
  unit,
  deliveryDate,
  status = 'OK',
  isFlagged = false,
  onClick,
}: Omit<DeliveryItemProps, 'id' | 'onView' | 'onEdit' | 'onDelete'> & { onClick?: () => void }) {
  const formatDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  };

  const getStatusColor = () => {
    switch (status) {
      case 'APPROVED':
        return 'bg-emerald-100 text-emerald-700';
      case 'PENDING_REVIEW':
        return 'bg-amber-100 text-amber-700';
      case 'REJECTED':
        return 'bg-red-100 text-red-700';
      default:
        return 'bg-slate-100 text-slate-600';
    }
  };

  return (
    <div
      onClick={onClick}
      className="rounded-xl border border-slate-100 bg-white p-4 hover:shadow-sm transition-shadow cursor-pointer"
    >
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2">
            <Package className="h-4 w-4 text-emerald-600 flex-shrink-0" />
            <h3 className="font-semibold text-slate-900 truncate">{commodityName}</h3>
            {isFlagged && <AlertTriangle className="h-4 w-4 text-amber-500 flex-shrink-0" />}
          </div>
          <div className="mt-1 flex items-center gap-2 text-sm text-slate-500">
            <MapPin className="h-3 w-3" />
            <span className="truncate">{schoolName}</span>
          </div>
        </div>
        <div className="text-right flex-shrink-0">
          <div className="text-lg font-bold text-slate-900">
            {quantity.toLocaleString()}
            <span className="text-xs font-normal text-slate-500 ml-1">{unit}</span>
          </div>
          <span className={`text-xs px-2 py-0.5 rounded-full ${getStatusColor()}`}>
            {status === 'OK' ? <Check className="h-3 w-3 inline" /> : status.replace('_', ' ')}
          </span>
        </div>
      </div>
      <div className="mt-2 flex items-center gap-1 text-xs text-slate-400">
        <Calendar className="h-3 w-3" />
        {formatDate(deliveryDate)}
      </div>
    </div>
  );
}
