'use client';

import { useState } from 'react';
import { ManualCreditDto } from '@/types/commission.types';
import { manualCredit } from '@/services/commission/commission.service';

interface CommissionManualCreditFormProps {
  onSuccess?: (commission: any) => void;
  onError?: (error: string) => void;
}

export const CommissionManualCreditForm = ({ onSuccess, onError }: CommissionManualCreditFormProps) => {
  const [userId, setUserId] = useState('');
  const [amount, setAmount] = useState('');
  const [currency, setCurrency] = useState('USD');
  const [notes, setNotes] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!userId || !amount || !currency) {
      onError?.('Please fill in all required fields.');
      return;
    }

    const amountNum = parseFloat(amount);
    if (isNaN(amountNum) || amountNum <= 0) {
      onError?.('Amount must be a positive number.');
      return;
    }

    try {
      setIsSubmitting(true);
      const dto: ManualCreditDto = {
        userId,
        amount: amountNum,
        currency,
        notes: notes || undefined,
      };
      const result = await manualCredit(dto);
      onSuccess?.(result);
      
      // Reset form
      setUserId('');
      setAmount('');
      setCurrency('USD');
      setNotes('');
    } catch (err: any) {
      onError?.(err?.response?.data?.message || 'Failed to credit commission.');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4 bg-white rounded-lg shadow p-6">
      <h3 className="text-lg font-semibold text-gray-900">Manual Commission Credit</h3>

      <div>
        <label htmlFor="userId" className="block text-sm font-medium text-gray-700">
          User ID <span className="text-red-500">*</span>
        </label>
        <input
          id="userId"
          type="text"
          value={userId}
          onChange={(e) => setUserId(e.target.value)}
          required
          className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
          placeholder="Enter user ID"
        />
      </div>

      <div className="grid grid-cols-2 gap-4">
        <div>
          <label htmlFor="amount" className="block text-sm font-medium text-gray-700">
            Amount <span className="text-red-500">*</span>
          </label>
          <input
            id="amount"
            type="number"
            step="0.01"
            min="0.01"
            value={amount}
            onChange={(e) => setAmount(e.target.value)}
            required
            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            placeholder="0.00"
          />
        </div>
        <div>
          <label htmlFor="currency" className="block text-sm font-medium text-gray-700">
            Currency <span className="text-red-500">*</span>
          </label>
          <input
            id="currency"
            type="text"
            value={currency}
            onChange={(e) => setCurrency(e.target.value.toUpperCase())}
            required
            maxLength={5}
            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
            placeholder="USD"
          />
        </div>
      </div>

      <div>
        <label htmlFor="notes" className="block text-sm font-medium text-gray-700">Notes</label>
        <textarea
          id="notes"
          value={notes}
          onChange={(e) => setNotes(e.target.value)}
          rows={3}
          className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm"
          placeholder="Optional notes about this credit"
        />
      </div>

      <div className="text-right">
        <button
          type="submit"
          disabled={isSubmitting}
          className="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50"
        >
          {isSubmitting ? 'Processing...' : 'Credit Commission'}
        </button>
      </div>
    </form>
  );
};

