import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Plus, Search, RefreshCw, AlertCircle, Loader2, X,
  MapPin, CalendarDays, Users, Hash, ChevronLeft, ChevronRight,
  Eye, Pencil, Trash2, Bus, Wallet,
} from 'lucide-react';
import { useFinanceStore, Trip } from '../../store/finance';
import { Modal, ModalBody } from '../../components/ui/Modal';

const PAGE_SIZE = 25;

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 === 'published') return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-300';
  if (s === 'completed') return 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300';
  if (s === 'cancelled') return 'bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-900/20 dark:text-rose-300';
  if (s === 'closed') return 'bg-muted text-text-muted border-border';
  return 'bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-300';
};

export default function Trips() {
  const navigate = useNavigate();
  const {
    trips, loading, error, fetchTrips, createTrip, updateTrip, deleteTrip,
  } = useFinanceStore();

  const [status, setStatus] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [editor, setEditor] = useState<{ row?: Trip; creating?: boolean } | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<Trip | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    fetchTrips({ status: status || undefined });
  }, [status, fetchTrips]);

  const filtered = useMemo(() => {
    if (!search.trim()) return trips;
    const needle = search.toLowerCase();
    return trips.filter((t) =>
      (t.name || '').toLowerCase().includes(needle) ||
      (t.destination || '').toLowerCase().includes(needle)
    );
  }, [trips, search]);

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

  const totals = useMemo(() => {
    let billedCount = 0;
    let paidCount = 0;
    let collected = 0;
    let outstanding = 0;
    filtered.forEach((t) => {
      billedCount += t.billed_count || 0;
      paidCount += t.paid_count || 0;
      collected += Number(t.collected) || 0;
    });
    return { billedCount, paidCount, collected, outstanding };
  }, [filtered]);

  const save = async (data: Partial<Trip>) => {
    setBusy(true);
    if (editor?.row && !editor.creating) {
      const r = await updateTrip(editor.row.uid, data);
      setBusy(false);
      if (r) setEditor(null);
    } else {
      const r = await createTrip(data);
      setBusy(false);
      if (r) {
        setEditor(null);
        navigate(`/finance/trips/${r.uid}`);
      }
    }
  };

  const onDelete = async (t: Trip) => {
    setBusy(true);
    const ok = await deleteTrip(t.uid);
    setBusy(false);
    if (ok) setConfirmDelete(null);
  };

  return (
    <div className="space-y-6 animate-in fade-in duration-300 pb-10">
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">School Trips</h1>
          <p className="text-text-muted mt-1 text-lg">Plan trips, bill participating students, track collections.</p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => fetchTrips()}
            className="flex items-center gap-2 px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all"
          >
            <RefreshCw size={16} /> Refresh
          </button>
          <button
            onClick={() => setEditor({ creating: 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]"
          >
            <Plus size={18} /> New Trip
          </button>
        </div>
      </div>

      {/* Summary tiles */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <SummaryTile icon={Bus} label="Active trips" value={filtered.length} />
        <SummaryTile icon={Users} label="Students billed" value={totals.billedCount} />
        <SummaryTile icon={Hash} label="Students paid" value={totals.paidCount} tone="emerald" />
        <SummaryTile icon={Wallet} label="Collected" value={currency(totals.collected)} tone="emerald" />
      </div>

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
          <div className="relative sm:col-span-2">
            <Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <input
              type="text"
              placeholder="Search trip name, destination…"
              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); 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 statuses</option>
            {['draft', 'published', 'closed', 'completed', 'cancelled'].map((s) => (
              <option key={s} value={s}>{s}</option>
            ))}
          </select>
        </div>
      </div>

      {error && (
        <div className="bg-red-50 dark:bg-red-950/30 border border-red-200 dark:border-red-900 rounded-2xl p-4 flex items-center gap-3 text-red-700 dark:text-red-300">
          <AlertCircle size={18} />
          <span className="text-sm">{error}</span>
        </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">Trip</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Dates</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Cost / student</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Billed / paid</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Collected</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">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((t) => (
                  <tr key={t.uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="p-1.5 rounded-md bg-primary/10 text-primary"><Bus size={14} /></div>
                        <div>
                          <p className="text-[0.85rem] font-semibold text-text">{t.name}</p>
                          <p className="text-[0.65rem] text-text-muted">{t.destination || '—'}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary whitespace-nowrap">
                      <span className="inline-flex items-center gap-1 text-text-muted">
                        <CalendarDays size={12} />
                        {(t.departure_date || '?')} → {(t.return_date || '?')}
                      </span>
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-text whitespace-nowrap">
                      {currency(Number(t.cost_per_student))}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] text-text-secondary whitespace-nowrap">
                      {t.billed_count || 0} / {t.paid_count || 0}
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-black text-emerald-600 whitespace-nowrap">
                      {currency(Number(t.collected) || 0)}
                    </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(t.status)}`}>{t.status}</span>
                    </td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-1">
                        <button onClick={() => navigate(`/finance/trips/${t.uid}`)} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="View trip" aria-label="View trip">
                          <Eye size={16} />
                        </button>
                        <button onClick={() => setEditor({ row: t, creating: false })} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="Edit trip" aria-label="Edit trip">
                          <Pencil size={16} />
                        </button>
                        <button onClick={() => setConfirmDelete(t)} className="p-2 rounded-lg hover:bg-red-500 hover:text-white text-text-muted transition-all" title="Delete trip" aria-label="Delete trip">
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={7} className="px-6 py-10 text-center text-text-muted text-sm">No trips match the current filters.</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>

      {editor && (
        <TripEditor
          initial={editor.row}
          isCreating={!!editor.creating}
          busy={busy}
          onSave={save}
          onClose={() => setEditor(null)}
        />
      )}

      {confirmDelete && (
        <Modal
          open={true}
          onClose={() => setConfirmDelete(null)}
          title="Delete trip?"
          icon={Trash2}
          maxWidth="max-w-sm"
          footer={
            <>
              <button onClick={() => setConfirmDelete(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={() => onDelete(confirmDelete)} disabled={busy} className="px-4 py-2 rounded-xl bg-red-500 text-white text-sm font-bold hover:bg-red-600 transition-all">{busy ? <Loader2 size={14} className="animate-spin" /> : 'Delete'}</button>
            </>
          }
        >
          <ModalBody>
            <p className="text-sm text-text-muted">Delete <strong>{confirmDelete.name}</strong>? Blocked if any student has already paid.</p>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}

function SummaryTile({
  icon: Icon, label, value, tone,
}: {
  icon: typeof Bus;
  label: string;
  value: string | number;
  tone?: 'emerald' | 'blue';
}) {
  const colorCls =
    tone === 'emerald' ? 'text-emerald-600'
    : tone === 'blue'   ? 'text-blue-600'
    : 'text-text';
  return (
    <div className="bg-card border border-border rounded-2xl p-4 shadow-sm">
      <div className="flex items-center gap-2 mb-1">
        <Icon size={14} className="text-text-muted" />
        <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
      </div>
      <p className={`text-2xl font-black ${colorCls}`}>{value}</p>
    </div>
  );
}

function TripEditor({
  initial, isCreating, busy, onSave, onClose,
}: {
  initial?: Trip;
  isCreating: boolean;
  busy: boolean;
  onSave: (data: Partial<Trip>) => Promise<unknown>;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial?.name || '');
  const [destination, setDestination] = useState(initial?.destination || '');
  const [departure, setDeparture] = useState(initial?.departure_date || '');
  const [returnDate, setReturn] = useState(initial?.return_date || '');
  const [cost, setCost] = useState(String(initial?.cost_per_student ?? 0));
  const [capacity, setCapacity] = useState(String(initial?.total_capacity ?? ''));
  const [status, setStatus] = useState<Trip['status']>(initial?.status || 'draft');
  const [description, setDescription] = useState(initial?.description || '');

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    await onSave({
      name: name.trim(),
      destination: destination.trim() || null,
      departure_date: departure || null,
      return_date: returnDate || null,
      cost_per_student: Number(cost) || 0,
      total_capacity: capacity === '' ? null : Number(capacity),
      status,
      description: description.trim() || null,
    } as any);
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={isCreating ? 'New trip' : `Edit ${initial?.name}`}
      icon={Bus}
      maxWidth="max-w-xl"
      footer={
        <>
          <button type="button" onClick={onClose} className="px-4 py-2 rounded-xl border border-border text-text text-sm font-bold hover:bg-muted transition-all">Cancel</button>
          <button type="submit" form="trip-form" disabled={busy || !name.trim()} className="flex items-center gap-2 px-4 py-2 rounded-xl bg-primary text-white text-sm font-bold hover:bg-primary-dark disabled:opacity-40 transition-all">
            {busy && <Loader2 size={14} className="animate-spin" />}
            <span>{isCreating ? 'Create' : 'Save'}</span>
          </button>
        </>
      }
    >
      <ModalBody>
        <form id="trip-form" onSubmit={submit}>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            <Field label="Name *" icon={Bus} value={name} onChange={setName} required />
            <Field label="Destination" icon={MapPin} value={destination} onChange={setDestination} />
            <Field label="Departure" icon={CalendarDays} type="date" value={departure} onChange={setDeparture} />
            <Field label="Return" icon={CalendarDays} type="date" value={returnDate} onChange={setReturn} />
            <Field label="Cost / student" icon={Hash} type="number" value={cost} onChange={setCost} />
            <Field label="Capacity" icon={Users} type="number" value={capacity} onChange={setCapacity} />
          </div>
          <label className="block mt-3">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Status</span>
            <select value={status} onChange={(e) => setStatus(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">
              {['draft', 'published', 'closed', 'completed', 'cancelled'].map((s) => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </label>
          <label className="block mt-3">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Description</span>
            <textarea rows={3} value={description} onChange={(e) => setDescription(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>
        </form>
      </ModalBody>
    </Modal>
  );
}

function Field({
  icon: Icon, label, value, onChange, type = 'text', required,
}: {
  icon: typeof Bus; label: string; value: string; onChange: (v: string) => void;
  type?: string; required?: boolean;
}) {
  return (
    <label className="block">
      <span className="text-xs font-bold uppercase tracking-wider text-text-muted flex items-center gap-1">
        <Icon size={12} /> {label}
      </span>
      <input
        type={type}
        required={required}
        value={value}
        onChange={(e) => onChange(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>
  );
}
