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

const PAGE_SIZE = 25;

const typeLabel: Record<string, string> = {
  class: 'Class',
  trip: 'Trip',
  hostel: 'Hostel',
  transport: 'Transport',
  club: 'Club',
  fee: 'Fee',
  custom: 'Custom',
};
const typeBadge: Record<string, string> = {
  class: 'bg-indigo-50 text-indigo-700 border-indigo-200',
  trip: 'bg-amber-50 text-amber-700 border-amber-200',
  hostel: 'bg-emerald-50 text-emerald-700 border-emerald-200',
  transport: 'bg-blue-50 text-blue-700 border-blue-200',
  club: 'bg-rose-50 text-rose-700 border-rose-200',
  fee: 'bg-purple-50 text-purple-700 border-purple-200',
  custom: 'bg-muted text-text-muted border-border',
};

export default function StudentGroups() {
  const navigate = useNavigate();
  const {
    studentGroups, currentGroup, busy, error,
    fetchStudentGroups, fetchStudentGroup, createStudentGroup,
    updateStudentGroup, deleteStudentGroup,
    addStudentGroupMembers, removeStudentGroupMember,
  } = useFinanceEngineStore();

  const [type, setType] = useState('');
  const [search, setSearch] = useState('');
  const [page, setPage] = useState(0);
  const [editor, setEditor] = useState<{ row?: StudentGroup; creating?: boolean } | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<StudentGroup | null>(null);
  const [assignModal, setAssignModal] = useState<StudentGroup | null>(null);
  const [banner, setBanner] = useState<{ kind: 'ok' | 'err'; msg: string } | null>(null);

  useEffect(() => {
    fetchStudentGroups({ type: type || undefined, search: search.trim() || undefined });
  }, [type, search, fetchStudentGroups]);

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

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

  const save = async (data: Partial<StudentGroup> & { auto_track_class?: boolean }) => {
    if (editor?.row && !editor.creating) {
      const r = await updateStudentGroup(editor.row.uid, data);
      if (r) setEditor(null);
    } else {
      const r = await createStudentGroup(data);
      if (r) setEditor(null);
    }
  };

  const onDelete = async (g: StudentGroup) => {
    const ok = await deleteStudentGroup(g.uid);
    if (ok) setConfirmDelete(null);
  };

  const onAssign = async (
    group: StudentGroup,
    body: { mode: 'ids' | 'class' | 'all'; student_uids?: string[]; class_id?: number },
  ) => {
    const r = await addStudentGroupMembers(group.uid, body);
    if (r) {
      setBanner({ kind: 'ok', msg: `Added ${r.added}, skipped ${r.skipped}. Total ${r.total}.` });
      // refresh detail if the user is currently viewing this group
      if (currentGroup?.uid === group.uid) await fetchStudentGroup(group.uid);
      await fetchStudentGroups({ type: type || undefined });
      setAssignModal(null);
    } 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 flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Student Groups</h1>
          <p className="text-text-muted mt-1 text-lg">
            Group students by class, bus route, hostel block, trip, or any custom cut.
          </p>
        </div>
        <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 Group
        </button>
      </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'
            : 'bg-red-50 border-red-200 text-red-700'
        }`}>
          {banner.kind === 'ok' ? <Users 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>
      )}

      {/* 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 group name…"
              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={type} onChange={(e) => { setType(e.target.value); setPage(0); }} className="px-3 py-2.5 bg-muted/30 dark:bg-background/60 border border-border rounded-xl text-sm text-text focus:outline-none focus:ring-2 focus:ring-primary/30">
            <option value="">All types</option>
            {Object.keys(typeLabel).map((t) => <option key={t} value={t}>{typeLabel[t]}</option>)}
          </select>
        </div>
        <p className="text-[0.65rem] mt-3 text-text-muted">{filtered.length} group{filtered.length === 1 ? '' : 's'}</p>
      </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">Name</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Type</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Members</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Class</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((g) => (
                  <tr key={g.uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <div className="flex items-center gap-2">
                        <div className="w-2 h-8 rounded-sm" style={{ background: g.color || '#94a3b8' }} />
                        <div>
                          <p className="text-[0.85rem] font-semibold text-text">{g.name}</p>
                          {g.description && <p className="text-[0.65rem] text-text-muted">{g.description}</p>}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4">
                      <span className={`text-[0.6rem] font-black uppercase tracking-tight px-2 py-1 rounded-full border ${typeBadge[g.type] || 'bg-muted text-text-muted'}`}>{typeLabel[g.type] || g.type}</span>
                    </td>
                    <td className="px-6 py-4 text-right text-[0.85rem] font-bold text-text">{g.member_count ?? '—'}</td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-muted">{g.class_name || (g.class_id ? `#${g.class_id}` : '—')}</td>
                    <td className="px-6 py-4 text-right whitespace-nowrap">
                      <div className="inline-flex items-center gap-1">
                        <button onClick={() => { setAssignModal(g); }} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="Add members" aria-label="Add members">
                          <UserPlus size={16} />
                        </button>
                        <button onClick={() => navigate(`/finance/groups/${g.uid}`)} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="View group" aria-label="View group">
                          <Eye size={16} />
                        </button>
                        <button onClick={() => setEditor({ row: g, creating: false })} className="p-2 rounded-lg hover:bg-primary hover:text-white text-text-muted transition-all" title="Edit" aria-label="Edit">
                          <Pencil size={16} />
                        </button>
                        <button onClick={() => setConfirmDelete(g)} className="p-2 rounded-lg hover:bg-red-500 hover:text-white text-text-muted transition-all" title="Delete" aria-label="Delete">
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={5} className="px-6 py-10 text-center text-text-muted text-sm">No groups yet — create one to bundle students for plans/discounts.</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 && (
        <GroupEditor
          initial={editor.row}
          isCreating={!!editor.creating}
          busy={busy}
          onSave={save}
          onClose={() => setEditor(null)}
        />
      )}

      {confirmDelete && (
        <Modal
          open={true}
          onClose={() => setConfirmDelete(null)}
          title="Delete group?"
          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">Soft-delete <strong>{confirmDelete.name}</strong> and its memberships.</p>
          </ModalBody>
        </Modal>
      )}

      {assignModal && (
        <AssignMembersModal
          group={assignModal}
          busy={busy}
          onClose={() => setAssignModal(null)}
          onAssign={(body) => onAssign(assignModal, body)}
        />
      )}
    </div>
  );
}

