import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Drawer, DrawerHeader, DrawerFooter } from '../../components/ui/Drawer';
import {
  Users, Search, Filter, Mail, Phone, Building2, Hash,
  Briefcase, CalendarDays, ChevronLeft, ChevronRight, RefreshCw,
  AlertCircle, X, UserMinus
} from 'lucide-react';
import { useHRStore, StaffRecord } from '../../store/hr';
import { useAuthStore } from '../../store/auth';

const PAGE_SIZE = 20;

const statusBadge = (isActive: number) =>
  isActive
    ? 'bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300'
    : 'bg-muted text-text-muted border-border';

export default function StaffDirectory() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const {
    records,
    departments,
    loading,
    error,
    fetchRecords,
    fetchMetadata,
  } = useHRStore();

  const [search, setSearch] = useState('');
  const [departmentFilter, setDepartmentFilter] = useState<number | 'all'>('all');
  const [activeOnly, setActiveOnly] = useState(true);
  const [page, setPage] = useState(0);
  const [selected, setSelected] = useState<StaffRecord | null>(null);

  useEffect(() => {
    fetchRecords();
    fetchMetadata();
  }, [fetchRecords, fetchMetadata]);

  const departmentOptions = useMemo(() => {
    return (departments || []).slice().sort((a: any, b: any) => {
      const an = (a?.name || '').toLowerCase();
      const bn = (b?.name || '').toLowerCase();
      return an.localeCompare(bn);
    });
  }, [departments]);

  const filtered = useMemo(() => {
    return records.filter((r) => {
      if (activeOnly && !r.is_active) return false;
      if (departmentFilter !== 'all') {
        const deptName = (r.department || '').toLowerCase();
        const opt = departmentOptions.find((d: any) => d.id === departmentFilter);
        if (!opt || deptName !== (opt.name || '').toLowerCase()) return false;
      }
      if (!search.trim()) return true;
      const needle = search.toLowerCase();
      return (
        (r.first_name || '').toLowerCase().includes(needle) ||
        (r.last_name || '').toLowerCase().includes(needle) ||
        (r.email || '').toLowerCase().includes(needle) ||
        (r.staff_number || '').toLowerCase().includes(needle) ||
        (r.designation || '').toLowerCase().includes(needle) ||
        (r.department || '').toLowerCase().includes(needle)
      );
    });
  }, [records, search, departmentFilter, activeOnly, departmentOptions]);

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

  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">Staff Directory</h1>
          <p className="text-text-muted mt-1 text-lg">
            Browse every active staff member. Read-only — edit through the HR Center.
          </p>
        </div>
        <button
          onClick={() => fetchRecords()}
          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>
      </div>

      {/* Filters */}
      <div className="bg-card rounded-2xl border border-border p-5 shadow-sm">
        <div className="grid grid-cols-1 md:grid-cols-3 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 name, email, designation…"
              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>

          <div className="relative">
            <Filter size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
            <select
              value={departmentFilter}
              onChange={(e) => {
                const v = e.target.value;
                setDepartmentFilter(v === 'all' ? 'all' : Number(v));
                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"
            >
              <option value="all">All departments</option>
              {departmentOptions.map((d: any) => (
                <option key={d.id} value={d.id}>{d.name}</option>
              ))}
            </select>
          </div>

          <label className="flex items-center gap-2 px-3 py-2.5 bg-muted/30 border border-border rounded-xl text-sm cursor-pointer">
            <input
              type="checkbox"
              checked={activeOnly}
              onChange={(e) => { setActiveOnly(e.target.checked); setPage(0); }}
              className="accent-primary"
            />
            <span className="font-semibold text-text">Active staff only</span>
          </label>
        </div>

        <p className="text-[0.65rem] mt-3 text-text-muted">
          {loading ? 'Loading…' : `${filtered.length} staff record${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">
                  Staff #
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Department
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Role
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Grade
                </th>
                <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">
                  Status
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {pageRows.length > 0 ? (
                pageRows.map((r) => (
                  <tr
                    key={r.id}
                    onClick={() => setSelected(r)}
                    className="hover:bg-muted/40 transition-colors cursor-pointer"
                  >
                    <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">
                          <Users size={14} />
                        </div>
                        <div>
                          <p className="text-[0.85rem] font-semibold text-text">
                            {r.first_name} {r.last_name}
                          </p>
                          <p className="text-[0.65rem] text-text-muted">{r.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-[0.75rem] font-mono text-text-muted">
                      {r.staff_number}
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary">
                      {r.department || '—'}
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary">
                      {r.role_name || '—'}
                    </td>
                    <td className="px-6 py-4 text-[0.85rem] text-text-secondary">
                      {r.grade_name || '—'}
                    </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(r.is_active)}`}>
                        {r.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="px-6 py-10 text-center text-text-muted text-sm">
                    No staff 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>

      {/* Detail drawer */}
      {selected && (
        <Drawer
          open={true}
          onClose={() => setSelected(null)}
          title={`${selected.first_name} ${selected.last_name}`}
          subtitle={`${selected.designation || '—'} · ${selected.department || '—'}`}
          zIndex={100}
          maxWidth="max-w-md"
        >
          <DrawerHeader>
            <p className="text-[0.6rem] uppercase font-black tracking-[2px] text-primary">Staff detail</p>
          </DrawerHeader>
          <div className="p-6 space-y-5">
            <DetailRow icon={Hash} label="Staff number" value={selected.staff_number} />
            <DetailRow icon={Mail} label="Email" value={selected.email} />
            <DetailRow
              icon={Phone}
              label="Phone"
              value={(selected as any).phone || (selected as any).phone_number || '—'}
            />
            <DetailRow icon={Building2} label="Department" value={selected.department || '—'} />
            <DetailRow icon={Briefcase} label="Role" value={selected.role_name || '—'} />
            <DetailRow icon={Briefcase} label="Salary grade" value={selected.grade_name || '—'} />
            <DetailRow
              icon={Briefcase}
              label="Employment type"
              value={selected.employment_type || '—'}
            />
            <DetailRow
              icon={CalendarDays}
              label="Appointed"
              value={
                selected.appointment_date
                  ? new Date(selected.appointment_date).toLocaleDateString()
                  : '—'
              }
            />
            <DetailRow
              icon={Users}
              label="Status"
              value={selected.is_active ? 'Active' : 'Inactive'}
            />
            {['school_admin', 'systems_admin', 'principal'].includes(user?.role || '') && selected.is_active === 1 && (
              <button
                type="button"
                onClick={() => {
                  setSelected(null);
                  navigate(`/admin/offboarding/wizard/${selected.id}`);
                }}
                className="w-full mt-6 py-3.5 bg-rose-600 hover:bg-rose-700 text-white rounded-xl font-bold text-xs uppercase tracking-widest transition-all shadow-md flex items-center justify-center gap-2"
              >
                <UserMinus size={14} /> Offboard Staff Member
              </button>
            )}
          </div>
        </Drawer>
      )}
    </div>
  );
}

function DetailRow({
  icon: Icon,
  label,
  value,
}: {
  icon: typeof Hash;
  label: string;
  value: string;
}) {
  return (
    <div className="flex items-start gap-3">
      <div className="p-2 rounded-lg bg-muted text-text-muted shrink-0">
        <Icon size={14} />
      </div>
      <div>
        <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted">{label}</p>
        <p className="text-sm font-semibold text-text mt-0.5 break-words">{value}</p>
      </div>
    </div>
  );
}