import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ArrowLeft, AlertCircle, Loader2, RefreshCw,
  Wallet, Search, DollarSign, ChevronLeft, ChevronRight,
  Bus, CalendarDays,
} from 'lucide-react';
import { useFinanceStore } from '../../store/finance';
import { Modal, ModalBody } from '../../components/ui/Modal';

const currency = (n: number) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(Number.isFinite(n) ? n : 0);

const statusBadge = (status: string) => {
  const s = status.toLowerCase();
  if (s === 'paid') return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300';
  if (s === 'partial') return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
  if (s === 'refunded') return 'bg-indigo-50 text-indigo-700 border-indigo-200 dark:bg-indigo-900/20 dark:text-indigo-300';
  if (s === 'cancelled') return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300';
  return 'bg-muted text-text-muted border-border';
};

export default function TripDetail() {
  const { uid } = useParams<{ uid: string }>();
  const navigate = useNavigate();
  const { currentTrip, fetchTrip, payTripStudent, assignTripStudents } = useFinanceStore();
  const [status, setStatus] = useState<'all' | 'pending' | 'partial' | 'paid' | 'refunded'>('all');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [paying, setPaying] = useState<{ uid: string; amount: number } | null>(null);
  const [payAmount, setPayAmount] = useState('');
  const [payMethod, setPayMethod] = useState('cash');
  const [payReference, setPayReference] = useState('');
  const [banner, setBanner] = useState<{ kind: 'ok' | 'err'; msg: string } | null>(null);
  const [assignModal, setAssignModal] = useState(false);
  const [assignMode, setAssignMode] = useState<'ids' | 'class' | 'all'>('all');
  const [assignClassId, setAssignClassId] = useState('');
  const [assignStudentUids, setAssignStudentUids] = useState('');

  useEffect(() => {
    if (uid) fetchTrip(uid);
  }, [uid, fetchTrip]);

  if (!currentTrip) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
        <AlertCircle size={32} className="text-rose-500" />
        <p>Trip not found.</p>
        <button onClick={() => navigate('/finance/trips')} className="px-4 py-2 bg-primary text-white rounded-xl">Back to trips</button>
      </div>
    );
  }

  const students = currentTrip.students || [];
  const filtered = students.filter((s) => {
    if (status !== 'all' && s.status !== status) return false;
    if (!search.trim()) return true;
    const name = `${s.first_name || ''} ${s.last_name || ''}`.toLowerCase();
    return name.includes(search.toLowerCase()) || (s.email || '').toLowerCase().includes(search.toLowerCase());
  });

  const PAGE_SIZE = 25;
  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const pageRows = filtered.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE);

  const counts = {
    paid: students.filter((s) => s.status === 'paid').length,
    partial: students.filter((s) => s.status === 'partial').length,
    pending: students.filter((s) => s.status === 'pending').length,
    total: students.length,
  };
  const collected = students.reduce((s, st) => s + Number(st.paid_amount || 0), 0);
  const invoiced = students.reduce((s, st) => s + Number(st.invoiced_amount || 0), 0);

  const onPayClick = (studentUid: string, invoicedAmount: number) => {
    setPaying({ uid: studentUid, amount: invoicedAmount });
    setPayAmount(String(invoicedAmount));
    setPayReference('');
    setBanner(null);
  };

  const onConfirmPay = async () => {
    if (!paying) return;
    const amt = Number(payAmount);
    if (!Number.isFinite(amt) || amt <= 0) { setBanner({ kind: 'err', msg: 'amount must be > 0' }); return; }
    const r = await payTripStudent(currentTrip.uid, paying.uid, {
      amount: amt,
      payment_method: payMethod,
      reference_number: payReference || `TRIP-${currentTrip.id}-${Date.now()}`,
    });
    if (r) {
      setBanner({ kind: 'ok', msg: `Recorded $${amt.toFixed(2)} payment.` });
      setPaying(null);
      await fetchTrip(currentTrip.uid);
    } else {
      setBanner({ kind: 'err', msg: 'Failed to record payment.' });
    }
  };

  const onAssign = async () => {
    const body: any = { mode: assignMode };
    if (assignMode === 'ids') {
      const uids = assignStudentUids.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
      if (uids.length === 0) { setBanner({ kind: 'err', msg: 'Enter at least one student UID.' }); return; }
      body.student_uids = uids;
    } else if (assignMode === 'class') {
      if (!assignClassId) { setBanner({ kind: 'err', msg: 'Pick a class.' }); return; }
      body.class_id = Number(assignClassId);
    }
    const r = await assignTripStudents(currentTrip.uid, body);
    if (r) {
      setBanner({ kind: 'ok', msg: `Added ${r.added} student(s); skipped ${r.skipped}.` });
      setAssignModal(false);
      await fetchTrip(currentTrip.uid);
    } else {
      setBanner({ kind: 'err', msg: 'Failed to assign.' });
    }
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex items-center gap-3">
        <button onClick={() => navigate('/finance/trips')} className="flex items-center gap-1 text-sm font-bold text-text-muted hover:text-text">
          <ArrowLeft size={16} /> Back to trips
        </button>
        <button onClick={() => fetchTrip(currentTrip.uid)} className="flex items-center gap-2 px-3 py-1.5 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">
          <RefreshCw size={14} /> Refresh
        </button>
      </div>

      <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="flex items-center gap-3">
            <div className="p-3 rounded-xl bg-primary/10 text-primary">
              <Bus size={24} />
            </div>
            <div>
              <h1 className="text-3xl font-black text-text tracking-tight">{currentTrip.name}</h1>
              <p className="text-sm text-text-muted mt-1">
                <span className="inline-flex items-center gap-1"><CalendarDays size={12} /> {currentTrip.departure_date || '?'} → {currentTrip.return_date || '?'}</span>
                {currentTrip.destination && ` · ${currentTrip.destination}`}
              </p>
              {currentTrip.description && <p className="text-xs text-text-muted italic mt-1">{currentTrip.description}</p>}
            </div>
          </div>
          <button
            onClick={() => setAssignModal(true)}
            className="flex items-center gap-2 bg-primary hover:bg-primary-dark text-white px-5 py-2.5 rounded-xl font-semibold transition-all shadow-lg shadow-blue-900/10 active:scale-[0.98]"
          >
            <DollarSign size={16} /> Assign students
          </button>
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Summary label="Students" value={counts.total} />
        <Summary label="Paid" value={counts.paid} tone="emerald" />
        <Summary label="Partial / pending" value={counts.partial + counts.pending} tone="amber" />
        <Summary label="Collected / invoiced" value={`${currency(collected)} / ${currency(invoiced)}`} tone="emerald" />
      </div>

      {banner && (
        <div className={`rounded-2xl border p-4 flex items-center gap-3 text-sm ${
          banner.kind === 'ok'
            ? 'bg-emerald-50 border-emerald-200 text-emerald-700 dark:bg-emerald-950/30 dark:border-emerald-900 dark:text-emerald-300'
            : 'bg-red-50 border-red-200 text-red-700 dark:bg-red-950/30 dark:border-red-900 dark:text-red-300'
        }`}>
          {banner.kind === 'ok' ? <Wallet size={18} /> : <AlertCircle size={18} />}
          <span className="flex-1">{banner.msg}</span>
          <button onClick={() => setBanner(null)} className="text-xs font-bold underline">Dismiss</button>
        </div>
      )}

      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div className="relative">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search student name or email…"
              value={search}
              onChange={(e) => { setSearch(e.target.value); setPage(0); }}
              className="w-full pl-9 pr-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
            />
          </div>
          <select
            value={status}
            onChange={(e) => { setStatus(e.target.value as any); setPage(0); }}
            className="px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
          >
            <option value="all">All statuses</option>
            <option value="pending">Pending</option>
            <option value="partial">Partial</option>
            <option value="paid">Paid</option>
            <option value="refunded">Refunded</option>
            <option value="cancelled">Cancelled</option>
          </select>
        </div>
      </div>

      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="overflow-x-auto">
          <table className="w-full text-left">
            <thead className="bg-muted/80 border-b border-border">
              <tr>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Student</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Invoiced</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Paid</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Outstanding</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Status</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Action</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((s) => {
                  const remaining = Math.max(0, Number(s.invoiced_amount) - Number(s.paid_amount));
                  return (
                    <tr key={s.uid} className="hover:bg-muted/40 transition-colors">
                      <td className="px-6 py-4">
                        <p className="text-[0.85rem] font-semibold text-text">{s.first_name} {s.last_name}</p>
                        <p className="text-[0.65rem] text-text-muted">{s.email}</p>
                      </td>
                      <td className="px-6 py-4 text-right text-[0.85rem] font-mono text-text">{currency(Number(s.invoiced_amount))}</td>
                      <td className="px-6 py-4 text-right text-[0.85rem] font-mono text-emerald-600">{currency(Number(s.paid_amount))}</td>
                      <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-rose-500">{currency(remaining)}</td>
                      <td className="px-6 py-4">
                        <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${statusBadge(s.status)}`}>{s.status}</span>
                      </td>
                      <td className="px-6 py-4 text-right">
                        {(s.status === 'pending' || s.status === 'partial') && (
                          <button
                            onClick={() => onPayClick(s.uid, remaining)}
                            className="flex items-center gap-1 px-3 py-1.5 rounded-xl bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-bold transition-all"
                          >
                            <DollarSign size={14} /> {remaining > 0 ? 'Record payment' : 'Mark paid'}
                          </button>
                        )}
                      </td>
                    </tr>
                  );
                })
              ) : (
                <tr><td colSpan={6} className="px-6 py-10 text-center text-text-muted text-sm">No students assigned yet — use "Assign students" above.</td></tr>
              )}
            </tbody>
          </table>
        </div>
        <div className="px-6 py-4 border-t border-border bg-muted/30 flex items-center justify-between">
          <span className="text-[0.7rem] font-bold text-text-muted">Page {page + 1} of {totalPages}</span>
          <div className="inline-flex items-center gap-2">
            <button disabled={page === 0} onClick={() => setPage((p) => Math.max(0, p - 1))} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              <ChevronLeft size={14} /> Prev
            </button>
            <button disabled={page + 1 >= totalPages} onClick={() => setPage((p) => p + 1)} className="flex items-center gap-1 px-3 py-1.5 rounded-lg border border-border bg-card text-xs font-bold disabled:opacity-40 hover:bg-muted transition-all">
              Next <ChevronRight size={14} />
            </button>
          </div>
        </div>
      </div>

      {paying && (
        <Modal
          open={true}
          onClose={() => setPaying(null)}
          title="Record trip payment"
          icon={DollarSign}
          maxWidth="max-w-md"
          footer={
            <>
              <button onClick={() => setPaying(null)} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
              <button onClick={onConfirmPay} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-emerald-500 text-white text-sm font-bold hover:bg-emerald-600 transition-all">
                <DollarSign size={14} /> Record
              </button>
            </>
          }
        >
          <ModalBody>
            <p className="text-sm text-text-muted mb-3">
              Recording payment of up to <strong>{currency(paying.amount)}</strong> remaining for this student.
            </p>
            <label className="block mt-2">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Amount</span>
              <input type="number" min={0} value={payAmount} onChange={(e) => setPayAmount(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
            </label>
            <label className="block mt-3">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Method</span>
              <select value={payMethod} onChange={(e) => setPayMethod(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
                {['cash', 'bank', 'paynow', 'ecocash', 'internal_transfer'].map((m) => <option key={m}>{m}</option>)}
              </select>
            </label>
            <label className="block mt-3">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Reference</span>
              <input value={payReference} onChange={(e) => setPayReference(e.target.value)} placeholder="Optional receipt #" className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
            </label>
          </ModalBody>
        </Modal>
      )}

      {assignModal && (
        <Modal
          open={true}
          onClose={() => setAssignModal(false)}
          title="Assign students to trip"
          icon={DollarSign}
          maxWidth="max-w-md"
          footer={
            <>
              <button onClick={() => setAssignModal(false)} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
              <button onClick={onAssign} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark transition-all">
                <DollarSign size={14} /> Assign
              </button>
            </>
          }
        >
          <ModalBody>
            <p className="text-sm text-text-muted mb-3">
              Each student gets a <strong>{currency(Number(currentTrip.cost_per_student))}</strong> trip_payments row.
            </p>
            <label className="block">
              <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Mode</span>
              <select value={assignMode} onChange={(e) => setAssignMode(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30">
                <option value="all">All students</option>
                <option value="class">By class ID</option>
                <option value="ids">By student UIDs</option>
              </select>
            </label>
            {assignMode === 'class' && (
              <label className="block mt-3">
                <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Class ID</span>
                <input type="number" min={1} value={assignClassId} onChange={(e) => setAssignClassId(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
              </label>
            )}
            {assignMode === 'ids' && (
              <label className="block mt-3">
                <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Student UIDs (comma- or whitespace-separated)</span>
                <textarea rows={4} value={assignStudentUids} onChange={(e) => setAssignStudentUids(e.target.value)} className="mt-1 w-full px-3 py-2 bg-muted/30 border border-border rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-primary/30" />
              </label>
            )}
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}

function Summary({ label, value, tone }: { label: string; value: string | number; tone?: 'emerald' | 'amber' }) {
  const colorCls = tone === 'emerald' ? 'text-emerald-600' : tone === 'amber' ? 'text-amber-600' : 'text-text';
  return (
    <div className="bg-card border border-border rounded-2xl p-4 shadow-sm">
      <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
      <p className={`text-2xl font-black mt-1 ${colorCls}`}>{value}</p>
    </div>
  );
}
