import React, { useState, useEffect } from 'react';
import api from '../../utils/api';
import Navbar from '../../components/Navbar';
import MemberFooter from '../../components/MemberFooter';
import { Card } from '../../components/ui/card';
import { Button } from '../../components/ui/button';
import { Badge } from '../../components/ui/badge';
import { Input } from '../../components/ui/input';
import { toast } from 'sonner';
import { FileText, ExternalLink, Calendar, Search } from 'lucide-react';

export default function NewsletterArchive() {
  const [newsletters, setNewsletters] = useState([]);
  const [years, setYears] = useState([]);
  const [selectedYear, setSelectedYear] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchYears();
    fetchNewsletters();
  }, []);

  const fetchYears = async () => {
    try {
      const response = await api.get('/newsletters/years');
      setYears(response.data);
    } catch (error) {
      console.error('Failed to load years');
    }
  };

  const fetchNewsletters = async (year = null) => {
    try {
      setLoading(true);
      const url = year ? `/newsletters?year=${year}` : '/newsletters';
      const response = await api.get(url);
      setNewsletters(response.data);
    } catch (error) {
      toast.error('Failed to load newsletters');
    } finally {
      setLoading(false);
    }
  };

  const handleYearFilter = (year) => {
    setSelectedYear(year);
    fetchNewsletters(year);
  };

  const clearFilter = () => {
    setSelectedYear(null);
    fetchNewsletters();
  };

  const filteredNewsletters = newsletters.filter(newsletter =>
    newsletter.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (newsletter.description && newsletter.description.toLowerCase().includes(searchTerm.toLowerCase()))
  );

  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  const groupByYear = (newsletters) => {
    const grouped = {};
    newsletters.forEach(newsletter => {
      const year = new Date(newsletter.published_date).getFullYear();
      if (!grouped[year]) {
        grouped[year] = [];
      }
      grouped[year].push(newsletter);
    });
    return grouped;
  };

  const groupedNewsletters = groupByYear(filteredNewsletters);
  const sortedYears = Object.keys(groupedNewsletters).sort((a, b) => b - a);

  if (loading) {
    return (
      <div className="min-h-screen bg-background">
        <Navbar />
        <div className="flex items-center justify-center min-h-[60vh]">
          <p className="text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Loading newsletters...
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-b from-[var(--neutral-100)] to-[var(--neutral-800)]">
      <Navbar />

      <div className="max-w-7xl mx-auto px-6 py-12">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-4xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Newsletter Archive
          </h1>
          <p className="text-brand-purple  mb-6" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Browse past monthly newsletters and stay informed about LOAF community updates.
          </p>

          {/* Filters */}
          <div className="flex gap-4 flex-wrap items-center">
            {/* Search */}
            <div className="relative flex-1 min-w-[300px]">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-brand-purple " />
              <Input
                type="text"
                placeholder="Search newsletters..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10 border-[var(--neutral-800)] focus:border-brand-purple "
              />
            </div>

            {/* Year Filter */}
            <div className="flex gap-2 flex-wrap">
              <Button
                onClick={clearFilter}
                variant={selectedYear === null ? "default" : "outline"}
                size="sm"
                className={selectedYear === null ? "bg-brand-purple hover:bg-[var(--purple-muted)]  text-white" : "border-brand-lavender  text-brand-lavender "}
              >
                All Years
              </Button>
              {years.map(year => (
                <Button
                  key={year}
                  onClick={() => handleYearFilter(year)}
                  variant={selectedYear === year ? "default" : "outline"}
                  size="sm"
                  className={selectedYear === year ? "bg-brand-purple  text-white" : "border-brand-purple  text-brand-purple "}
                >
                  {year}
                </Button>
              ))}
            </div>
          </div>
        </div>

        {/* Newsletter List */}
        {filteredNewsletters.length === 0 ? (
          <Card className="p-12 text-center bg-background rounded-2xl border border-[var(--neutral-800)]">
            <FileText className="h-16 w-16 text-[var(--neutral-800)] mx-auto mb-4" />
            <p className="text-brand-purple  text-lg" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              No newsletters found
            </p>
          </Card>
        ) : (
          <div className="space-y-8">
            {sortedYears.map(year => (
              <div key={year}>
                <h2 className="text-2xl font-semibold text-[var(--purple-ink)] mb-4 flex items-center gap-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                  <Calendar className="h-6 w-6" />
                  {year}
                </h2>
                <div className="grid md:grid-cols-2 gap-6">
                  {groupedNewsletters[year].map(newsletter => (
                    <Card key={newsletter.id} className="p-6 bg-background rounded-2xl border border-[var(--neutral-800)] hover:shadow-lg transition-shadow">
                      <div className="flex items-start gap-4">
                        <div className="bg-gradient-to-br from-brand-purple  to-[var(--purple-ink)] p-4 rounded-xl">
                          <FileText className="h-8 w-8 text-white" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <h3 className="text-xl font-semibold text-[var(--purple-ink)] mb-2" style={{ fontFamily: "'Inter', sans-serif" }}>
                            {newsletter.title}
                          </h3>
                          {newsletter.description && (
                            <p className="text-brand-purple  mb-3 line-clamp-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                              {newsletter.description}
                            </p>
                          )}
                          <div className="flex items-center gap-3 mb-4">
                            <Badge className="bg-[var(--neutral-800)] text-[var(--purple-ink)] hover:bg-[var(--neutral-800)]">
                              {formatDate(newsletter.published_date)}
                            </Badge>
                            <Badge variant="outline" className="border-brand-purple  text-brand-purple ">
                              {newsletter.document_type === 'google_docs' ? 'Google Docs' : newsletter.document_type.toUpperCase()}
                            </Badge>
                          </div>
                          <Button
                            onClick={() => window.open(newsletter.document_url, '_blank')}
                            className="w-full bg-brand-purple  text-white hover:bg-[var(--purple-muted)] rounded-full flex items-center justify-center gap-2"
                          >
                            <ExternalLink className="h-4 w-4" />
                            View Newsletter
                          </Button>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
      <MemberFooter />
    </div>
  );
}
