'use client';
import axios from 'axios';
import Layout from "@/components/layout/Layout";
import Link from "next/link";
import { useState, useEffect } from 'react';

export default function Memories() {
  const [selectedYear, setSelectedYear] = useState('');
  const [events, setEvents] = useState([]);
  const [years, setYears] = useState([]);

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

  const getEvents = async () => {
    try {
      const eventRes = await axios.get(
        'https://api.tamilculturewaterloo.org/api/events/'
      );

      const eventsData = eventRes?.data?.data || [];
      setEvents(eventsData);

      // Extract unique years & sort (latest first)
      const uniqueYears = [...new Set(eventsData.map(event => event.year))].sort((a, b) => b - a);
      setYears(uniqueYears);

      // Default to latest year immediately
      if (uniqueYears.length > 0) {
        setSelectedYear(uniqueYears[0]);
      }
    } catch (error) {
      console.log("error fetching data", error);
    }
  };

  // Filter events by selected year
  const filteredEvents = events.filter(event => event.year === selectedYear);

  return (
    <Layout headerStyle={1} footerStyle={1}>
      <div>
        {/* Header Section */}
        <div
          className="inner-page-header"
          style={{ backgroundImage: 'url(/assets/img/event/gallery/gallery-banner.webp)' }}
        >
          <div className="container">
            <div className="row">
              <div className="col-lg-12 m-auto">
                <div className="heading1">
                  <h1>Recent Memories</h1>
                  <div className="space20" />
                  <Link href="/">
                    Home <i className="fa-solid fa-angle-right" /> <span>Recent Memories</span>
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Memory Section */}
        <div className="memory-inner-section-area blog-details-section sp4">
          <div className="container">
            <div className="row gx-5">
              {/* Left Column: Year Tabs */}
              <div className="col-lg-3 mb-4 mb-lg-0">
                <div className="blog-auhtor-details sticky-top" style={{ top: "120px" }}>
                  <div className="blog-categories">
                    <ul className="list-unstyled">
                      {years.map((year) => (
                        <li key={year}>
                          <button
                            onClick={() => setSelectedYear(year)}
                            className={`btn w-100 mb-2 category-btn ${selectedYear === year ? 'active' : ''}`}
                          >
                            Year {year}
                          </button>
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>

              {/* Right Column: Gallery */}
              <div className="col-lg-9">
                <div className="row justify-content-start">
                  {filteredEvents.map((event, idx) => (
                    <div className="col-lg-4 col-md-6 mb-4" key={idx}>
                      <div className="memory3-boxarea">
                        <div className="img1">
                          <img src={event.eventimageurl} alt={event.eventtitle} />
                        </div>
                        <div className="content-area">
                          <p>{event.eventdate}</p>
                          <div className="space12" />
                          <Link href={`/photo-gallery/single-gallery?id=${event.id}`}>
                            {event.eventtitle}
                          </Link>
                          <div className="plus">
                            <Link href={`/photo-gallery/single-gallery?id=${event.id}`}>
                              <i className="fa-solid fa-plus" />
                            </Link>
                          </div>
                        </div>
                      </div>
                    </div>
                  ))}
                  {filteredEvents.length === 0 && (
                    <div className="col-12 text-center">
                      <p>No events found for {selectedYear}</p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
}
