// src/components/dashboard/OrderApprovalModal.tsx
'use client';

import { useState } from 'react';
import { X, AlertCircle, CheckCircle, Send } from 'lucide-react';
import toast from 'react-hot-toast';

interface OrderApprovalModalProps {
  isOpen: boolean;
  onClose: () => void;
  orderId: string;
  orderNumber: string;
  orderType: 'individual' | 'package';
  itemId?: string;
  packageItemId?: string;
  itemName?: string;
  onSuccess: () => void;
}

export default function OrderApprovalModal({
  isOpen,
  onClose,
  orderId,
  orderNumber,
  orderType,
  itemId,
  packageItemId,
  itemName,
  onSuccess,
}: OrderApprovalModalProps) {
  const [action, setAction] = useState<'approve' | 'reject' | null>(null);
  const [rejectionReason, setRejectionReason] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  if (!isOpen) return null;

  const handleSubmit = async () => {
    if (!action) {
      toast.error('Please select an action');
      return;
    }

    if (action === 'reject' && !rejectionReason.trim()) {
      toast.error('Please provide a reason for rejection');
      return;
    }

    setIsSubmitting(true);

    try {
      const response = await fetch('/api/frontend/dashboard/orders/approve-reject', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          orderId,
          action,
          rejectionReason: action === 'reject' ? rejectionReason : undefined,
          itemId,
          packageItemId,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.message || 'Failed to process order');
      }

      toast.success(
        action === 'approve' 
          ? 'Order approved successfully! Links are now live.' 
          : 'Order rejected successfully.'
      );
      
      onSuccess();
      onClose();
    } catch (error) {
      console.error('Error:', error);
      toast.error(error instanceof Error ? error.message : 'Failed to process order');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/50" onClick={onClose} />
      
      {/* Modal */}
      <div className="relative bg-white rounded-2xl shadow-xl max-w-md w-full p-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-gray-900">Review Order</h2>
          <button
            onClick={onClose}
            className="p-1 text-gray-400 hover:text-gray-600 rounded-lg"
          >
            <X className="h-5 w-5" />
          </button>
        </div>

        {/* Order Info */}
        <div className="mb-6 p-4 bg-gray-50 rounded-lg">
          <p className="text-sm text-gray-600">Order #{orderNumber}</p>
          <p className="text-sm font-medium text-gray-900 mt-1">
            {orderType === 'package' ? 'Package Order' : 'Individual Order'}
          </p>
          {itemName && (
            <p className="text-sm text-gray-600 mt-1">
              Item: <span className="font-medium">{itemName}</span>
            </p>
          )}
        </div>

        {/* Action Selection */}
        <div className="space-y-4">
          <div className="flex gap-4">
            <button
              onClick={() => setAction('approve')}
              className={`flex-1 flex items-center justify-center gap-2 p-4 rounded-xl border-2 transition-all ${
                action === 'approve'
                  ? 'border-green-500 bg-green-50 text-green-700'
                  : 'border-gray-200 hover:border-green-200 text-gray-600'
              }`}
            >
              <CheckCircle className="h-5 w-5" />
              <span className="font-medium">Approve</span>
            </button>
            
            <button
              onClick={() => setAction('reject')}
              className={`flex-1 flex items-center justify-center gap-2 p-4 rounded-xl border-2 transition-all ${
                action === 'reject'
                  ? 'border-red-500 bg-red-50 text-red-700'
                  : 'border-gray-200 hover:border-red-200 text-gray-600'
              }`}
            >
              <AlertCircle className="h-5 w-5" />
              <span className="font-medium">Reject</span>
            </button>
          </div>

          {/* Rejection Reason */}
          {action === 'reject' && (
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                Reason for Rejection
              </label>
              <textarea
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                rows={4}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-red-500 transition-colors"
                placeholder="Please provide a detailed reason for rejection..."
              />
              <p className="text-xs text-gray-500">
                This reason will be shared with our team to improve future deliveries.
              </p>
            </div>
          )}

          {/* Action Buttons */}
          <div className="flex gap-3 pt-4">
            <button
              onClick={onClose}
              className="flex-1 px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors"
            >
              Cancel
            </button>
            <button
              onClick={handleSubmit}
              disabled={isSubmitting || !action || (action === 'reject' && !rejectionReason.trim())}
              className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-[#0066FF] text-white rounded-lg hover:bg-[#0052cc] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {isSubmitting ? (
                <>
                  <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin" />
                  Processing...
                </>
              ) : (
                <>
                  <Send className="h-4 w-4" />
                  Submit Review
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}