import { useState, useEffect } from 'react';
import api from '../../store/auth';
import { useAuthStore } from '../../store/auth';
import { Modal, ModalBody } from '../../components/ui/Modal';
import {
  Bell,
  Plus,
  Search,
  Pin,
  AlertTriangle,
  GraduationCap,
  Megaphone,
  Bus,
  Building,
  Calendar,
  Users,
  Pencil,
  Trash2,
  ChevronRight,
  Sparkles,
  Info,
  Clock,
  UserCircle,
  MoreVertical,
  X,
  ArrowUpRight,
  ShieldCheck,
  CheckCircle2,
  Filter,
  Download
} from 'lucide-react';


export default function NoticeBoard() {
  const { user } = useAuthStore();
  const [notices, setNotices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showModal, setShowModal] = useState(false);
  const [editingNotice, setEditingNotice] = useState<any | null>(null);
  const [selectedCategory, setSelectedCategory] = useState('All');
  const [form, setForm] = useState({
    title: '',
    content: '',
    category: 'Academic',
    priority: 'Normal',
    audience: 'All',
    is_pinned: false,
    expiry_date: '',
  });

  const [priorityFilter, setPriorityFilter] = useState<'All' | 'Normal' | 'Important' | 'Urgent'>('All');
  const [showFilters, setShowFilters] = useState(false);

  useEffect(() => {
    loadNotices();
  }, []);
  
  const loadNotices = async () => {
    setLoading(true);
    try {
      const res = await api.get('/notices');
      setNotices(res.data || []);
    } catch (err) {
      console.error('Failed to load notices');
      setNotices([]);
    } finally {
      setLoading(false);
    }
  };

  const saveNotice = async () => {
    try {
      const payload = {
        ...form,
        expiry_date: form.expiry_date || null
      };
      if (editingNotice) {
        await api.put(`/notices/${editingNotice.id}`, payload);
      } else {
        await api.post('/notices', payload);
      }
      setShowModal(false);
      setEditingNotice(null);
      setForm({
        title: '',
        content: '',
        category: 'Academic',
        priority: 'Normal',
        audience: 'All',
        is_pinned: false,
        expiry_date: '',
      });
      loadNotices();
    } catch (err) {
      console.error(err);
      alert('Failed to save notification');
    }
  };

  const deleteNotice = async (id: number) => {
    if (!confirm('Archive this notification?')) return;
    try {
      await api.delete(`/notices/${id}`);
      loadNotices();
    } catch (err) {
      console.error(err);
      alert('Protocol failure: notification maintained');
    }
  };

  const editNotice = (notice: any) => {
    setEditingNotice(notice);
    setForm({
      title: notice.title || '',
      content: notice.content || '',
      category: notice.category || 'Academic',
      priority: notice.priority || 'Normal',
      audience: notice.audience || 'All',
      is_pinned: !!notice.is_pinned,
      expiry_date: notice.expiry_date ? notice.expiry_date.substring(0, 10) : '',
    });
    setShowModal(true);
  };

  const filtered = notices.filter((n) => {
    const matchesSearch = n.title?.toLowerCase().includes(search.toLowerCase());
    const matchesCategory = selectedCategory === 'All' || n.category === selectedCategory;
    const matchesPriority = priorityFilter === 'All' || n.priority === priorityFilter;
    return matchesSearch && matchesCategory && matchesPriority;
  });

  const stats = [
    { title: 'Live Notifications', value: notices.length, color: 'blue', icon: Bell, trend: 'Active' },
    // PDF §6 — "Priority Pins" should never render a bare `0` (looks like a
    // bug). When nothing is pinned we render an em-dash and "None" trend
    // so the tile reads as a clean empty state instead of a counter.
    {
      title: 'Priority Pins',
      value: notices.filter(n => n.is_pinned || n.pinned).length,
      valueWhenZero: '—',
      color: 'orange',
      icon: Pin,
      trend: notices.some(n => n.is_pinned || n.pinned) ? 'Pinned' : 'None',
    },
    { title: 'Critical Alerts', value: notices.filter(n => n.priority === 'Urgent').length, color: 'rose', icon: AlertTriangle, trend: 'High' },
    { title: 'System Status', value: 'Optimal', color: 'emerald', icon: ShieldCheck, trend: 'Status' },
  ];

  const categories = [
    { label: 'All', icon: Bell },
    { label: 'Academic', icon: GraduationCap },
    { label: 'Administration', icon: Megaphone },
    { label: 'Transport', icon: Bus },
    { label: 'Hostel', icon: Building },
    { label: 'Emergency', icon: AlertTriangle },
  ];

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      case 'rose': return 'bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800';
      case 'orange': return 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const canCreate = ['school_admin', 'systems_admin', 'principal', 'teacher', 'hr', 'bursar'].includes(user?.role || '');
  const canEdit = ['school_admin', 'systems_admin', 'principal', 'teacher', 'hr', 'bursar'].includes(user?.role || '');
  const canDelete = ['school_admin', 'systems_admin', 'principal'].includes(user?.role || '');

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight uppercase">Communication Hub</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>NextGen Hub</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Notice Board</span>
          </nav>
        </div>

        {canCreate && (
          <div className="flex gap-3">
             <button
                onClick={() => {
                  if (notices.length === 0) return;
                  const rows = notices.map(n => ({
                    id: n.id,
                    title: n.title ?? '',
                    category: n.category ?? '',
                    priority: n.priority ?? '',
                    audience: n.audience ?? '',
                    is_pinned: !!(n.is_pinned || n.pinned),
                    creator: n.creator_name ?? '',
                    created_at: n.created_at ?? ''
                  }));
                  const headers = Object.keys(rows[0]);
                  const escape = (v: unknown) => { const s = v == null ? '' : String(v); return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; };
                  const csv = [headers.join(','), ...rows.map(r => headers.map(h => escape((r as any)[h])).join(','))].join('\n');
                  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                  const url = URL.createObjectURL(blob);
                  const link = document.createElement('a');
                  link.href = url;
                  link.download = `noticeboard_archive_${new Date().toISOString().split('T')[0]}.csv`;
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link);
                  URL.revokeObjectURL(url);
                }}
                className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
            >
                <Download size={18} className="text-primary" />
                Archive Audit
            </button>
            <button
                onClick={() => {
                    setEditingNotice(null);
                    setForm({ title: '', content: '', category: 'Academic', priority: 'Normal', audience: 'All', is_pinned: false, expiry_date: '' });
                    setShowModal(true);
                }}
                className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            >
                <Plus size={18} />
                Create Notification
            </button>
          </div>
        )}
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.title} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.title}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">
                  {stat.value === 0 && stat.valueWhenZero ? stat.valueWhenZero : stat.value}
                </p>
                <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        {/* Category Picker */}
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-grow lg:flex-grow-0 min-w-0 overflow-x-auto custom-scrollbar">
          {categories.map((cat) => (
            <button
              key={cat.label}
              onClick={() => setSelectedCategory(cat.label)}
              className={`
                flex-1 px-6 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all whitespace-nowrap flex items-center justify-center gap-2
                ${selectedCategory === cat.label 
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                  : 'text-text-muted hover:text-text'}
              `}
            >
              <cat.icon size={14} />
              {cat.label}
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <div className="relative group flex-1 focus-within:w-full lg:focus-within:w-1/2 transition-all">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
            placeholder="Search active notifications by title or content..."
            value={search}
            onChange={e => setSearch(e.target.value)}
          />
        </div>

        <button
          onClick={() => setShowFilters(v => !v)}
          className={`px-5 py-3 rounded-2xl border transition-all flex items-center justify-center gap-2 ${showFilters ? 'bg-primary text-white border-primary' : 'bg-muted/50 hover:bg-muted text-text-muted border-border'}`}
        >
          <Filter size={18} />
          <span className="text-[0.7rem] font-black uppercase tracking-widest">More Filters</span>
        </button>
      </div>

      {showFilters && (
        <div className="bg-card border border-border rounded-[1.5rem] p-5 shadow-sm flex flex-wrap items-center gap-4 animate-in slide-in-from-top-2 duration-200">
          <span className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Priority:</span>
          {(['All', 'Normal', 'Important', 'Urgent'] as const).map(p => (
            <button
              key={p}
              onClick={() => setPriorityFilter(p)}
              className={`px-4 py-2 rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border ${priorityFilter === p ? 'bg-primary text-white border-primary' : 'bg-muted/50 text-text-muted border-border hover:bg-muted'}`}
            >
              {p}
            </button>
          ))}
        </div>
      )}

      {/* Main Content Area */}
      {loading ? (
        <div className="py-20 text-center">
          <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Syncing Hub Transmissions...</p>
        </div>
      ) : (
        <div className="space-y-4">
          {filtered.length === 0 ? (
            <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
                <Megaphone size={64} className="mx-auto text-text-muted/30 mb-6" />
                <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">Quiet Hub</h3>
                <p className="text-text-muted font-medium max-w-xs mx-auto">No active notifications identified in this frequency.</p>
            </div>
          ) : filtered.map((notice) => (
            <div key={notice.id} className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden">
              <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/20 transition-colors"></div>
              
              <div className="flex justify-between items-start gap-8 relative z-10">
                <div className="flex-1">
                  <div className="flex flex-wrap gap-2 mb-6">
                    {notice.is_pinned && (
                      <span className="px-3 py-1 rounded-lg bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 text-[0.6rem] font-black uppercase tracking-widest border border-amber-100 dark:border-amber-800 flex items-center gap-1.5 shadow-sm">
                        <Pin size={10} /> PINNED Intel
                      </span>
                    )}

                    {notice.category === 'Emergency' ? (
                      <span className="px-3 py-1 rounded-lg bg-rose-500 text-white text-[0.6rem] font-black uppercase tracking-widest border border-rose-500 shadow-sm flex items-center gap-1.5">
                        <AlertTriangle size={10} /> Emergency
                      </span>
                    ) : (
                      <span className="px-3 py-1 rounded-lg bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 text-[0.6rem] font-black uppercase tracking-widest border border-blue-100 dark:border-blue-800 shadow-sm">
                        {notice.category}
                      </span>
                    )}

                    <span className={`px-3 py-1 rounded-lg text-[0.6rem] font-black uppercase tracking-widest border shadow-sm ${
                        notice.priority === 'Urgent' 
                        ? 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400 border-rose-100 dark:border-rose-800' 
                        : 'bg-muted dark:bg-muted/30 text-text-muted border-border'
                    }`}>
                      {notice.priority} Priority
                    </span>

                    {notice.expiry_date && (
                      <span className="px-3 py-1 rounded-lg bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 text-[0.6rem] font-black uppercase tracking-widest border border-orange-100 dark:border-orange-800/20 shadow-sm flex items-center gap-1.5">
                        <Clock size={10} /> Expires: {notice.expiry_date.substring(0, 10)}
                      </span>
                    )}
                  </div>

                  <h3 className="text-2xl font-black text-text tracking-tight group-hover:text-primary transition-colors mb-4 uppercase">
                    {notice.title}
                  </h3>
                  <p className="text-[1.05rem] text-text-secondary font-medium leading-relaxed mb-8 max-w-4xl">
                    {notice.content}
                  </p>

                  <div className="flex flex-wrap items-center gap-6 pt-6 border-t border-border/50">
                    <div className="flex items-center gap-2 text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                      <UserCircle size={14} className="text-primary" />
                      {notice.creator_name || 'System Administrator'}
                    </div>
                    <div className="w-1 h-1 rounded-full bg-border"></div>
                    <div className="flex items-center gap-2 text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                      <Calendar size={14} className="text-emerald-500" />
                      {new Date(notice.created_at).toLocaleDateString()}
                    </div>
                    <div className="w-1 h-1 rounded-full bg-border"></div>
                    <div className="flex items-center gap-2 text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                      <Users size={14} className="text-orange-500" />
                      Scope: {notice.audience}
                    </div>
                  </div>
                </div>

                <div className="flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                  {canEdit && (
                    <button
                      onClick={() => editNotice(notice)}
                      className="p-3 rounded-xl bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40 border border-blue-100 dark:border-blue-800 transition-all shadow-sm"
                    >
                      <Pencil size={18} />
                    </button>
                  )}
                  {canDelete && (
                    <button
                      onClick={() => deleteNotice(notice.id)}
                      className="p-3 rounded-xl bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 hover:bg-rose-100 dark:hover:bg-rose-900/40 border border-rose-100 dark:border-rose-800 transition-all shadow-sm"
                    >
                      <Trash2 size={18} />
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Modal Infrastructure */}
      {showModal && (
        <Modal
          open={true}
          onClose={() => setShowModal(false)}
          title={editingNotice ? 'Update Transmission' : 'New Notification'}
          icon={Sparkles}
          subtitle={editingNotice ? 'Syncing system announcement' : 'Compose a school-wide notification'}
          maxWidth="max-w-2xl"
          zIndex={150}
        >
          <ModalBody className="p-0 max-h-[90vh] flex flex-col">
            <form id="noticeboard-form" onSubmit={(e) => { e.preventDefault(); saveNotice(); }} className="p-4 sm:p-8 md:p-10 space-y-4 sm:space-y-6 overflow-y-auto custom-scrollbar">
                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Notification Header</label>
                    <input 
                        className="form-input text-text" 
                        value={form.title} 
                        onChange={e => setForm({ ...form, title: e.target.value })} 
                        placeholder="e.g., Annual Sports Protocol Update" 
                        required 
                    />
                </div>

                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Intel Content</label>
                    <textarea 
                        className="form-input rounded-[2rem] px-5 py-5 text-text" 
                        rows={4} 
                        value={form.content} 
                        onChange={e => setForm({ ...form, content: e.target.value })} 
                        placeholder="Construct message content here..." 
                        required 
                    />
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Category</label>
                        <select className="form-input appearance-none cursor-pointer text-text" value={form.category} onChange={e => setForm({ ...form, category: e.target.value })}>
                            <option>Academic</option>
                            <option>Administration</option>
                            <option>Transport</option>
                            <option>Hostel</option>
                            <option>Emergency</option>
                        </select>
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Priority</label>
                        <select className="form-input appearance-none cursor-pointer text-text" value={form.priority} onChange={e => setForm({ ...form, priority: e.target.value })}>
                            <option>Normal</option>
                            <option>Important</option>
                            <option>Urgent</option>
                        </select>
                    </div>
                    <div className="space-y-1.5">
                        <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Audience</label>
                        <select className="form-input appearance-none cursor-pointer text-text" value={form.audience} onChange={e => setForm({ ...form, audience: e.target.value })}>
                            <option>All</option>
                            <option>Students</option>
                            <option>Teachers</option>
                            <option>Parents</option>
                        </select>
                    </div>
                </div>

                <div className="space-y-1.5">
                    <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Expiry Date</label>
                    <input 
                        type="date"
                        className="form-input text-text" 
                        value={form.expiry_date} 
                        onChange={e => setForm({ ...form, expiry_date: e.target.value })} 
                    />
                </div>

                <div className="flex items-center gap-3 p-4 sm:p-5 bg-amber-50 dark:bg-amber-900/20 rounded-2xl border border-amber-100 dark:border-amber-800">
                    <div className="w-10 h-10 rounded-xl bg-card border border-border flex items-center justify-center text-amber-600 dark:text-amber-400 shadow-sm shrink-0"><Pin size={20} /></div>
                    <div className="flex-1 min-w-0">
                        <p className="text-[0.65rem] font-black uppercase text-amber-600 dark:text-amber-400 tracking-widest">Pin Intel</p>
                        <p className="text-[0.6rem] font-bold text-amber-400 dark:text-amber-300">Maintain visibility at the top of the hub</p>
                    </div>
                    <input 
                        type="checkbox" 
                        className="w-6 h-6 rounded-lg border-amber-200 dark:border-amber-700 text-amber-600 focus:ring-amber-500 cursor-pointer shrink-0"
                        checked={form.is_pinned}
                        onChange={e => setForm({ ...form, is_pinned: e.target.checked })}
                    />
                </div>

                <div className="pt-4 flex flex-col sm:flex-row gap-3 sm:gap-4">
                    <button type="button" onClick={() => setShowModal(false)} className="w-full sm:flex-1 py-3.5 sm:py-4 bg-muted/50 hover:bg-muted text-text font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all border border-border cursor-pointer">Abort</button>
                    <button type="submit" className="w-full sm:flex-1 py-3.5 sm:py-4 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-[0.7rem] rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-2 cursor-pointer">
                        {editingNotice ? <CheckCircle2 size={16} /> : <Megaphone size={16} />}
                        <span>{editingNotice ? 'Commit Changes' : 'Finalize'}</span>
                    </button>
                </div>
            </form>
          </ModalBody>
        </Modal>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); }
      `}</style>
    </div>
  );
}


