import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';

const MOCK_NOTICES = [
  {
    _id: 'mock1',
    title: 'Mid-Term Examination Schedule Released',
    content: 'The mid-term examination schedule for the academic year 2024-25 is now available. Students are requested to download the timetable and guidelines for their respective grades.',
    category: 'Exam',
    date: new Date('2024-11-15T00:00:00Z').toISOString()
  },
  {
    _id: 'mock2',
    title: 'School Winter Trip 2024',
    content: 'Pack your bags! Our annual winter mountain retreat for Grades 6-10 is now open for registrations. Discover nature and build friendships.',
    category: 'Academic',
    date: new Date('2024-10-20T00:00:00Z').toISOString()
  },
  {
    _id: 'mock3',
    title: 'Admissions Open for Grade 1-5',
    content: 'Join the St. Andrews family! Application forms for the upcoming academic session are now available at the administrative office and online.',
    category: 'Admissions',
    date: new Date('2024-10-18T00:00:00Z').toISOString()
  },
  {
    _id: 'mock4',
    title: 'Parent-Teacher Meeting (PTM)',
    content: 'A PTM is scheduled for this coming Saturday to discuss your child\'s performance in the recent class tests. All parents are requested to attend.',
    category: 'Academic',
    date: new Date('2024-10-12T00:00:00Z').toISOString()
  },
  {
    _id: 'mock5',
    title: 'Winter Holidays Announcement',
    content: 'The school will remain closed for winter vacation starting from December 24th to January 7th. Regular classes will resume on January 8th.',
    category: 'Holidays',
    date: new Date('2024-10-05T00:00:00Z').toISOString()
  }
];

