import { useState } from 'react';
import { Clock, Check, Truck, Package, XCircle, RotateCcw } from 'lucide-react';

type OrderStatus = 'pending' | 'confirmed' | 'processing' | 'shipped' | 'delivered' | 'cancelled' | 'refunded';

interface Order {
  id: string;
  status: OrderStatus;
  customerName: string;
  total: number;
  updatedAt: string;
}

interface OrderStatusManagerProps {
  order: Order;
  onStatusChange: (status: OrderStatus) => void;
}

const STATUS_CONFIG: Record<OrderStatus, {
  label: string;
  color: string;
  bgColor: string;
  icon: any;
  nextStatuses: OrderStatus[];
}> = {
  pending: {
    label: 'รอตรวจสอบ',
    color: 'text-yellow-600',
    bgColor: 'bg-yellow-50 border-yellow-200',
    icon: Clock,
    nextStatuses: ['confirmed', 'cancelled']
  },
  confirmed: {
    label: 'ยืนยันแล้ว',
    color: 'text-blue-600',
    bgColor: 'bg-blue-50 border-blue-200',
    icon: Check,
    nextStatuses: ['processing', 'cancelled']
  },
  processing: {
    label: 'กำลังจัดเตรียม',
    color: 'text-purple-600',
    bgColor: 'bg-purple-50 border-purple-200',
    icon: Package,
    nextStatuses: ['shipped']
  },
  shipped: {
    label: 'จัดส่งแล้ว',
    color: 'text-indigo-600',
    bgColor: 'bg-indigo-50 border-indigo-200',
    icon: Truck,
    nextStatuses: ['delivered']
  },
  delivered: {
    label: 'จัดส่งสำเร็จ',
    color: 'text-green-600',
    bgColor: 'bg-green-50 border-green-200',
    icon: Check,
    nextStatuses: ['refunded']
  },
  cancelled: {
    label: 'ยกเลิกแล้ว',
    color: 'text-red-600',
    bgColor: 'bg-red-50 border-red-200',
    icon: XCircle,
    nextStatuses: []
  },
  refunded: {
    label: 'คืนเงินแล้ว',
    color: 'text-gray-600',
    bgColor: 'bg-gray-50 border-gray-200',
    icon: RotateCcw,
    nextStatuses: []
  }
};