function GroupEditor({
  initial, isCreating, busy, onSave, onClose,
}: {
  initial?: StudentGroup;
  isCreating: boolean;
  busy: boolean;
  onSave: (data: Partial<StudentGroup> & { auto_track_class?: boolean }) => Promise<unknown>;
  onClose: () => void;
}) {
  const [name, setName] = useState(initial?.name || '');
  const [description, setDescription] = useState(initial?.description || '');
  const [type, setType] = useState<StudentGroup['type']>(initial?.type || 'custom');
  const [color, setColor] = useState(initial?.color || '#3b82f6');
  const [classId, setClassId] = useState(String(initial?.class_id ?? ''));
  const [capacity, setCapacity] = useState(String(initial?.capacity ?? ''));
  const [autoTrack, setAutoTrack] = useState(Boolean(initial?.auto_track_class));

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!name.trim()) return;
    await onSave({
      name: name.trim(),
      description: description.trim() || null,
      type,
      color: color || null,
      class_id: classId === '' ? null : Number(classId),
      capacity: capacity === '' ? null : Number(capacity),
      auto_track_class: autoTrack,
    });
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={isCreating ? 'New student group' : `Edit ${initial?.name}`}
      icon={Hash}
      maxWidth="max-w-lg"
      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="sg-edit-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="sg-edit-form" onSubmit={submit}>
          <Field label="Name *" icon={Hash} value={name} onChange={setName} required />
        <Field label="Description" icon={MapPin} value={description} onChange={setDescription} />
        <div className="grid grid-cols-2 gap-3 mt-3">
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Type</span>
            <select value={type} onChange={(e) => setType(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 dark:bg-background/60 border border-border rounded-xl text-sm text-text focus:outline-none focus:ring-2 focus:ring-primary/30">
              {Object.keys(typeLabel).map((t) => <option key={t} value={t}>{typeLabel[t]}</option>)}
            </select>
          </label>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Color</span>
            <input type="color" value={color} onChange={(e) => setColor(e.target.value)} className="mt-1 w-full h-10 px-1 py-1 bg-muted/30 border border-border rounded-xl text-sm" />
          </label>
        </div>
        <div className="grid grid-cols-2 gap-3 mt-3">
          <Field label="Class ID (optional)" icon={Bus} type="number" value={classId} onChange={setClassId} />
          <Field label="Capacity" icon={Users} type="number" value={capacity} onChange={setCapacity} />
        </div>
        <label className="flex items-center gap-2 mt-3 text-sm">
          <input type="checkbox" checked={autoTrack} onChange={(e) => setAutoTrack(e.target.checked)} className="accent-primary" />
          <span>Auto-track class enrollments (every student in the class joins this group automatically)</span>
        </label>
        <div className="mt-5 flex justify-end gap-2">
          <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" 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>
        </div>
      </form>
          </ModalBody>
    </Modal>
  );
}

