"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";
import { formatDistance } from 'date-fns';
import { fr } from 'date-fns/locale';

interface NewsItem {
  id: number;
  title: string;
  date: 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]);

  const formatDate = (dateString: string) => {
    try {
      const date = new Date(dateString);
      return formatDistance(date, new Date(), {
        addSuffix: true,
        locale: fr
      });
    } catch (err) {
      console.error('Error formatting date:', err);
      return dateString;
    }
  };

  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">
        <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-3">
          <div className="flex items-center justify-center py-6">
            <RefreshCw className="h-4 w-4 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">
      <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="h-7 w-7 p-0 hover:bg-gray-100/50 rounded-full"
        >
          <RefreshCw className="h-3.5 w-3.5 text-gray-600" />
        </Button>
      </CardHeader>
      <CardContent className="p-3">
        {error ? (
          <div className="text-xs text-red-500 text-center py-3">{error}</div>
        ) : (
          <div className="space-y-2 max-h-[400px] overflow-y-auto pr-1 scrollbar-thin scrollbar-thumb-gray-200 scrollbar-track-transparent">
            {news.length === 0 ? (
              <div className="text-xs text-gray-500 text-center py-6">No news available</div>
            ) : (
              news.map((item) => (
                <div
                  key={item.id}
                  className="p-2 rounded-lg bg-white shadow-sm hover:shadow-md transition-all duration-200 border border-gray-100"
                  onClick={() => window.open(item.url, '_blank')}
                >
                  <div className="flex flex-col gap-1">
                    <div className="flex items-center justify-between text-xs">
                      <span className="text-gray-500">{formatDate(item.date)}</span>
                    </div>
                    <h3 className="text-sm font-medium text-gray-800 line-clamp-2" title={item.title}>
                      {item.title}
                    </h3>
                    <p className="text-xs text-gray-500 line-clamp-2" title={item.description}>
                      {item.description}
                    </p>
                  </div>
                </div>
              ))
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}
