import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { 
  Bell, 
  CheckCheck, 
  Trash2, 
  ChevronLeft, 
  ChevronRight, 
  RefreshCw,
  MessageSquare,
  UserPlus,
  CheckCircle,
  XCircle,
  Clock,
  AlertTriangle,
  AlertCircle,
  FileText
} from 'lucide-react';
import notificationApi, { Notification } from '@/services/notificationApi';
import { formatDistanceToNow } from 'date-fns';

interface NotificationsProps {
  onNavigate?: (page: string) => void;
}

export function Notifications({ onNavigate }: NotificationsProps) {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [filter, setFilter] = useState<'all' | 'unread'>('all');
  const [refreshing, setRefreshing] = useState(false);

  const ITEMS_PER_PAGE = 20;

  const fetchNotifications = async (page: number = currentPage, unreadOnly: boolean = filter === 'unread') => {
    try {
      setLoading(page === 1);
      const result = await notificationApi.list({ page, limit: ITEMS_PER_PAGE, unreadOnly });
      
      const notifs = result.data?.notifications || [];
      // Extract pagination data from the response
      const pagination = result.data?.pagination || {};
      const total = pagination.total || 0;
      const totalPages = pagination.totalPages || 1;
      
      setNotifications(notifs);
      setTotalCount(total);
      setTotalPages(totalPages);
      setCurrentPage(page); // Update current page to match what was fetched
    } catch (error) {
      console.error('[Notifications] Failed to fetch:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useEffect(() => {
    setCurrentPage(1); // Reset to page 1 when filter changes
    fetchNotifications(1, filter === 'unread');
  }, [filter]);

  const handleNotificationClick = async (notification: Notification) => {
    try {
      // Mark as read
      if (!notification.isRead) {
        await notificationApi.markAsRead(notification.notificationId);
        setNotifications(prev => 
          prev.map(n => n.notificationId === notification.notificationId ? { ...n, isRead: true } : n)
        );
      }

      // Navigate to the request if URL provided
      if (notification.actionUrl && onNavigate) {
        const requestNumber = notification.metadata?.requestNumber;
        if (requestNumber) {
          let navigationUrl = `request/${requestNumber}`;
          
          // Work note related notifications should open Work Notes tab
          if (notification.notificationType === 'mention' || 
              notification.notificationType === 'comment' || 
              notification.notificationType === 'worknote') {
            navigationUrl += '?tab=worknotes';
          }
          
          // Document added notifications should open Documents tab
          if (notification.notificationType === 'document_added') {
            navigationUrl += '?tab=documents';
          }
          
          onNavigate(navigationUrl);
        }
      }
    } catch (error) {
      console.error('[Notifications] Error handling notification click:', error);
    }
  };

  const handleMarkAllAsRead = async () => {
    try {
      setRefreshing(true);
      await notificationApi.markAllAsRead();
      await fetchNotifications(currentPage, filter === 'unread');
    } catch (error) {
      console.error('[Notifications] Error marking all as read:', error);
      setRefreshing(false);
    }
  };

  const handleDelete = async (notificationId: string) => {
    try {
      await notificationApi.delete(notificationId);
      setNotifications(prev => prev.filter(n => n.notificationId !== notificationId));
      setTotalCount(prev => prev - 1);
    } catch (error) {
      console.error('[Notifications] Error deleting notification:', error);
    }
  };

  const handleRefresh = () => {
    setRefreshing(true);
    fetchNotifications(currentPage, filter === 'unread');
  };

  const handlePageChange = (newPage: number) => {
    if (newPage < 1 || newPage > totalPages) return;
    setCurrentPage(newPage);
    fetchNotifications(newPage, filter === 'unread');
  };

  const getNotificationIcon = (type: string) => {
    const iconClass = "w-6 h-6";
    
    switch (type) {
      case 'mention':
      case 'comment':
        return <MessageSquare className={`${iconClass} text-blue-600`} />;
      case 'worknote':
        return <FileText className={`${iconClass} text-purple-600`} />;
      case 'document_added':
        return <FileText className={`${iconClass} text-teal-600`} />;
      case 'assignment':
        return <UserPlus className={`${iconClass} text-indigo-600`} />;
      case 'approval':
        return <CheckCircle className={`${iconClass} text-green-600`} />;
      case 'rejection':
        return <XCircle className={`${iconClass} text-red-600`} />;
      case 'tat_alert':
        return <Clock className={`${iconClass} text-orange-600`} />;
      case 'tat_breach':
        return <AlertCircle className={`${iconClass} text-red-600`} />;
      case 'tat_breach_initiator':
        return <AlertTriangle className={`${iconClass} text-amber-600`} />;
      default:
        return <Bell className={`${iconClass} text-gray-600`} />;
    }
  };

  const getPriorityColor = (priority?: string) => {
    switch (priority?.toUpperCase()) {
      case 'URGENT':
        return 'bg-red-100 text-red-800 border-red-200';
      case 'HIGH':
        return 'bg-orange-100 text-orange-800 border-orange-200';
      case 'MEDIUM':
        return 'bg-blue-100 text-blue-800 border-blue-200';
      default:
        return 'bg-gray-100 text-gray-800 border-gray-200';
    }
  };

  const unreadCount = notifications.filter(n => !n.isRead).length;

  return (
    <div className="max-w-6xl mx-auto space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-3">
            <Bell className="w-8 h-8 text-blue-600" />
            Notifications
          </h1>
          <p className="text-gray-600 mt-1">
            {totalCount} total notification{totalCount !== 1 ? 's' : ''}
            {unreadCount > 0 && ` • ${unreadCount} unread`}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleRefresh}
            disabled={refreshing}
            className="gap-2"
          >
            <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
            Refresh
          </Button>
          {unreadCount > 0 && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleMarkAllAsRead}
              disabled={refreshing}
              className="gap-2"
            >
              <CheckCheck className="w-4 h-4" />
              Mark All Read
            </Button>
          )}
        </div>
      </div>

      {/* Filter Tabs */}
      <div className="flex gap-2">
        <Button
          variant={filter === 'all' ? 'default' : 'outline'}
          size="sm"
          onClick={() => {
            setFilter('all');
            setCurrentPage(1);
          }}
        >
          All Notifications
        </Button>
        <Button
          variant={filter === 'unread' ? 'default' : 'outline'}
          size="sm"
          onClick={() => {
            setFilter('unread');
            setCurrentPage(1);
          }}
        >
          Unread
          {unreadCount > 0 && (
            <Badge className="ml-2 bg-red-500 text-white">
              {unreadCount}
            </Badge>
          )}
        </Button>
      </div>

      {/* Notifications List */}
      <Card>
        <CardHeader>
          <CardTitle>Recent Activity</CardTitle>
          <CardDescription>
            Stay updated with all your workflow activities and mentions
          </CardDescription>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
            </div>
          ) : notifications.length === 0 ? (
            <div className="text-center py-12">
              <Bell className="w-16 h-16 text-gray-300 mx-auto mb-4" />
              <p className="text-lg font-medium text-gray-900 mb-2">No notifications</p>
              <p className="text-sm text-gray-500">
                {filter === 'unread' 
                  ? "You're all caught up! No unread notifications."
                  : "You don't have any notifications yet."}
              </p>
            </div>
          ) : (
            <div className="space-y-2">
              {notifications.map((notif) => (
                <div
                  key={notif.notificationId}
                  className={`p-4 rounded-lg border transition-all cursor-pointer hover:shadow-md ${
                    !notif.isRead 
                      ? 'bg-blue-50 border-blue-200 hover:bg-blue-100' 
                      : 'bg-white border-gray-200 hover:bg-gray-50'
                  }`}
                  onClick={() => handleNotificationClick(notif)}
                >
                  <div className="flex items-start gap-4">
                    {/* Icon */}
                    <div className="shrink-0 mt-0.5">
                      {getNotificationIcon(notif.notificationType)}
                    </div>

                    {/* Content */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2 mb-1">
                        <h4 className={`text-sm ${!notif.isRead ? 'font-bold' : 'font-semibold'} text-gray-900`}>
                          {notif.title}
                        </h4>
                        <div className="flex items-center gap-2 shrink-0">
                          {notif.priority && notif.priority !== 'LOW' && (
                            <Badge 
                              variant="outline" 
                              className={`text-xs ${getPriorityColor(notif.priority)}`}
                            >
                              {notif.priority}
                            </Badge>
                          )}
                          {!notif.isRead && (
                            <div className="w-2 h-2 rounded-full bg-blue-600"></div>
                          )}
                        </div>
                      </div>
                      
                      <p className="text-sm text-gray-700 mb-2 line-clamp-2">
                        {notif.message}
                      </p>
                      
                      <div className="flex items-center justify-between">
                        <p className="text-xs text-gray-500">
                          {formatDistanceToNow(new Date(notif.createdAt), { addSuffix: true })}
                          {notif.metadata?.requestNumber && (
                            <span className="ml-2">• {notif.metadata.requestNumber}</span>
                          )}
                        </p>
                        
                        <Button
                          variant="ghost"
                          size="sm"
                          className="h-7 w-7 p-0 hover:bg-red-100 hover:text-red-600"
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDelete(notif.notificationId);
                          }}
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>

      {/* Pagination */}
      {!loading && totalPages > 1 && (
        <div className="flex items-center justify-between">
          <p className="text-sm text-gray-600">
            Showing {((currentPage - 1) * ITEMS_PER_PAGE) + 1} to {Math.min(currentPage * ITEMS_PER_PAGE, totalCount)} of {totalCount} notifications
          </p>
          
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              size="sm"
              onClick={() => handlePageChange(currentPage - 1)}
              disabled={currentPage === 1}
            >
              <ChevronLeft className="w-4 h-4" />
              Previous
            </Button>
            
            <div className="flex items-center gap-1">
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (currentPage <= 3) {
                  pageNum = i + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = currentPage - 2 + i;
                }
                
                return (
                  <Button
                    key={pageNum}
                    variant={currentPage === pageNum ? 'default' : 'outline'}
                    size="sm"
                    className="w-9 h-9 p-0"
                    onClick={() => handlePageChange(pageNum)}
                  >
                    {pageNum}
                  </Button>
                );
              })}
            </div>
            
            <Button
              variant="outline"
              size="sm"
              onClick={() => handlePageChange(currentPage + 1)}
              disabled={currentPage === totalPages}
            >
              Next
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>
      )}
    </div>
  );
}

