"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { RefreshCw } from "lucide-react";
import { useSession } from "next-auth/react";

interface NewsItem {
  id: string;
  title: string;
  date: string;
  category: string;
}

export function News() {
  const [news, setNews] = useState<NewsItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refreshing, setRefreshing] = useState(false);
  const { status } = useSession();

  const fetchNews = async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    setLoading(true);
    
    // Placeholder data - replace with actual API call
    const mockNews = [
      { id: '1', title: 'New Project Management Features Released', date: '2024-03-20', category: 'Product Update' },
      { id: '2', title: 'Team Meeting Schedule Changes', date: '2024-03-19', category: 'Announcement' },
      { id: '3', title: 'Upcoming Training Sessions', date: '2024-03-18', category: 'Training' },
    ];
    
    try {
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1000));
      setNews(mockNews);
      setError(null);
    } catch (err) {
      setError('Failed to fetch news');
      console.error('Error fetching news:', err);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    if (status === 'authenticated') {
      fetchNews();
    }
  }, [status]);

  if (status === 'loading' || loading) {
    return (
      <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
        <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
          <CardTitle className="text-lg font-semibold text-gray-800">News</CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          <p className="text-center text-gray-500">Loading...</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="transition-transform duration-500 ease-in-out transform hover:scale-105 bg-white/95 backdrop-blur-sm border-0 shadow-lg h-full">
      <CardHeader className="flex flex-row items-center justify-between pb-2 border-b border-gray-100">
        <CardTitle className="text-lg font-semibold text-gray-800">News</CardTitle>
        <Button
          variant="ghost"
          size="icon"
          onClick={() => fetchNews(true)}
          disabled={refreshing}
          className={`${refreshing ? 'animate-spin' : ''} text-gray-600 hover:text-gray-900`}
        >
          <RefreshCw className="h-4 w-4" />
        </Button>
      </CardHeader>
      <CardContent className="p-4">
        {error ? (
          <p className="text-center text-red-500">{error}</p>
        ) : (
          <div className="space-y-4 max-h-[300px] overflow-y-auto">
            {news.length === 0 ? (
              <p className="text-center text-gray-500">No news available</p>
            ) : (
              news.map((item) => (
                <div
                  key={item.id}
                  className="p-3 hover:bg-gray-50/50 rounded-lg transition-colors"
                >
                  <div className="flex items-center justify-between mb-1">
                    <span className="text-xs font-medium text-gray-500">{item.date}</span>
                    <span className="text-xs px-2 py-1 rounded-full bg-blue-50 text-blue-700">
                      {item.category}
                    </span>
                  </div>
                  <h3 className="text-sm font-medium text-gray-800">{item.title}</h3>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
