import React, { useEffect, useState } from 'react';
import { Search, GraduationCap, Calendar, Filter, Mail, Phone, ExternalLink } from 'lucide-react';
import { useOffboardingStore } from '../../store/offboarding';
import { useCohortsStore } from '../../store/cohorts';
import RoleBadge from '../../components/RoleBadge';

export default function Alumni() {
  const { alumni, loading, error, fetchAlumni } = useOffboardingStore();
  const { cohorts, fetchCohorts } = useCohortsStore();

  const [search, setSearch] = useState('');
  const [cohortFilter, setCohortFilter] = useState<string>('');
  const [yearFilter, setYearFilter] = useState<string>('');
  const [reasonFilter, setReasonFilter] = useState<string>('');

  useEffect(() => {
    fetchCohorts();
  }, [fetchCohorts]);

  useEffect(() => {
    fetchAlumni({
      cohort_id: cohortFilter || undefined,
      year: yearFilter || undefined,
      search: search || undefined,
    });
  }, [cohortFilter, yearFilter, search, fetchAlumni]);

  // Extract years for select filter
  const alumniYears = Array.from(
    new Set(
      alumni
        .map((a) => (a.effective_date ? new Date(a.effective_date).getFullYear().toString() : null))
        .filter(Boolean)
    )
  ).sort((a, b) => (b || '').localeCompare(a || ''));

  const filteredAlumni = alumni.filter((a) => {
    if (reasonFilter && a.reason !== reasonFilter) return false;
    return true;
  });

  return (
    <div className="space-y-6 animate-in fade-in duration-500">
      {/* Page Header */}
      <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
        <div>
          <h1 className="text-3xl font-black text-text tracking-tight flex items-center gap-3">
            <GraduationCap className="text-primary shrink-0" size={32} />
            <span>Alumni & Former Students</span>
          </h1>
          <p className="text-sm text-text-muted mt-1">
            Browse and filter through past students who graduated, transferred, or completed withdrawal processes.
          </p>
        </div>
      </div>

      {/* Filter and Search Bar */}
      <div className="bg-card border border-border rounded-2xl p-4 flex flex-col md:flex-row gap-3">
        <div className="flex-1 relative">
          <Search size={14} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted" />
          <input
            type="text"
            placeholder="Search by name or email..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 rounded-xl border border-border bg-background/50 text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
          />
        </div>

        <select
          value={cohortFilter}
          onChange={(e) => setCohortFilter(e.target.value)}
          className="px-4 py-2.5 rounded-xl border border-border bg-background text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
        >
          <option value="">All Cohorts</option>
          {cohorts.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>

        <select
          value={yearFilter}
          onChange={(e) => setYearFilter(e.target.value)}
          className="px-4 py-2.5 rounded-xl border border-border bg-background text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
        >
          <option value="">All Years</option>
          {alumniYears.map((y) => (
            <option key={y} value={y}>
              {y}
            </option>
          ))}
        </select>

        <select
          value={reasonFilter}
          onChange={(e) => setReasonFilter(e.target.value)}
          className="px-4 py-2.5 rounded-xl border border-border bg-background text-text text-sm focus:outline-none focus:ring-2 focus:ring-primary/45"
        >
          <option value="">All Reasons</option>
          <option value="graduated">Graduated</option>
          <option value="transferred">Transferred</option>
          <option value="withdrawn">Withdrawn</option>
          <option value="expelled">Expelled</option>
        </select>
      </div>

      {error && (
        <div className="p-4 bg-rose-500/10 border border-rose-500/20 text-rose-500 rounded-xl text-sm font-bold">
          {error}
        </div>
      )}

      {/* Grid Layout of Alumni Cards */}
      {loading && alumni.length === 0 ? (
        <div className="py-20 text-center">
          <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-text-muted text-sm font-bold uppercase tracking-wider">Syncing Alumni Directory...</p>
        </div>
      ) : filteredAlumni.length === 0 ? (
        <div className="bg-card border border-border rounded-[2.5rem] py-20 text-center shadow-sm">
          <GraduationCap className="w-12 h-12 text-text-muted/40 mx-auto mb-4" />
          <p className="text-text-muted text-sm font-extrabold">No alumni match your current filter parameters.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredAlumni.map((student) => (
            <div
              key={student.id}
              className="bg-card border border-border rounded-[2rem] p-6 hover:shadow-lg transition-all group flex flex-col justify-between"
            >
              <div className="space-y-4">
                <div className="flex justify-between items-start">
                  <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-primary to-slate-900 flex items-center justify-center text-white text-lg font-black shadow-md">
                    {student.first_name[0]}
                    {student.last_name[0]}
                  </div>
                  <span className={`px-2 py-0.5 rounded text-[0.55rem] font-black uppercase tracking-wider border ${
                    student.reason === 'graduated'
                      ? 'bg-emerald-50 text-emerald-600 border-emerald-100 dark:bg-emerald-500/10 dark:text-emerald-400'
                      : student.reason === 'expelled'
                      ? 'bg-rose-50 text-rose-600 border-rose-100 dark:bg-rose-500/10 dark:text-rose-400'
                      : 'bg-blue-50 text-blue-600 border-blue-100 dark:bg-blue-500/10 dark:text-blue-400'
                  }`}>
                    {student.reason}
                  </span>
                </div>

                <div className="space-y-1">
                  <h3 className="text-lg font-black text-text group-hover:text-primary transition-colors">
                    {student.first_name} {student.last_name}
                  </h3>
                  {student.cohort_name && (
                    <span className="inline-block px-2.5 py-0.5 bg-muted text-text-muted border border-border/60 rounded-md text-[0.6rem] font-bold uppercase tracking-wider">
                      {student.cohort_name}
                    </span>
                  )}
                </div>

                <div className="space-y-2.5 pt-4 border-t border-border/60">
                  <div className="flex items-center gap-3 text-xs text-text-muted">
                    <Mail size={12} className="shrink-0" />
                    <span className="truncate">{student.email}</span>
                  </div>
                  {student.phone && (
                    <div className="flex items-center gap-3 text-xs text-text-muted">
                      <Phone size={12} className="shrink-0" />
                      <span>{student.phone}</span>
                    </div>
                  )}
                  <div className="flex items-center gap-3 text-xs text-text-muted">
                    <Calendar size={12} className="shrink-0" />
                    <span>Left: {new Date(student.effective_date).toLocaleDateString()}</span>
                  </div>
                </div>

                {student.destination && (
                  <div className="bg-muted/30 border border-border/50 rounded-xl p-3 text-xs">
                    <span className="text-[0.55rem] font-black uppercase text-text-muted block">Transferred To</span>
                    <span className="font-bold text-text mt-0.5 block">{student.destination}</span>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
