'use client';

import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { Bell, CheckCircle, XCircle, Calendar, MessageCircle, CheckCheck, Loader2 } from 'lucide-react';
import AuthService from '@/app/services/AuthService';
import { getUserNotifications } from '@/app/utils/api';

export default function NotificationsPage() {
  const { t } = useTranslation();
  const router = useRouter();
  const [notifications, setNotifications] = useState([]);
  const [unreadCount, setUnreadCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!AuthService.isAuthenticated()) {
      router.push('/login');
      return;
    }
    fetchNotifications();
  }, [router]);

  const fetchNotifications = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const data = await getUserNotifications();
      const items = Array.isArray(data) ? data : [];
      setNotifications(items);
      setUnreadCount(items.length);
    } catch (err) {
      console.error('Error fetching notifications:', err);
      setError(err.message || t('fetch-notifications-failed'));
    } finally {
      setIsLoading(false);
    }
  };

  const markAsRead = (id) => {
    setNotifications(prev =>
      prev.map(n => (n.id === id ? { ...n, read: true } : n))
    );
    setUnreadCount(prev => Math.max(0, prev - 1));
  };

  const markAllAsRead = () => {
    setNotifications(prev => prev.map(n => ({ ...n, read: true })));
    setUnreadCount(0);
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center"
        >
          <Loader2 className="w-12 h-12 text-amber-500 mx-auto mb-4 animate-spin" />
          <p className="text-gray-600">{t('loading')}</p>
        </motion.div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center"
        >
          <XCircle className="w-16 h-16 text-red-500 mx-auto mb-4" />
          <h3 className="text-xl font-bold text-gray-700 mb-2">{t('loading-error')}</h3>
          <p className="text-gray-500 mb-4">{error}</p>
          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={fetchNotifications}
            className="px-6 py-2 bg-amber-500 text-white rounded-xl font-medium hover:bg-amber-600 transition-colors"
          >
            {t('retry')}
          </motion.button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="container mx-auto px-4 max-w-4xl">
        <motion.div
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex justify-between items-center mb-8"
        >
          <div>
            <h1 className="text-3xl font-bold text-gray-900 mb-2">{t('notifications')}</h1>
            <p className="text-gray-600">
              {unreadCount > 0 ? t('unread-notifications', { count: unreadCount }) : t('all-notifications-read')}
            </p>
          </div>
          {unreadCount > 0 && (
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={markAllAsRead}
              className="flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-xl text-sm font-medium text-gray-700 hover:bg-gray-50 transition-all shadow-sm"
            >
              <CheckCheck className="w-4 h-4 text-amber-500" />
              {t('mark-all-read')}
            </motion.button>
          )}
        </motion.div>

        {notifications.length === 0 ? (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="bg-white rounded-2xl p-12 text-center border-2 border-dashed border-gray-300"
          >
            <Bell className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-xl font-bold text-gray-700 mb-2">{t('no-notifications')}</h3>
            <p className="text-gray-500">{t('notifications-empty-hint')}</p>
          </motion.div>
        ) : (
          <div className="space-y-4">
            <AnimatePresence>
              {notifications.map((notification, index) => (
                <motion.div
                  key={notification.id || index}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, x: 100 }}
                  transition={{ delay: index * 0.05, type: 'spring', stiffness: 100 }}
                  whileHover={{ scale: 1.01 }}
                  onClick={() => markAsRead(notification.id)}
                  className={`bg-white rounded-2xl shadow-sm border transition-all hover:shadow-md cursor-pointer ${
                    !notification.read ? 'border-amber-200 bg-amber-50/50' : 'border-gray-200'
                  }`}
                >
                  <div className="p-5 flex gap-4">
                    <div className={`w-12 h-12 rounded-full flex items-center justify-center shrink-0 ${
                      !notification.read ? 'bg-amber-100' : 'bg-gray-100'
                    }`}>
                      {!notification.read ? (
                        <Bell className="w-6 h-6 text-amber-600" />
                      ) : (
                        <CheckCircle className="w-6 h-6 text-gray-400" />
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex justify-between items-start gap-4">
                        <div className="min-w-0">
                          <h3 className={`text-base ${!notification.read ? 'font-bold text-gray-900' : 'font-medium text-gray-700'}`}>
                            {notification.title}
                          </h3>
                          {notification.message && (
                            <p className="text-gray-500 text-sm mt-1 line-clamp-2">{notification.message}</p>
                          )}
                          <div className="flex items-center gap-2 mt-2">
                            {notification.date && (
                              <span className="text-xs text-gray-400 flex items-center gap-1">
                                <Calendar className="w-3 h-3" />
                                {notification.date}
                              </span>
                            )}
                            {notification.type && (
                              <span className="text-xs text-gray-400 flex items-center gap-1">
                                <MessageCircle className="w-3 h-3" />
                                {notification.type}
                              </span>
                            )}
                          </div>
                        </div>
                        {!notification.read && (
                          <span className="w-2.5 h-2.5 bg-amber-500 rounded-full shrink-0 mt-2" />
                        )}
                      </div>
                    </div>
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>
          </div>
        )}
      </div>
    </div>
  );
}