export default function Notices() {
  const [notices, setNotices] = useState([]);
  const [search, setSearch] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('All');
  const [loading, setLoading] = useState(true);

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

  const fetchNotices = async () => {
    try {
      setLoading(true);
      const res = await axios.get('http://localhost:5000/api/notices');
      if (res.data && res.data.length > 0) {
        setNotices(res.data);
      } else {
        setNotices(MOCK_NOTICES);
      }
    } catch (err) {
      console.error("Failed to fetch notices:", err);
      setNotices(MOCK_NOTICES);
    } finally {
      setLoading(false);
    }
  };

  const getFilteredNotices = () => {
    return notices.filter(notice => {
      const matchesCategory = categoryFilter === 'All' || notice.category === categoryFilter;
      const matchesSearch = notice.title.toLowerCase().includes(search.toLowerCase()) || 
                            notice.content.toLowerCase().includes(search.toLowerCase());
      return matchesCategory && matchesSearch;
    });
  };

  const filtered = getFilteredNotices();
  const urgentNotice = notices.find(n => n.category === 'Exam') || notices[0];

  return (
    <div className="min-h-screen pt-16">
      <Navbar />
      <main className="pt-0">
        
        <section className="relative overflow-hidden px-4 md:px-8 pb-20 text-center">
          <div className="absolute inset-0 -z-10 opacity-30">
            <div className="floating-cloud absolute top-10 left-[10%] opacity-40">
              <span className="material-symbols-outlined text-[120px] text-primary-container">cloud</span>
            </div>
            <div className="floating-cloud absolute top-40 left-[60%] opacity-20">
              <span className="material-symbols-outlined text-[160px] text-primary-container">cloud</span>
            </div>
          </div>
          <div className="max-w-4xl mx-auto">
            <div className="inline-flex items-center gap-2 bg-secondary-container px-4 py-2 rounded-full mb-6">
              <span className="material-symbols-outlined text-on-secondary-container text-sm" style={{ fontVariationSettings: "'FILL' 1" }}>campaign</span>
              <span className="text-label-md text-on-secondary-container uppercase tracking-widest">Official Updates</span>
            </div>
            <h1 className="font-headline-xl text-headline-xl text-primary mb-6">School Notices</h1>
            <p className="font-body-lg text-body-lg text-on-surface-variant max-w-2xl mx-auto leading-relaxed">
              Stay informed with the latest school notices and important updates. From academic schedules to campus events, find everything you need to navigate the school year.
            </p>
          </div>
          
          <div className="mt-12 flex justify-center max-w-5xl mx-auto">
            <div className="w-full h-64 md:h-96 rounded-xl shadow-2xl relative overflow-hidden bg-primary-container/20 border-4 border-white">
              <img alt="Whimsical School Illustration" className="w-full h-full object-cover" src="https://lh3.googleusercontent.com/aida/AP1WRLszFuEq5teuoDu0canzgobK3Ch6X_aF72CZKvyTp4Y32IEW_rhOVei6Kpc3Eu7uOgA7JboRsdakOOqFhQTLmfsbwE1oOlbAgtI_iX5rNhfzdNyvKNBrsi_fGiIUoxpa8cezzFg2n7s-k6T9opHGalfNXzcZwP2WZKOSSGiWdZG-qSQaDKs73vz3YBip2sRVVniBJo7v7cCpCNOMMUgdtIxrw8ctmYyNO2G-f3HCL1Cz3Wk3-Ijia5ImX4M"/>
              <div className="absolute inset-0 bg-gradient-to-t from-primary/30 to-transparent pointer-events-none"></div>
            </div>
          </div>
        </section>

        <section className="px-4 md:px-8 py-12 bg-white relative z-10">
          <div className="max-w-7xl mx-auto">
            
            {/* Urgent Notice Banner */}
            {urgentNotice && (
              <div className="mb-16">
                <div className="relative overflow-hidden group rounded-xl bg-primary text-on-primary p-8 md:p-12 flex flex-col md:flex-row items-center gap-10 shadow-xl shadow-primary/20">
                  <div className="absolute top-0 right-0 opacity-10 pointer-events-none translate-x-1/4 -translate-y-1/4">
                    <span className="material-symbols-outlined text-[300px]">event_note</span>
                  </div>
                  <div className="relative z-10 flex-1">
                    <div className="inline-block bg-tertiary-container text-on-tertiary-container px-4 py-1 rounded-full text-label-sm font-bold mb-4 flex items-center gap-2">
                      <span className="material-symbols-outlined text-sm">priority_high</span>
                      URGENT
                    </div>
                    <h2 className="font-headline-lg text-headline-lg mb-4">{urgentNotice.title}</h2>
                    <p className="font-body-md text-on-primary/90 mb-8 max-w-xl">
                      {urgentNotice.content}
                    </p>
                    <div className="flex flex-wrap gap-4">
                      <button className="bg-white text-primary px-8 py-3 rounded-full font-label-md hover:bg-primary-fixed hover:scale-105 transition-all flex items-center gap-2 shadow-md">
                        <span className="material-symbols-outlined">download</span>
                        Download Document (PDF)
                      </button>
                    </div>
                  </div>
                  <div className="hidden md:flex w-64 h-64 rounded-lg bg-white/10 backdrop-blur-md border border-white/20 p-6 items-center justify-center text-center">
                    <div>
                      <span className="block text-headline-xl font-bold">
                        {new Date(urgentNotice.date).getDate()}
                      </span>
                      <span className="block text-label-md uppercase opacity-80">
                        {new Date(urgentNotice.date).toLocaleString('default', { month: 'long', year: 'numeric' })}
                      </span>
                      <div className="mt-4 border-t border-white/20 pt-4 text-label-sm">
                        Event Notice
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            )}

            {/* Filter and Search Bar */}
            <div className="sticky top-24 z-40 mb-12">
              <div className="bg-white/90 backdrop-blur-lg rounded-full shadow-lg border border-surface-variant p-2 flex flex-col md:flex-row items-center gap-4">
                <div className="flex-1 w-full relative flex items-center">
                  <span className="material-symbols-outlined ml-4 text-on-surface-variant">search</span>
                  <input 
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="w-full border-none bg-transparent px-4 py-2 focus:ring-0 text-body-md focus:outline-none" 
                    placeholder="Search by keyword, content, or category..." 
                    type="text"
                  />
                </div>
                <div className="flex items-center gap-2 px-2 overflow-x-auto no-scrollbar w-full md:w-auto">
                  {['All', 'Academic', 'Exam', 'Admissions', 'Holidays'].map((category) => (
                    <button 
                      key={category}
                      onClick={() => setCategoryFilter(category)}
                      className={`px-6 py-2 rounded-full text-label-md transition-all font-semibold ${
                        categoryFilter === category 
                          ? 'bg-primary text-on-primary' 
                          : 'bg-surface-container text-on-surface-variant hover:bg-primary-container/20'
                      }`}
                    >
                      {category}
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {/* Notices Grid */}
            {loading ? (
              <div className="text-center py-20 text-on-surface-variant">
                <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
                <p>Loading notices...</p>
              </div>
            ) : filtered.length === 0 ? (
              <div className="text-center py-20 text-on-surface-variant">
                <span className="material-symbols-outlined text-6xl mb-4">search_off</span>
                <p className="text-lg font-headline">No notices match your filters.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-20">
                {filtered.map((notice) => (
                  <div key={notice._id} className="notice-card bg-white border border-surface-variant rounded-xl p-8 flex flex-col transition-all duration-300 hover:shadow-xl shadow-sm">
                    <div className="w-14 h-14 rounded-lg bg-primary-container/20 flex items-center justify-center mb-6">
                      <span className="material-symbols-outlined text-primary text-3xl">
                        {notice.category === 'Exam' ? 'quiz' : notice.category === 'Admissions' ? 'person_add' : notice.category === 'Holidays' ? 'beach_access' : 'description'}
                      </span>
                    </div>
                    <span className="text-label-sm text-tertiary font-bold mb-2">{notice.category}</span>
                    <h3 className="font-headline font-semibold text-xl mb-4 text-on-surface leading-snug">{notice.title}</h3>
                    <p className="text-body-md text-on-surface-variant mb-8 flex-grow leading-relaxed">
                      {notice.content}
                    </p>
                    <div className="flex items-center justify-between mt-auto pt-6 border-t border-surface-variant/50">
                      <span className="text-label-sm text-on-surface-variant flex items-center gap-1">
                        <span className="material-symbols-outlined text-sm">calendar_month</span>
                        {new Date(notice.date).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })}
                      </span>
                      <button className="text-primary font-bold flex items-center gap-1 hover:gap-2 transition-all">
                        <span className="material-symbols-outlined text-sm">download</span>
                        PDF
                      </button>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </section>
      </main>
      <Footer />
    </div>
  );
}
