"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: number;
  title: string;
  displayDate: string;
  timestamp: string;
  source: string;
  description: string | null;
  category: string | null;
  url: 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);
    if (!isRefresh) setLoading(true);
    
    try {
      const response = await fetch('/api/news');
      if (!response.ok) {
        throw new Error('Failed to fetch news');
      }
      
      const data = await response.json();
      setNews(data);
      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 max-h-[32rem]">
        <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0 border-b border-gray-100">
          <CardTitle className="text-xl font-bold">News</CardTitle>
        </CardHeader>
        <CardContent className="p-6">
          <div className="flex items-center justify-center">
            <RefreshCw className="h-5 w-5 animate-spin text-gray-400" />
          </div>
        </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 max-h-[32rem]">
      <CardHeader className="flex flex-row items-center justify-between pb-2 space-y-0 border-b border-gray-100">
        <CardTitle className="text-xl font-bold">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-0 overflow-auto" style={{ height: 'calc(32rem - 57px)' }}>
        {error ? (
          <p className="text-center text-red-500 p-4">{error}</p>
        ) : (
          <div className="divide-y divide-gray-100">
            {news.length === 0 ? (
              <p className="text-center text-gray-500 p-4">No news available</p>
            ) : (
              news.map((item) => (
                <div
                  key={item.id}
                  className="px-4 py-3 hover:bg-gray-50 transition-colors cursor-pointer"
                  onClick={() => window.open(item.url, '_blank')}
                >
                  <h3 className="text-sm font-medium text-gray-900 line-clamp-2 mb-1.5">
                    {item.title}
                  </h3>
                  {item.description && (
                    <p className="text-sm text-gray-600 line-clamp-2 mb-2">
                      {item.description}
                    </p>
                  )}
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-gray-500">{item.displayDate}</span>
                    {item.category && (
                      <span className="text-sm font-medium text-blue-600">
                        {item.category}
                      </span>
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
