import { useState, useMemo } from 'react';
import { useFeeStore } from '@/stores/feeStore';
import { useStudentStore } from '@/stores/studentStore';
import { useUIStore } from '@/stores/uiStore';
import { formatCurrency } from '@/lib/formatters';
import { format } from 'date-fns';
import { Check, Loader2, X } from 'lucide-react';

export default function RecordPaymentScreen() {
  const { students } = useStudentStore();
  const { recordPayment } = useFeeStore();
  const { goBack, showToast } = useUIStore();
  const [studentId, setStudentId] = useState<number | ''>('');
  const [amount, setAmount] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('cash');
  const [paymentDate, setPaymentDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [notes, setNotes] = useState('');
  const [isSaving, setIsSaving] = useState(false);
  const [success, setSuccess] = useState(false);

  const selectedStudent = students.find(s => s.id === Number(studentId));
  const monthlyFee = selectedStudent?.monthlyFee || 0;

  const handleSave = async () => {
    if (!studentId || !amount) { showToast({ type: 'error', message: 'Fill all required fields' }); return; }
    setIsSaving(true);
    await recordPayment({
      studentId: Number(studentId),
      amount: parseFloat(amount),
      paymentMethod: paymentMethod as 'cash' | 'upi' | 'card' | 'bank_transfer' | 'other',
      paymentDate,
      notes,
      generateReceipt: true,
    });
    setIsSaving(false);
    setSuccess(true);
    showToast({ type: 'success', message: 'Payment recorded and receipt generated!' });
  };

  if (success) {
    return (
      <div className="px-4 pt-4 pb-4 flex flex-col items-center justify-center min-h-[60vh]">
        <div className="w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4">
          <Check className="w-8 h-8 text-emerald-500" />
        </div>
        <h2 className="text-xl font-bold text-gray-900">Payment Recorded!</h2>
        <p className="text-sm text-gray-500 mt-1">Receipt generated for {selectedStudent?.fullName}</p>
        <div className="w-full bg-gray-50 rounded-xl p-4 mt-6">
          <div className="flex justify-between text-sm mb-2">
            <span className="text-gray-500">Amount Paid</span>
            <span className="font-bold text-gray-900">{formatCurrency(parseFloat(amount))}</span>
          </div>
          <div className="flex justify-between text-sm">
            <span className="text-gray-500">Method</span>
            <span className="font-medium text-gray-800 capitalize">{paymentMethod}</span>
          </div>
        </div>
        <button onClick={goBack} className="mt-6 w-full py-3 brand-gradient text-white font-semibold rounded-xl button-shadow">
          Done
        </button>
      </div>
    );
  }

  return (
    <div className="px-4 pt-4 pb-4">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-lg font-bold text-gray-900">Record Payment</h2>
        <button onClick={goBack} className="p-2 -mr-2"><X className="w-5 h-5 text-gray-500" /></button>
      </div>

      <div className="space-y-4">
        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Student *</label>
          <select value={studentId} onChange={e => setStudentId(Number(e.target.value))}
            className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500">
            <option value="">Select student...</option>
            {students.filter(s => s.isActive).map(s => <option key={s.id} value={s.id}>{s.fullName} ({s.studentId})</option>)}
          </select>
        </div>

        {selectedStudent && (
          <div className="bg-gray-50 rounded-xl p-3 space-y-1.5">
            <div className="flex justify-between text-sm"><span className="text-gray-500">Monthly Fee</span><span className="font-medium">{formatCurrency(monthlyFee)}</span></div>
            <div className="border-t border-gray-200 pt-1.5 flex justify-between text-sm font-bold"><span className="text-gray-800">Total</span><span className="text-orange-600">{formatCurrency(monthlyFee)}</span></div>
          </div>
        )}

        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Amount Paid *</label>
          <div className="relative">
            <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-500 font-medium">\u20b9</span>
            <input type="number" value={amount} onChange={e => setAmount(e.target.value)}
              className="w-full h-11 pl-8 pr-4 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500" placeholder="0.00" />
          </div>
        </div>

        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Payment Method</label>
          <select value={paymentMethod} onChange={e => setPaymentMethod(e.target.value)}
            className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500">
            <option value="cash">Cash</option>
            <option value="upi">UPI</option>
            <option value="card">Card</option>
            <option value="bank_transfer">Bank Transfer</option>
            <option value="other">Other</option>
          </select>
        </div>

        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Payment Date</label>
          <input type="date" value={paymentDate} onChange={e => setPaymentDate(e.target.value)}
            className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500" />
        </div>

        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Notes</label>
          <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="Optional"
            className="w-full h-20 px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500 resize-none" />
        </div>

        <button onClick={handleSave} disabled={isSaving}
          className="w-full h-12 brand-gradient text-white font-semibold rounded-xl button-shadow flex items-center justify-center gap-2 disabled:opacity-50 active:scale-[0.98] transition-transform">
          {isSaving ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Save & Generate Receipt'}
        </button>
      </div>
    </div>
  );
}
