import React, { useState } from 'react';
import { useCollege } from '../context/CollegeContext';
import {
  X,
  CreditCard,
  Building,
  CheckCircle2,
  AlertCircle,
  FileCheck,
  Upload,
  Lock,
  Unlock,
  Receipt,
  Info,
  DollarSign,
  ShieldCheck,
} from 'lucide-react';
import confetti from 'canvas-confetti';

interface BankPaymentModalProps {
  isOpen: boolean;
  onClose: () => void;
  defaultStudentId?: string;
}

export const BankPaymentModal: React.FC<BankPaymentModalProps> = ({
  isOpen,
  onClose,
  defaultStudentId,
}) => {
  const { currentUser, fees, submitBankDepositSlip, quickClearFeeBalance, isResultsLocked } = useCollege();

  // Find targeted student
  const activeStudentId = defaultStudentId || (currentUser.role === 'student' ? currentUser.studentId : currentUser.role === 'parent' ? currentUser.studentId : 'STC/2026/ICT-108') || 'STC/2026/ICT-108';
  const targetFee = fees.find(f => f.studentId === activeStudentId) || fees[1] || fees[0];

  const [paymentAmount, setPaymentAmount] = useState<number>(targetFee ? targetFee.balanceDue : 54000);
  const [bankRefNumber, setBankRefNumber] = useState('');
  const [depositDate, setDepositDate] = useState(new Date().toISOString().split('T')[0]);
  const [depositNotes, setDepositNotes] = useState('');
  const [successMessage, setSuccessMessage] = useState('');
  const [activeTab, setActiveTab] = useState<'upload' | 'ledger' | 'instructions'>('upload');

  if (!isOpen) return null;

  const handleDepositSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!bankRefNumber) {
      alert('Please enter the National Bank deposit slip reference number.');
      return;
    }

    submitBankDepositSlip(targetFee.studentId, {
      amount: Number(paymentAmount),
      bankRefNumber,
      depositDate,
      bankName: 'National Bank of Malawi',
      serviceCentre: 'Customs Road',
      notes: depositNotes || `Tuition fee payment for ${targetFee.studentName}`,
    });

    setSuccessMessage(`Bank deposit slip (Ref: ${bankRefNumber}, MK ${Number(paymentAmount).toLocaleString()}) submitted to the Accounts Office for verification.`);
    try {
      confetti({ particleCount: 50, spread: 60 });
    } catch (e) {}
  };

  const handleInstantClear = () => {
    quickClearFeeBalance(targetFee.studentId);
    setSuccessMessage(`Fee balance cleared in full! Official examination results and transcripts are now immediately unlocked.`);
    try {
      confetti({ particleCount: 80, spread: 70 });
    } catch (e) {}
  };

  const lockStatus = isResultsLocked(targetFee?.studentId);

  return (
    <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur-sm flex items-center justify-center p-2 sm:p-4 overflow-y-auto">
      <div className="bg-white rounded-2xl shadow-2xl max-w-2xl w-full max-h-[92vh] flex flex-col overflow-hidden border border-slate-200 animate-in fade-in zoom-in-95">
        
        {/* Modal Top Bar */}
        <div className="bg-slate-900 text-white px-6 py-4 flex items-center justify-between border-b border-slate-800 shrink-0">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-lg bg-amber-500 border border-amber-400 flex items-center justify-center font-bold text-slate-950 shadow-sm">
              <CreditCard className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base font-bold tracking-tight text-white leading-tight">
                Official Bank Payment Portal
              </h2>
              <p className="text-xs text-amber-300 font-mono">
                National Bank of Malawi • Account: 1003452219
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            aria-label="Close modal"
            className="p-1.5 text-slate-400 hover:text-white hover:bg-slate-800 rounded-lg transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Tab Navigation */}
        <div className="flex border-b border-slate-200 bg-slate-50 px-6 pt-3 gap-3 shrink-0">
          <button
            onClick={() => setActiveTab('upload')}
            className={`pb-2.5 text-xs font-bold transition border-b-2 ${
              activeTab === 'upload'
                ? 'border-emerald-600 text-emerald-700'
                : 'border-transparent text-slate-500 hover:text-slate-800'
            }`}
          >
            Submit Deposit Slip
          </button>
          <button
            onClick={() => setActiveTab('ledger')}
            className={`pb-2.5 text-xs font-bold transition border-b-2 ${
              activeTab === 'ledger'
                ? 'border-emerald-600 text-emerald-700'
                : 'border-transparent text-slate-500 hover:text-slate-800'
            }`}
          >
            Payment Ledger & Slips
          </button>
          <button
            onClick={() => setActiveTab('instructions')}
            className={`pb-2.5 text-xs font-bold transition border-b-2 ${
              activeTab === 'instructions'
                ? 'border-emerald-600 text-emerald-700'
                : 'border-transparent text-slate-500 hover:text-slate-800'
            }`}
          >
            College Payment Policy
          </button>
        </div>

        {/* Modal Body */}
        <div className="flex-1 overflow-y-auto p-4 sm:p-6 space-y-5">
          
          {/* Target Student Fee Balance Snapshot */}
          <div className={`p-4 rounded-xl border flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 ${
            targetFee.balanceDue === 0
              ? 'bg-emerald-50 border-emerald-300 text-emerald-950'
              : 'bg-amber-50 border-amber-300 text-amber-950'
          }`}>
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <span className="font-bold text-sm">{targetFee.studentName}</span>
                <span className="text-xs font-mono bg-white px-2 py-0.5 rounded border border-slate-300">
                  {targetFee.studentId}
                </span>
              </div>
              <p className="text-xs text-slate-600">{targetFee.courseName}</p>
              
              <div className="flex items-center gap-2 pt-1 text-xs">
                {lockStatus.isLocked ? (
                  <span className="inline-flex items-center gap-1 font-semibold text-rose-700 bg-rose-100 px-2 py-0.5 rounded border border-rose-300">
                    <Lock className="w-3 h-3" />
                    Exam Results Locked (Fee Balance Due)
                  </span>
                ) : (
                  <span className="inline-flex items-center gap-1 font-semibold text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded border border-emerald-300">
                    <Unlock className="w-3 h-3" />
                    Fees Cleared (Results Accessible)
                  </span>
                )}
              </div>
            </div>

            <div className="text-left sm:text-right border-t sm:border-t-0 pt-2 sm:pt-0 w-full sm:w-auto">
              <span className="text-[11px] text-slate-500 block uppercase font-semibold">Outstanding Balance</span>
              <span className="text-xl font-bold font-mono text-slate-900">
                MK {targetFee.balanceDue.toLocaleString()}
              </span>
              <span className="text-[10px] text-slate-500 block">Total Due: MK {targetFee.totalAmountDue.toLocaleString()}</span>
            </div>
          </div>

          {successMessage && (
            <div className="p-3 bg-emerald-50 border border-emerald-300 rounded-xl text-xs font-medium text-emerald-900 flex items-start gap-2 animate-in fade-in">
              <CheckCircle2 className="w-4 h-4 text-emerald-600 shrink-0 mt-0.5" />
              <div>
                <p className="font-bold">Success!</p>
                <p>{successMessage}</p>
              </div>
            </div>
          )}

          {activeTab === 'upload' && (
            <div className="space-y-4">
              
              {/* National Bank Details Box */}
              <div className="bg-slate-900 text-white rounded-xl p-4 space-y-3 shadow-md">
                <div className="flex items-center justify-between border-b border-slate-800 pb-2">
                  <span className="text-xs font-bold text-amber-400 uppercase tracking-wider flex items-center gap-1.5">
                    <Building className="w-3.5 h-3.5" />
                    Official Bank Account Details
                  </span>
                  <span className="text-[10px] bg-slate-800 px-2 py-0.5 rounded text-slate-300 font-mono">
                    National Bank of Malawi
                  </span>
                </div>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-xs">
                  <div>
                    <span className="text-slate-400 text-[11px] block">Service Centre:</span>
                    <span className="font-semibold text-white">Customs Road</span>
                  </div>
                  <div>
                    <span className="text-slate-400 text-[11px] block">Account Name:</span>
                    <span className="font-semibold text-white">Soche Technical College</span>
                  </div>
                  <div className="col-span-2">
                    <span className="text-slate-400 text-[11px] block">Account Number:</span>
                    <span className="font-mono font-bold text-emerald-400 text-sm">1003452219</span>
                  </div>
                </div>
              </div>

              {/* Upload Deposit Slip Form */}
              <form onSubmit={handleDepositSubmit} className="space-y-4 text-xs">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block font-semibold text-slate-700 mb-1">
                      AMOUNT DEPOSITED (MWK) *
                    </label>
                    <input
                      type="number"
                      required
                      min={1000}
                      value={paymentAmount}
                      onChange={e => setPaymentAmount(Number(e.target.value))}
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono font-bold text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                    />
                  </div>

                  <div>
                    <label className="block font-semibold text-slate-700 mb-1">
                      BANK DEPOSIT SLIP REF / TELLER NO *
                    </label>
                    <input
                      type="text"
                      required
                      placeholder="e.g. NB-LIMBE-894211"
                      value={bankRefNumber}
                      onChange={e => setBankRefNumber(e.target.value)}
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg font-mono text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                    />
                  </div>

                  <div>
                    <label className="block font-semibold text-slate-700 mb-1">
                      DATE OF BANK DEPOSIT
                    </label>
                    <input
                      type="date"
                      value={depositDate}
                      onChange={e => setDepositDate(e.target.value)}
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                    />
                  </div>

                  <div>
                    <label className="block font-semibold text-slate-700 mb-1">
                      PAYMENT PURPOSE / NOTES
                    </label>
                    <input
                      type="text"
                      placeholder="e.g. 30% Final Tuition balance"
                      value={depositNotes}
                      onChange={e => setDepositNotes(e.target.value)}
                      className="w-full px-3 py-2 border border-slate-300 rounded-lg text-slate-900 focus:ring-2 focus:ring-emerald-500 focus:outline-none"
                    />
                  </div>
                </div>

                {/* Slip attachment preview */}
                <div className="p-3 bg-slate-50 border border-slate-200 rounded-lg flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Upload className="w-4 h-4 text-emerald-600" />
                    <span className="text-slate-700 font-medium">Bank Slip Scanned Attachment (Auto-generated demo)</span>
                  </div>
                  <span className="text-[11px] font-mono text-emerald-700 bg-emerald-100 px-2 py-0.5 rounded font-semibold">
                    deposit_slip_verified.jpg
                  </span>
                </div>

                <div className="flex flex-col sm:flex-row items-center justify-between gap-3 pt-3 border-t border-slate-200">
                  {/* Quick Demo Simulator CTA */}
                  <button
                    type="button"
                    onClick={handleInstantClear}
                    className="w-full sm:w-auto px-3.5 py-2 bg-amber-100 hover:bg-amber-200 text-amber-900 font-semibold rounded-lg transition text-xs border border-amber-300 flex items-center justify-center gap-1.5"
                  >
                    <Unlock className="w-3.5 h-3.5" />
                    Instant Clear Balance (Demo Bypass)
                  </button>

                  <button
                    type="submit"
                    className="w-full sm:w-auto px-5 py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg transition shadow flex items-center justify-center gap-1.5"
                  >
                    <FileCheck className="w-4 h-4" />
                    Submit Bank Slip for Clearance
                  </button>
                </div>
              </form>
            </div>
          )}

          {activeTab === 'ledger' && (
            <div className="space-y-4">
              <h4 className="font-bold text-xs text-slate-700 uppercase tracking-wider">
                Transaction History & Verified Receipts
              </h4>

              <div className="space-y-3">
                {targetFee.bankDepositSlips.map(slip => (
                  <div
                    key={slip.id}
                    className="border border-slate-200 rounded-xl p-4 bg-slate-50 flex flex-col sm:flex-row sm:items-center justify-between gap-3 text-xs"
                  >
                    <div className="space-y-1">
                      <div className="flex items-center gap-2">
                        <span className="font-bold font-mono text-slate-900">
                          Ref: {slip.bankRefNumber}
                        </span>
                        <span className={`px-2 py-0.5 rounded text-[10px] font-bold ${
                          slip.status === 'Verified'
                            ? 'bg-emerald-100 text-emerald-900 border border-emerald-300'
                            : slip.status === 'Pending Review'
                            ? 'bg-amber-100 text-amber-900 border border-amber-300'
                            : 'bg-rose-100 text-rose-900'
                        }`}>
                          {slip.status}
                        </span>
                      </div>
                      <p className="text-slate-600">{slip.bankName} - {slip.serviceCentre} ({slip.depositDate})</p>
                      {slip.receiptNumber && (
                        <p className="text-emerald-700 font-mono text-[11px] font-medium flex items-center gap-1">
                          <Receipt className="w-3 h-3" />
                          Official Receipt: {slip.receiptNumber}
                        </p>
                      )}
                      {slip.notes && <p className="text-slate-500 italic text-[11px]">Note: {slip.notes}</p>}
                    </div>

                    <div className="text-left sm:text-right">
                      <span className="text-sm font-bold font-mono text-emerald-700 block">
                        MK {slip.amount.toLocaleString()}
                      </span>
                      <span className="text-[10px] text-slate-400">Uploaded {slip.uploadedAt}</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {activeTab === 'instructions' && (
            <div className="space-y-3 text-xs text-slate-700 leading-relaxed bg-slate-50 p-4 rounded-xl border border-slate-200">
              <h4 className="font-bold text-slate-900 uppercase tracking-wider text-xs">
                Payment Terms & Regulations (Soche Technical College)
              </h4>
              <p>
                1. <strong>Payment Schedule:</strong> Tuition fees are payable in full upon admission. Where not possible, a minimum down payment of <strong>70%</strong> is payable upon registration, with the remaining <strong>30%</strong> balance payable at month-end of the preceding month.
              </p>
              <p>
                2. <strong>Direct Bank Deposit Only:</strong> All fees must be deposited directly into <strong>National Bank of Malawi, Customs Road Service Centre, Account Name: Soche Technical College, Account Number: 1003452219</strong>.
              </p>
              <p>
                3. <strong>Examination Clearance:</strong> End of semester examination results and official transcripts are restricted until full fee clearance is stamped by the Accounts Office.
              </p>
              <p>
                4. <strong>Refund Policy:</strong> Fees once paid are non-refundable and non-transferable unless the college is unable to provide the service. When refunds are due, 10% processing fee is withheld.
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
