/**
 * Pay Fees Modal - Paynow Integration
 * For Students and Parents
 */

import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { api } from '../store/api';
import {
  CreditCard, DollarSign, CheckCircle, X,
  Loader2, AlertCircle, ExternalLink, ArrowLeft
} from 'lucide-react';

interface FeeRecord {
  id: number;
  student_id: number;
  amount: number;
  paid_amount: number;
  status: string;
  fee_name: string;
  due_date: string;
}

interface PaymentResult {
  success: boolean;
  payment_id: string;
  reference: string;
  amount: number;
  payment_url?: string;
  poll_url?: string;
  mode?: string;
}

export function PayFeesModal({ 
  studentId, 
  onClose 
}: { 
  studentId: number; 
  onClose: () => void;
}) {
  const [fees, setFees] = useState<FeeRecord[]>([]);
  const [selectedFee, setSelectedFee] = useState<FeeRecord | null>(null);
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [paymentResult, setPaymentResult] = useState<PaymentResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [checkingStatus, setCheckingStatus] = useState(false);
  
  useEffect(() => {
    fetchStudentFees();
  }, [studentId]);
  
  const fetchStudentFees = async () => {
    try {
      const response = await api.get(`/fees/students?student_id=${studentId}`);
      setFees(response.data.filter((f: FeeRecord) => f.status !== 'paid'));
    } catch (error) {
      console.error('Failed to fetch fees:', error);
    }
  };
  
  const handleInitiatePayment = async () => {
    if (!selectedFee) return;
    
    const paymentAmount = parseFloat(amount);
    if (isNaN(paymentAmount) || paymentAmount <= 0) {
      setError('Please enter a valid amount');
      return;
    }
    
    const remaining = selectedFee.amount - selectedFee.paid_amount;
    if (paymentAmount > remaining) {
      setError(`Amount exceeds remaining balance of $${remaining.toFixed(2)}`);
      return;
    }
    
    setLoading(true);
    setError(null);
    
    try {
      const response = await api.post('/payments/initiate', {
        student_fee_id: selectedFee.id,
        amount: paymentAmount
      });
      
      setPaymentResult(response.data);
      
    } catch (err: any) {
      setError(err.response?.data?.error || 'Failed to initiate payment');
    } finally {
      setLoading(false);
    }
  };
  
  const checkPaymentStatus = async () => {
    if (!paymentResult?.payment_id) return;
    
    setCheckingStatus(true);
    try {
      const response = await api.get(`/payments/status/${paymentResult.payment_id}`);
      
      if (response.data.status === 'completed') {
        setPaymentResult({
          ...paymentResult,
          success: true
        });
        // Refresh fees
        fetchStudentFees();
      }
      
    } catch (error) {
      console.error('Failed to check status:', error);
    } finally {
      setCheckingStatus(false);
    }
  };
  
  const handlePaynowRedirect = () => {
    if (paymentResult?.payment_url) {
      // Open Paynow in new tab
      window.open(paymentResult.payment_url, '_blank');
    }
  };
  
  // Step 1: Select fee and amount
  if (!paymentResult) {
    return createPortal(
      <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center z-[150] p-4" onClick={onClose}>
        <div className="bg-card text-text border border-border rounded-[2.5rem] w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
          <div className="p-6 border-b border-border flex items-center justify-between relative">
            <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
              <DollarSign size={180} />
            </div>
            <div className="relative z-10 flex items-center gap-3">
              <div className="w-10 h-10 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
                <DollarSign className="text-green-600 dark:text-green-400" size={20} />
              </div>
              <div>
                <h2 className="font-semibold text-lg">Pay School Fees</h2>
                <p className="text-sm text-text-muted">Select fee and enter amount</p>
              </div>
            </div>
            <button onClick={onClose} className="relative z-10 p-2 hover:bg-muted rounded-lg text-text-muted hover:text-text">
              <X size={20} />
            </button>
          </div>
          
          <div className="p-6 space-y-4">
            {/* Error Display */}
            {error && (
              <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-3 flex items-center gap-2 text-red-700 dark:text-red-400">
                <AlertCircle size={18} />
                {error}
              </div>
            )}
            
            {/* Select Fee */}
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">Select Fee Type</label>
              <div className="space-y-2">
                {fees.length > 0 ? fees.map((fee) => {
                  const remaining = fee.amount - fee.paid_amount;
                  return (
                    <div 
                      key={fee.id}
                      onClick={() => {
                        setSelectedFee(fee);
                        setAmount(remaining.toFixed(2));
                        setError(null);
                      }}
                      className={`p-4 border rounded-lg cursor-pointer transition ${
                        selectedFee?.id === fee.id 
                          ? 'border-primary bg-primary/5' 
                          : 'border-border hover:border-text-muted'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="font-medium text-text">{fee.fee_name}</p>
                          <p className="text-sm text-text-muted">
                            Due: {fee.due_date || 'No due date'}
                          </p>
                        </div>
                        <div className="text-right">
                          <p className="font-bold text-text">${remaining.toFixed(2)}</p>
                          <p className="text-xs text-text-muted">
                            ${fee.paid_amount.toFixed(2)} paid
                          </p>
                        </div>
                      </div>
                    </div>
                  );
                }) : (
                  <div className="text-center py-8 text-text-muted">
                    <CheckCircle size={48} className="mx-auto text-green-500 mb-2" />
                    <p>All fees are paid!</p>
                  </div>
                )}
              </div>
            </div>
            
            {/* Amount Input */}
            {selectedFee && (
              <div>
                <label className="block text-sm font-medium text-text-secondary mb-2">
                  Amount to Pay ($)
                </label>
                <div className="relative">
                  <span className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted font-bold">$</span>
                  <input 
                    type="number" 
                    step="0.01"
                    className="w-full pl-8 pr-4 py-3 border border-border bg-background rounded-lg text-lg text-text outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                    value={amount}
                    onChange={(e) => {
                      setAmount(e.target.value);
                      setError(null);
                    }}
                    placeholder="0.00"
                  />
                </div>
                <p className="text-xs text-text-muted mt-1">
                  Remaining balance: ${(selectedFee.amount - selectedFee.paid_amount).toFixed(2)}
                </p>
              </div>
            )}
            
            {/* Quick Amount Buttons */}
            {selectedFee && (
              <div className="flex gap-2">
                {[0.25, 0.5, 0.75, 1].map((fraction) => {
                  const amt = ((selectedFee.amount - selectedFee.paid_amount) * fraction).toFixed(2);
                  return (
                    <button
                      key={fraction}
                      onClick={() => setAmount(amt)}
                      className="flex-1 py-2 border border-border rounded-lg text-sm text-text-secondary hover:bg-muted transition-colors"
                    >
                      {fraction * 100}%
                    </button>
                  );
                })}
              </div>
            )}
          </div>
          
          <div className="p-6 border-t border-border bg-muted/30 flex justify-between rounded-b-2xl">
            <button 
              onClick={onClose}
              className="px-4 py-2 border border-border text-text-secondary rounded-lg hover:bg-muted transition-colors"
            >
              Cancel
            </button>
            <button 
              onClick={handleInitiatePayment}
              disabled={!selectedFee || loading || parseFloat(amount) <= 0}
              className="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2 shadow-lg shadow-green-500/20"
            >
              {loading ? (
                <>
                  <Loader2 size={18} className="animate-spin" />
                  Processing...
                </>
              ) : (
                <>
                  <CreditCard size={18} />
                  Pay with Paynow
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    );
  }
  
  // Step 2: Payment initiated
  if (paymentResult.mode === 'test') {
    return createPortal(
      <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center z-[150] p-4" onClick={onClose}>
        <div className="bg-card text-text border border-border rounded-[2.5rem] w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200">
          <div className="p-6 border-b border-border flex items-center justify-between relative">
            <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
              <DollarSign size={180} />
            </div>
            <div className="relative z-10">
              <h2 className="font-semibold text-lg">Test Mode - Payment Initiated</h2>
            </div>
            <button onClick={onClose} className="relative z-10 p-2 hover:bg-muted rounded-lg text-text-muted hover:text-text">
              <X size={20} />
            </button>
          </div>
          
          <div className="p-6 space-y-4">
            <div className="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4">
              <p className="text-sm text-blue-700 dark:text-blue-400">
                <strong>Test Mode:</strong> Paynow integration is not configured. 
                In production, this would redirect to Paynow payment page.
              </p>
            </div>
            
            <div className="space-y-3 text-text">
              <div className="flex justify-between py-2 border-b border-border">
                <span className="text-text-muted">Payment ID</span>
                <span className="font-mono text-sm">{paymentResult.payment_id}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-border">
                <span className="text-text-muted">Reference</span>
                <span className="font-mono text-sm">{paymentResult.reference}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-border">
                <span className="text-text-muted">Amount</span>
                <span className="font-bold text-lg">${paymentResult.amount.toFixed(2)}</span>
              </div>
              <div className="flex justify-between py-2">
                <span className="text-text-muted">Status</span>
                <span className="px-3 py-1 bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400 rounded-full text-sm">
                  Pending
                </span>
              </div>
            </div>
            
            <div className="bg-muted/50 rounded-lg p-4 text-text-muted">
              <p className="text-sm">
                To simulate a successful payment:
              </p>
              <ol className="text-sm mt-2 space-y-1 list-decimal list-inside">
                <li>Configure Paynow credentials in settings</li>
                <li>Redirect to actual Paynow payment page</li>
                <li>Complete payment on Paynow</li>
                <li>Return to see updated status</li>
              </ol>
            </div>
          </div>
          
          <div className="p-6 border-t border-border bg-muted/30 flex justify-between rounded-b-2xl">
            <button 
              onClick={() => {
                setPaymentResult(null);
                setSelectedFee(null);
                setAmount('');
              }}
              className="px-4 py-2 border border-border text-text-secondary rounded-lg hover:bg-muted flex items-center gap-2 transition-colors"
            >
              <ArrowLeft size={18} />
              Back
            </button>
            <button 
              onClick={onClose}
              className="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shadow-lg shadow-blue-500/10"
            >
              Done
            </button>
          </div>
        </div>
      </div>
    );
  }
  
  // Step 2: Real payment with Paynow redirect
  return createPortal(
    <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center z-[150] p-4" onClick={onClose}>
      <div className="bg-card text-text border border-border rounded-[2.5rem] w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
        <div className="p-6 border-b border-border flex items-center justify-between relative">
          <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
            <DollarSign size={180} />
          </div>
          <div className="relative z-10 flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-green-100 dark:bg-green-900/30 flex items-center justify-center">
              <CheckCircle className="text-green-600 dark:text-green-400" size={20} />
            </div>
            <div>
              <h2 className="font-semibold text-lg">Payment Initiated</h2>
              <p className="text-sm text-text-muted">Redirecting to Paynow...</p>
            </div>
          </div>
          <button onClick={onClose} className="relative z-10 p-2 hover:bg-muted rounded-lg text-text-muted hover:text-text">
            <X size={20} />
          </button>
        </div>
        
        <div className="p-6 space-y-4 text-text">
          <div className="bg-green-50 dark:bg-green-900/20 rounded-lg p-4 text-center">
            <DollarSign size={48} className="mx-auto text-green-600 dark:text-green-400 mb-2" />
            <p className="text-2xl font-bold">${paymentResult.amount.toFixed(2)}</p>
            <p className="text-sm text-text-muted">Ready to pay</p>
          </div>
          
          <div className="space-y-2 text-sm">
            <div className="flex justify-between py-2 border-b border-border">
              <span className="text-text-muted">Reference</span>
              <span className="font-mono">{paymentResult.reference}</span>
            </div>
            <div className="flex justify-between py-2">
              <span className="text-text-muted">Payment ID</span>
              <span className="font-mono text-xs">{paymentResult.payment_id}</span>
            </div>
          </div>
          
          {paymentResult.payment_url && (
            <button 
              onClick={handlePaynowRedirect}
              className="w-full py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 flex items-center justify-center gap-2 font-medium shadow-lg shadow-green-500/20"
            >
              <ExternalLink size={18} />
              Continue to Paynow
            </button>
          )}
          
          <div className="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-3 text-sm">
            <p className="text-yellow-700 dark:text-yellow-400 text-center italic">
              <strong>Important:</strong> After completing payment on Paynow, 
              return here and click "Check Status" to confirm your payment.
            </p>
          </div>
        </div>
        
        <div className="p-6 border-t border-border bg-muted/30 flex justify-between rounded-b-2xl">
          <button 
            onClick={checkPaymentStatus}
            disabled={checkingStatus}
            className="px-4 py-2 border border-border text-text-secondary rounded-lg hover:bg-muted flex items-center gap-2 transition-colors"
          >
            {checkingStatus && <Loader2 size={18} className="animate-spin" />}
            Check Payment Status
          </button>
          <button 
            onClick={onClose}
            className="px-6 py-2 text-text-muted hover:text-text rounded-lg transition-colors"
          >
            Close
          </button>
        </div>
      </div>
    </div>
  ,
    document.body
  );
}

// ==========================================
// PAYMENT SUCCESS VIEW
// ==========================================

export function PaymentSuccessView({ paymentData, onDone }: {
  paymentData: any;
  onDone: () => void;
}) {
  return createPortal(
    <div className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm flex items-center justify-center z-[150] p-4" onClick={onDone}>
      <div className="bg-card text-text border border-border rounded-[2.5rem] w-full max-w-xl max-h-[90vh] overflow-hidden animate-in zoom-in-95 duration-200" onClick={(e) => e.stopPropagation()}>
        <div className="p-6 border-b border-border flex items-center justify-between relative">
          <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12 text-primary">
            <CheckCircle size={180} />
          </div>
          <div className="relative z-10">
            <div className="space-y-4 text-center">
              <div className="w-20 h-20 rounded-full bg-green-100 dark:bg-green-900/30 flex items-center justify-center mx-auto mb-4">
                <CheckCircle size={48} className="text-green-600 dark:text-green-400" />
              </div>

              <h2 className="text-2xl font-bold text-text mb-2 uppercase tracking-tight">Payment Successful!</h2>
            </div>
          </div>
          <button onClick={onDone} className="relative z-10 p-2 hover:bg-muted rounded-lg text-text-muted hover:text-text">
            <X size={20} />
          </button>
        </div>
        <p className="text-text-muted mb-6">
          Your payment of <strong>${paymentData.amount?.toFixed(2)}</strong> has been received.
        </p>
        
        <div className="bg-muted/50 rounded-lg p-4 mb-6 text-left border border-border">
          <div className="flex justify-between py-2 border-b border-border/50">
            <span className="text-text-muted">Reference</span>
            <span className="font-mono text-text">{paymentData.reference}</span>
          </div>
          <div className="flex justify-between py-2 border-b border-border/50">
            <span className="text-text-muted">Fee</span>
            <span className="text-text">{paymentData.fee_name}</span>
          </div>
          <div className="flex justify-between py-2">
            <span className="text-gray-600 dark:text-text-muted">Date</span>
            <span className="text-text">{new Date().toLocaleDateString()}</span>
          </div>
        </div>
        
        <button 
          onClick={onDone}
          className="w-full py-4 bg-primary text-white rounded-xl hover:bg-primary/90 font-bold shadow-lg shadow-blue-500/20 active:scale-95 transition-all"
        >
          Done
        </button>
      </div>
    </div>
  ,
    document.body
  );
}

// ==========================================
// PAYMENT HISTORY COMPONENT
// ==========================================

export function PaymentHistory({ studentId }: { studentId: number }) {
  const [payments, setPayments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetchPayments();
  }, [studentId]);
  
  const fetchPayments = async () => {
    try {
      const response = await api.get(`/payments/student/${studentId}`);
      setPayments(response.data);
    } catch (error) {
      console.error('Failed to fetch payments:', error);
    } finally {
      setLoading(false);
    }
  };
  
  if (loading) {
    return <div className="text-center py-4 text-text-muted italic">Loading payments...</div>;
  }
  
  return (
    <div className="space-y-4 text-text">
      <h3 className="font-bold uppercase tracking-widest text-[0.65rem] text-text-muted px-1">Payment History</h3>

      {payments.length > 0 ? (
        <div className="space-y-2">
          {payments.map((payment) => (
            <div key={payment.id} className="bg-card border border-border rounded-xl p-4 flex items-center justify-between hover:shadow-md transition-shadow group">
              <div className="flex items-center gap-3">
                <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
                  payment.status === 'completed' ? 'bg-green-100 dark:bg-green-900/30' :
                  payment.status === 'pending' ? 'bg-yellow-100 dark:bg-yellow-900/30' : 'bg-red-100 dark:bg-red-900/30'
                }`}>
                  {payment.status === 'completed' ? (
                    <CheckCircle className="text-green-600 dark:text-green-400" size={20} />
                  ) : payment.status === 'pending' ? (
                    <Loader2 className="text-yellow-600 dark:text-yellow-400 animate-spin" size={20} />
                  ) : (
                    <X className="text-red-600 dark:text-red-400" size={20} />
                  )}
                </div>
                <div>
                  <p className="font-bold text-text">${payment.amount.toFixed(2)}</p>
                  <p className="text-xs text-text-muted uppercase font-black tracking-tight">{payment.fee_name}</p>
                </div>
              </div>
              <div className="text-right">
                <p className={`text-[0.65rem] font-black uppercase tracking-widest ${
                  payment.status === 'completed' ? 'text-green-600 dark:text-green-400' :
                  payment.status === 'pending' ? 'text-yellow-600 dark:text-yellow-400' : 'text-red-600 dark:text-red-400'
                }`}>
                  {payment.status}
                </p>
                <p className="text-[0.6rem] text-text-muted font-bold font-mono">
                  {new Date(payment.created_at).toLocaleDateString()}
                </p>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="text-center py-10 text-text-muted/30 border-2 border-dashed border-border rounded-xl">
          <CreditCard size={48} className="mx-auto mb-2 opacity-20" />
          <p className="text-xs font-bold uppercase tracking-widest">No payment history found</p>
        </div>
      )}
    </div>
  );
}
