import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ArrowLeft, AlertCircle, Loader2, RefreshCw,
  Users, MapPin, Hash, Trash2, X,
} from 'lucide-react';
import { useFinanceEngineStore, StudentGroup } from '../../store/finance-engine';
import { Modal, ModalBody } from '../../components/ui/Modal';

export default function StudentGroupDetail() {
  const { uid } = useParams<{ uid: string }>();
  const navigate = useNavigate();
  const { currentGroup, fetchStudentGroup, removeStudentGroupMember, busy } = useFinanceEngineStore();
  const [confirm, setConfirm] = useState<{ member_uid: string; name: string } | null>(null);

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

  if (!currentGroup) {
    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>Group not found.</p>
        <button onClick={() => navigate('/finance/groups')} className="px-4 py-2 bg-primary text-white rounded-xl">Back</button>
      </div>
    );
  }

  const g: StudentGroup = currentGroup;
  const members = g.members || [];

  const onRemove = async (memberUid: string) => {
    if (!confirm) return;
    const ok = await removeStudentGroupMember(g.uid, memberUid);
    if (ok) {
      setConfirm(null);
      await fetchStudentGroup(g.uid);
    }
  };

  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/groups')} className="flex items-center gap-1 text-sm font-bold text-text-muted hover:text-text">
          <ArrowLeft size={16} /> Back to groups
        </button>
        <button onClick={() => fetchStudentGroup(g.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 items-center gap-3">
          <div className="w-3 h-12 rounded-sm" style={{ background: g.color || '#94a3b8' }} />
          <div>
            <h1 className="text-2xl font-black text-text tracking-tight">{g.name}</h1>
            <p className="text-sm text-text-muted mt-1">{g.description || 'No description.'}</p>
            <p className="text-[0.7rem] text-text-muted mt-1">
              <span className="inline-flex items-center gap-1"><MapPin size={10} /> Type: {g.type}</span>
              {g.class_name && ` · Class: ${g.class_name}`}
              {g.capacity && ` · Capacity: ${g.capacity}`}
            </p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <Tile label="Members" value={members.length} />
        <Tile label="Type" value={g.type} />
      </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">Member</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Email</th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">Joined</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">
              {members.length > 0 ? (
                members.map((m) => (
                  <tr key={m.member_uid} className="hover:bg-muted/40 transition-colors">
                    <td className="px-6 py-4">
                      <p className="text-[0.85rem] font-semibold text-text">{m.first_name} {m.last_name}</p>
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-muted">{m.email}</td>
                    <td className="px-6 py-4 text-[0.75rem] font-mono text-text-muted">{m.joined_at?.slice(0, 10) || '—'}</td>
                    <td className="px-6 py-4 text-right">
                      <button onClick={() => setConfirm({ member_uid: m.student_uid, name: `${m.first_name} ${m.last_name}` })} className="p-2 rounded-lg hover:bg-red-500 hover:text-white text-text-muted transition-all" title="Remove from group" aria-label="Remove from group">
                        <Trash2 size={16} />
                      </button>
                    </td>
                  </tr>
                ))
              ) : (
                <tr><td colSpan={4} className="px-6 py-10 text-center text-text-muted text-sm">No members yet — use the "Add members" button on the groups list.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {confirm && (
        <Modal
          open={true}
          onClose={() => setConfirm(null)}
          title="Remove member?"
          icon={X}
          maxWidth="max-w-sm"
          footer={
            <>
              <button onClick={() => setConfirm(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={() => onRemove(confirm.member_uid)} 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" /> : 'Remove'}</button>
            </>
          }
        >
          <ModalBody>
            <p className="text-sm text-text-muted">Remove <strong>{confirm.name}</strong> from this group? Their existing fees and discounts stay — only the group link is dropped.</p>
          </ModalBody>
        </Modal>
      )}
    </div>
  );
}

function Tile({ label, value }: { label: string; value: string | number }) {
  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 capitalize">{value}</p>
    </div>
  );
}