function AssignMembersModal({
  group, busy, onClose, onAssign,
}: {
  group: StudentGroup;
  busy: boolean;
  onClose: () => void;
  onAssign: (body: { mode: 'ids' | 'class' | 'all'; student_uids?: string[]; class_id?: number }) => Promise<unknown>;
}) {
  const [mode, setMode] = useState<'ids' | 'class' | 'all'>('all');
  const [classId, setClassId] = useState('');
  const [studentUids, setStudentUids] = useState('');

  const submit = (e: React.FormEvent) => {
    e.preventDefault();
    if (mode === 'ids') {
      const uids = studentUids.split(/[\s,]+/).map((s) => s.trim()).filter(Boolean);
      if (uids.length === 0) return;
      onAssign({ mode: 'ids', student_uids: uids });
    } else if (mode === 'class') {
      if (!classId) return;
      onAssign({ mode: 'class', class_id: Number(classId) });
    } else {
      onAssign({ mode: 'all' });
    }
  };

  return (
    <Modal
      open={true}
      onClose={onClose}
      title={`Add members to ${group.name}`}
      icon={UserPlus}
      maxWidth="max-w-md"
      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="sg-assign-form" disabled={busy} 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" /> : 'Assign'}
          </button>
        </>
      }
    >
      <ModalBody>
        <form id="sg-assign-form" onSubmit={submit}>
          <p className="text-sm text-text-muted mb-3">
            Selects how recipients are added to <strong>{group.name}</strong>.
          </p>
          <label className="block">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Mode</span>
          <select value={mode} onChange={(e) => setMode(e.target.value as any)} className="mt-1 w-full px-3 py-2 bg-muted/30 dark:bg-background/60 border border-border rounded-xl text-sm text-text 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>
        {mode === 'class' && (
          <label className="block mt-3">
            <span className="text-xs font-bold uppercase tracking-wider text-text-muted">Class ID</span>
            <input type="number" value={classId} onChange={(e) => setClassId(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>
        )}
        {mode === '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={studentUids} onChange={(e) => setStudentUids(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>
        )}
        <div className="mt-5 flex justify-end gap-2">
          <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" disabled={busy} 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" /> : <UserPlus size={14} />}
            <span>Add</span>
          </button>
        </div>
      </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 mt-3">
      <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>
  );
}