export default function OrderStatusManager({ order, onStatusChange }: OrderStatusManagerProps) {
  const [isUpdating, setIsUpdating] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [selectedStatus, setSelectedStatus] = useState<OrderStatus | null>(null);

  const currentConfig = STATUS_CONFIG[order.status];
  const Icon = currentConfig.icon;

  const handleStatusChange = async (newStatus: OrderStatus) => {
    setSelectedStatus(newStatus);
    setShowConfirmModal(true);
  };

  const confirmStatusChange = async () => {
    if (!selectedStatus) return;
    
    setIsUpdating(true);
    try {
      await onStatusChange(selectedStatus);
    } finally {
      setIsUpdating(false);
      setShowConfirmModal(false);
      setSelectedStatus(null);
    }
  };

  return (
    <div className="space-y-6">
      {/* Current Status */}
      <div className={`p-4 rounded-xl border ${currentConfig.bgColor}`}>
        <div className="flex items-center gap-3">
          <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
            order.status === 'cancelled' || order.status === 'refunded' 
              ? 'bg-red-100' : 'bg-white'
          }`}>
            <Icon className={`w-5 h-5 ${currentConfig.color}`} />
          </div>
          <div className="flex-1">
            <p className={`font-medium ${currentConfig.color}`}>
              {currentConfig.label}
            </p>
            <p className="text-xs text-gray-500 mt-0.5">
              อัปเดตล่าสุด: {new Date(order.updatedAt).toLocaleDateString('th-TH', {
                day: 'numeric',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
              })}
            </p>
          </div>
        </div>
      </div>

      {/* Progress Timeline */}
      <div className="relative">
        <div className="absolute left-5 top-0 bottom-0 w-0.5 bg-gray-200" />
        <div className="space-y-4 relative">
          {(['pending', 'confirmed', 'processing', 'shipped', 'delivered']).map((status, index) => {
            const config = STATUS_CONFIG[status as OrderStatus];
            const statusIndex = Object.keys(STATUS_CONFIG).indexOf(order.status);
            const currentIndex = Object.keys(STATUS_CONFIG).indexOf(status);
            const isCompleted = currentIndex <= statusIndex;
            const isCurrent = status === order.status;
            
            return (
              <div key={status} className="flex items-center gap-4">
                <div className={`
                  w-10 h-10 rounded-full flex items-center justify-center z-10
                  ${isCompleted ? 'bg-green-500 text-white' : 'bg-gray-200 text-gray-400'}
                  ${isCurrent ? 'ring-4 ring-offset-2 ' + config.bgColor.replace('50', '100').replace('200', '300') : ''}
                `}>
                  <Check className="w-5 h-5" />
                </div>
                <div>
                  <p className={`text-sm font-medium ${
                    isCompleted ? 'text-gray-900' : 'text-gray-400'
                  }`}>
                    {config.label}
                  </p>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Next Actions */}
      {currentConfig.nextStatuses.length > 0 && (
        <div className="border-t pt-6">
          <p className="text-sm font-medium text-gray-700 mb-3">อัปเดตสถานะ</p>
          <div className="flex flex-wrap gap-2">
            {currentConfig.nextStatuses.map(status => {
              const config = STATUS_CONFIG[status];
              const NextIcon = config.icon;
              
              return (
                <button
                  key={status}
                  onClick={() => handleStatusChange(status)}
                  disabled={isUpdating}
                  className={`
                    flex items-center gap-2 px-4 py-2 rounded-lg border-2 transition-colors
                    ${config.bgColor} ${config.color} border-current
                    hover:opacity-80 disabled:opacity-50
                  `}
                >
                  <NextIcon className="w-4 h-4" />
                  <span className="font-medium">{config.label}</span>
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* History */}
      <div className="border-t pt-6">
        <p className="text-sm font-medium text-gray-700 mb-3">ประวัติการเปลี่ยนสถานะ</p>
        <div className="space-y-3">
          <div className="flex items-center gap-3 text-sm">
            <div className="w-2 h-2 rounded-full bg-green-500" />
            <span className="text-gray-600">ยืนยันคำสั่งซื้อ</span>
            <span className="text-gray-400 ml-auto">10 เม.ย. 2567 14:30</span>
          </div>
          <div className="flex items-center gap-3 text-sm">
            <div className="w-2 h-2 rounded-full bg-yellow-500" />
            <span className="text-gray-600">สร้างคำสั่งซื้อ</span>
            <span className="text-gray-400 ml-auto">10 เม.ย. 2567 14:00</span>
          </div>
        </div>
      </div>

      {/* Confirm Modal */}
      {showConfirmModal && selectedStatus && (
        <div className="fixed inset-0 z-50 flex items-center justify-center">
          <div 
            className="absolute inset-0 bg-black/50"
            onClick={() => setShowConfirmModal(false)}
          />
          <div className="relative bg-white rounded-xl p-6 max-w-sm w-full mx-4 shadow-xl">
            <h3 className="font-medium text-lg mb-2">ยืนยันการเปลี่ยนสถานะ</h3>
            <p className="text-gray-600 mb-6">
              คุณต้องการเปลี่ยนสถานะจาก 
              <span className="font-medium"> {currentConfig.label} </span>
              เป็น 
              <span className="font-medium"> {STATUS_CONFIG[selectedStatus].label} </span>
              หรือไม่?
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => setShowConfirmModal(false)}
                className="flex-1 py-2 border rounded-lg hover:bg-gray-50"
              >
                ยกเลิก
              </button>
              <button
                onClick={confirmStatusChange}
                disabled={isUpdating}
                className="flex-1 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              >
                {isUpdating ? 'กำลังอัปเดต...' : 'ยืนยัน'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
