'use client';

/**
 * Manual M-Pesa Confirmation Modal
 * Allows manager/admin to manually confirm M-Pesa payment with transaction code
 */

import { useState } from 'react';
import { Modal, Button, Input } from '@/components/ui';
import { CreditCard, CheckCircle, AlertCircle } from 'lucide-react';
import toast from 'react-hot-toast';
import { paymentsAPI } from '@/lib/api';

export default function ManualMPesaConfirmModal({
  isOpen,
  onClose,
  paymentId,
  onConfirm,
}) {
  const [transactionCode, setTransactionCode] = useState('');
  const [isProcessing, setIsProcessing] = useState(false);

  const handleConfirm = async () => {
    if (!transactionCode.trim()) {
      toast.error('Please enter M-Pesa transaction code');
      return;
    }

    // Validate format (uppercase alphanumeric, 5-50 chars)
    if (!/^[A-Z0-9]{5,50}$/.test(transactionCode.trim().toUpperCase())) {
      toast.error('Transaction code must be 5-50 uppercase letters and numbers');
      return;
    }

    setIsProcessing(true);
    try {
      const response = await paymentsAPI.manuallyConfirm({
        payment_id: paymentId,
        mpesa_transaction_code: transactionCode.trim().toUpperCase(),
      });

      if (response.success || response.data) {
        toast.success('M-Pesa payment confirmed successfully!');
        if (onConfirm) {
          onConfirm(response.data || response);
        }
        setTransactionCode('');
        onClose();
      }
    } catch (error) {
      toast.error(error.response?.data?.message || error.message || 'Failed to confirm payment');
    } finally {
      setIsProcessing(false);
    }
  };

  return (
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="Manual M-Pesa Confirmation"
      size="md"
    >
      <div className="p-6 space-y-6">
        {/* Info Section */}
        <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-xl p-4">
          <div className="flex items-start gap-3">
            <AlertCircle className="w-5 h-5 text-blue-600 dark:text-blue-400 mt-0.5" />
            <div className="flex-1">
              <p className="font-semibold text-blue-900 dark:text-blue-100 mb-1">
                Confirm M-Pesa Payment
              </p>
              <p className="text-sm text-blue-700 dark:text-blue-300">
                Enter the M-Pesa transaction code (receipt number) from the customer's payment confirmation message.
                This will mark the payment as successful.
              </p>
            </div>
          </div>
        </div>

        {/* Transaction Code Input */}
        <div>
          <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
            M-Pesa Transaction Code *
          </label>
          <Input
            type="text"
            value={transactionCode}
            onChange={(e) => setTransactionCode(e.target.value.toUpperCase())}
            placeholder="e.g., RGT8X7Z9K1"
            icon={CreditCard}
            maxLength={50}
            className="font-mono text-lg tracking-wider"
            disabled={isProcessing}
          />
          <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">
            Enter the transaction code exactly as it appears in the M-Pesa confirmation message (e.g., RGT8X7Z9K1)
          </p>
        </div>

        {/* Action Buttons */}
        <div className="flex gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
          <Button
            variant="outline"
            onClick={onClose}
            className="flex-1"
            disabled={isProcessing}
          >
            Cancel
          </Button>
          <Button
            variant="primary"
            onClick={handleConfirm}
            className="flex-1 flex items-center justify-center gap-2"
            disabled={isProcessing || !transactionCode.trim()}
            loading={isProcessing}
          >
            <CheckCircle className="w-5 h-5" />
            Confirm Payment
          </Button>
        </div>
      </div>
    </Modal>
  );
}

