'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Bell,
  Search,
  Filter,
  RefreshCw,
  Mail,
  MessageSquare,
  CheckCircle,
  XCircle,
  Clock,
  Eye,
  RotateCcw,
  Trash2,
  Calendar,
  FileText,
  DollarSign,
  Pill,
  Stethoscope,
  AlertTriangle,
  Check,
  X,
} from 'lucide-react';
import ProtectedRoute from '../protected-route';
import SidebarLayout from '../components/sidebar-layout';
import { useTranslations } from '../hooks/useTranslations';

interface Notification {
  _id: string;
  type: string;
  recipientId: string;
  recipientType: string;
  recipientEmail?: string;
  recipientPhone?: string;
  title: string;
  message: string;
  channels: string[];
  status: string;
  priority: string;
  scheduledFor?: string;
  sentAt?: string;
  readAt?: string;
  relatedEntity?: {
    type: string;
    id: string;
  };
  deliveryStatus: {
    email?: { sent: boolean; error?: string };
    sms?: { sent: boolean; error?: string };
    inApp?: { sent: boolean };
  };
  createdAt: string;
}

interface Stats {
  pending: number;
  sent: number;
  failed: number;
  read: number;
  sentToday: number;
}

const TYPE_ICONS: Record<string, any> = {
  appointment_reminder: Calendar,
  lab_result: FileText,
  payment_due: DollarSign,
  medication_reminder: Pill,
  follow_up: Stethoscope,
  system: Bell,
};

const TYPE_COLORS: Record<string, string> = {
  appointment_reminder: 'bg-blue-100 text-blue-800',
  lab_result: 'bg-purple-100 text-purple-800',
  payment_due: 'bg-yellow-100 text-yellow-800',
  medication_reminder: 'bg-green-100 text-green-800',
  follow_up: 'bg-cyan-100 text-cyan-800',
  system: 'bg-gray-100 text-gray-800',
};

const STATUS_COLORS: Record<string, string> = {
  pending: 'bg-yellow-100 text-yellow-800',
  sent: 'bg-blue-100 text-blue-800',
  failed: 'bg-red-100 text-red-800',
  read: 'bg-green-100 text-green-800',
};

const PRIORITY_COLORS: Record<string, string> = {
  low: 'bg-gray-100 text-gray-800',
  normal: 'bg-blue-100 text-blue-800',
  high: 'bg-orange-100 text-orange-800',
  urgent: 'bg-red-100 text-red-800',
};

export default function NotificationsPage() {
  const { t, translationsLoaded } = useTranslations();
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [stats, setStats] = useState<Stats>({ pending: 0, sent: 0, failed: 0, read: 0, sentToday: 0 });
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [statusFilter, setStatusFilter] = useState('all');
  const [selectedNotification, setSelectedNotification] = useState<Notification | null>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);

  const fetchNotifications = useCallback(async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams();
      if (typeFilter !== 'all') params.append('type', typeFilter);
      if (statusFilter !== 'all') params.append('status', statusFilter);

      const response = await fetch(`/api/notifications?${params.toString()}`);
      if (response.ok) {
        const data = await response.json();
        setNotifications(data.notifications || []);
        setStats(data.stats || { pending: 0, sent: 0, failed: 0, read: 0, sentToday: 0 });
      }
    } catch (error) {
      console.error('Error fetching notifications:', error);
    } finally {
      setLoading(false);
    }
  }, [typeFilter, statusFilter]);

  useEffect(() => {
    fetchNotifications();
  }, [fetchNotifications]);

  const handleMarkAsRead = async (id: string) => {
    try {
      const response = await fetch(`/api/notifications/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'markAsRead' }),
      });
      if (response.ok) {
        fetchNotifications();
      }
    } catch (error) {
      console.error('Error marking as read:', error);
    }
  };

  const handleRetry = async (id: string) => {
    try {
      const response = await fetch(`/api/notifications/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'retry' }),
      });
      if (response.ok) {
        fetchNotifications();
      }
    } catch (error) {
      console.error('Error retrying notification:', error);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm(t('notifications.confirmDelete'))) return;
    
    try {
      const response = await fetch(`/api/notifications/${id}`, {
        method: 'DELETE',
      });
      if (response.ok) {
        fetchNotifications();
        if (selectedNotification?._id === id) {
          setShowDetailsModal(false);
          setSelectedNotification(null);
        }
      }
    } catch (error) {
      console.error('Error deleting notification:', error);
    }
  };

  const formatDate = (dateStr: string) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString();
  };

  const formatTypeLabel = (type: string) => {
    const typeMap: Record<string, string> = {
      'appointment_reminder': t('notifications.types.appointmentReminder'),
      'lab_result': t('notifications.types.labResult'),
      'payment_due': t('notifications.types.paymentDue'),
      'medication_reminder': t('notifications.types.medicationReminder'),
      'follow_up': t('notifications.types.followUp'),
      'system': t('notifications.types.system')
    };
    return typeMap[type] || type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  };

  const formatStatusLabel = (status: string) => {
    const statusMap: Record<string, string> = {
      'pending': t('notifications.pending'),
      'sent': t('notifications.sent'),
      'failed': t('notifications.failed'),
      'read': t('notifications.read')
    };
    return statusMap[status] || status;
  };

  const formatPriorityLabel = (priority: string) => {
    const priorityMap: Record<string, string> = {
      'low': t('notifications.priorities.low'),
      'normal': t('notifications.priorities.normal'),
      'high': t('notifications.priorities.high'),
      'urgent': t('notifications.priorities.urgent')
    };
    return priorityMap[priority] || priority;
  };

  const filteredNotifications = notifications.filter(n => 
    n.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    n.message.toLowerCase().includes(searchTerm.toLowerCase()) ||
    n.recipientEmail?.toLowerCase().includes(searchTerm.toLowerCase()) ||
    n.recipientPhone?.includes(searchTerm)
  );

  if (!translationsLoaded) {
    return <div className="flex items-center justify-center h-screen">Loading...</div>;
  }

  return (
    <ProtectedRoute requiredRoles={['admin', 'staff', 'doctor']}>
      <SidebarLayout title={t('notifications.title')} description={t('notifications.description')}>
        <div className="space-y-6">
          {/* Header Actions */}
          <div className="flex justify-end">
            <button
              onClick={fetchNotifications}
              className="flex items-center gap-2 px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              <RefreshCw className="h-4 w-4" />
              {t('notifications.refresh')}
            </button>
          </div>

          {/* Stats Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-5 gap-4">
            <div className="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">{t('notifications.sentToday')}</span>
                <Bell className="h-5 w-5 text-blue-500" />
              </div>
              <p className="text-2xl font-bold text-gray-900 mt-1">{stats.sentToday}</p>
            </div>
            <div className="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">{t('notifications.pending')}</span>
                <Clock className="h-5 w-5 text-yellow-500" />
              </div>
              <p className="text-2xl font-bold text-yellow-600 mt-1">{stats.pending}</p>
            </div>
            <div className="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">{t('notifications.sent')}</span>
                <CheckCircle className="h-5 w-5 text-blue-500" />
              </div>
              <p className="text-2xl font-bold text-blue-600 mt-1">{stats.sent}</p>
            </div>
            <div className="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">{t('notifications.failed')}</span>
                <XCircle className="h-5 w-5 text-red-500" />
              </div>
              <p className="text-2xl font-bold text-red-600 mt-1">{stats.failed}</p>
            </div>
            <div className="bg-white rounded-lg shadow-sm p-4 border border-gray-200">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-500">{t('notifications.read')}</span>
                <Eye className="h-5 w-5 text-green-500" />
              </div>
              <p className="text-2xl font-bold text-green-600 mt-1">{stats.read}</p>
            </div>
          </div>

          {/* Filters */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
            <div className="flex flex-col sm:flex-row gap-4">
              <div className="flex-1 relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
                <input
                  type="text"
                  placeholder={t('notifications.searchPlaceholder')}
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                />
              </div>
              <select
                value={typeFilter}
                onChange={(e) => setTypeFilter(e.target.value)}
                className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">{t('notifications.allTypes')}</option>
                <option value="appointment_reminder">{t('notifications.types.appointmentReminder')}</option>
                <option value="lab_result">{t('notifications.types.labResult')}</option>
                <option value="payment_due">{t('notifications.types.paymentDue')}</option>
                <option value="medication_reminder">{t('notifications.types.medicationReminder')}</option>
                <option value="follow_up">{t('notifications.types.followUp')}</option>
                <option value="system">{t('notifications.types.system')}</option>
              </select>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="all">{t('notifications.allStatus')}</option>
                <option value="pending">{t('notifications.pending')}</option>
                <option value="sent">{t('notifications.sent')}</option>
                <option value="failed">{t('notifications.failed')}</option>
                <option value="read">{t('notifications.read')}</option>
              </select>
            </div>
          </div>

          {/* Notifications Table */}
          <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
            {loading ? (
              <div className="p-8 text-center">
                <RefreshCw className="h-8 w-8 animate-spin mx-auto text-gray-400" />
                <p className="mt-2 text-gray-500">{t('notifications.loading')}</p>
              </div>
            ) : filteredNotifications.length === 0 ? (
              <div className="p-8 text-center">
                <Bell className="h-12 w-12 mx-auto text-gray-400" />
                <p className="mt-2 text-gray-500">{t('notifications.noNotifications')}</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.type')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.title')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.recipient')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.channels')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.status')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.priority')}</th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.date')}</th>
                      <th className="px-4 py-3 text-right text-xs font-medium text-gray-500 uppercase">{t('notifications.tableHeaders.actions')}</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200">
                    {filteredNotifications.map((notification) => {
                      const TypeIcon = TYPE_ICONS[notification.type] || Bell;
                      return (
                        <tr key={notification._id} className="hover:bg-gray-50">
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-2">
                              <div className={`p-2 rounded-lg ${TYPE_COLORS[notification.type] || 'bg-gray-100'}`}>
                                <TypeIcon className="h-4 w-4" />
                              </div>
                              <span className="text-sm text-gray-600">
                                {formatTypeLabel(notification.type)}
                              </span>
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <p className="text-sm font-medium text-gray-900 truncate max-w-[200px]">
                              {notification.title}
                            </p>
                          </td>
                          <td className="px-4 py-3">
                            <div className="text-sm">
                              {notification.recipientEmail && (
                                <p className="text-gray-600 truncate max-w-[150px]">{notification.recipientEmail}</p>
                              )}
                              {notification.recipientPhone && (
                                <p className="text-gray-500 text-xs">{notification.recipientPhone}</p>
                              )}
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center gap-1">
                              {notification.channels.includes('email') && (
                                <div className={`p-1 rounded ${notification.deliveryStatus.email?.sent ? 'text-green-600' : 'text-gray-400'}`}>
                                  <Mail className="h-4 w-4" />
                                </div>
                              )}
                              {notification.channels.includes('sms') && (
                                <div className={`p-1 rounded ${notification.deliveryStatus.sms?.sent ? 'text-green-600' : 'text-gray-400'}`}>
                                  <MessageSquare className="h-4 w-4" />
                                </div>
                              )}
                              {notification.channels.includes('in_app') && (
                                <div className={`p-1 rounded ${notification.deliveryStatus.inApp?.sent ? 'text-green-600' : 'text-gray-400'}`}>
                                  <Bell className="h-4 w-4" />
                                </div>
                              )}
                            </div>
                          </td>
                          <td className="px-4 py-3">
                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${STATUS_COLORS[notification.status]}`}>
                              {formatStatusLabel(notification.status)}
                            </span>
                          </td>
                          <td className="px-4 py-3">
                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${PRIORITY_COLORS[notification.priority]}`}>
                              {formatPriorityLabel(notification.priority)}
                            </span>
                          </td>
                          <td className="px-4 py-3 text-sm text-gray-500">
                            {formatDate(notification.createdAt)}
                          </td>
                          <td className="px-4 py-3">
                            <div className="flex items-center justify-end gap-1">
                              <button
                                onClick={() => {
                                  setSelectedNotification(notification);
                                  setShowDetailsModal(true);
                                }}
                                className="p-1 text-gray-400 hover:text-blue-600"
                                title={t('notifications.viewDetails')}
                              >
                                <Eye className="h-4 w-4" />
                              </button>
                              {notification.status === 'sent' && (
                                <button
                                  onClick={() => handleMarkAsRead(notification._id)}
                                  className="p-1 text-gray-400 hover:text-green-600"
                                  title={t('notifications.markAsRead')}
                                >
                                  <Check className="h-4 w-4" />
                                </button>
                              )}
                              {notification.status === 'failed' && (
                                <button
                                  onClick={() => handleRetry(notification._id)}
                                  className="p-1 text-gray-400 hover:text-orange-600"
                                  title={t('notifications.retry')}
                                >
                                  <RotateCcw className="h-4 w-4" />
                                </button>
                              )}
                              <button
                                onClick={() => handleDelete(notification._id)}
                                className="p-1 text-gray-400 hover:text-red-600"
                                title={t('notifications.delete')}
                              >
                                <Trash2 className="h-4 w-4" />
                              </button>
                            </div>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>

        {/* Details Modal */}
        {showDetailsModal && selectedNotification && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
            <div className="bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto m-4">
              <div className="flex items-center justify-between p-4 border-b border-gray-200">
                <h2 className="text-lg font-semibold text-gray-900">{t('notifications.notificationDetails')}</h2>
                <button
                  onClick={() => setShowDetailsModal(false)}
                  className="text-gray-400 hover:text-gray-600"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>
              <div className="p-4 space-y-4">
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.type')}</label>
                    <p className="text-gray-900">{formatTypeLabel(selectedNotification.type)}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.status')}</label>
                    <p>
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${STATUS_COLORS[selectedNotification.status]}`}>
                        {formatStatusLabel(selectedNotification.status)}
                      </span>
                    </p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.priority')}</label>
                    <p>
                      <span className={`px-2 py-1 rounded-full text-xs font-medium ${PRIORITY_COLORS[selectedNotification.priority]}`}>
                        {formatPriorityLabel(selectedNotification.priority)}
                      </span>
                    </p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.created')}</label>
                    <p className="text-gray-900">{formatDate(selectedNotification.createdAt)}</p>
                  </div>
                </div>

                <div>
                  <label className="text-sm font-medium text-gray-500">{t('notifications.titleLabel')}</label>
                  <p className="text-gray-900">{selectedNotification.title}</p>
                </div>

                <div>
                  <label className="text-sm font-medium text-gray-500">{t('notifications.message')}</label>
                  <p className="text-gray-900 whitespace-pre-wrap">{selectedNotification.message}</p>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.email')}</label>
                    <p className="text-gray-900">{selectedNotification.recipientEmail || '-'}</p>
                  </div>
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.phone')}</label>
                    <p className="text-gray-900">{selectedNotification.recipientPhone || '-'}</p>
                  </div>
                </div>

                <div>
                  <label className="text-sm font-medium text-gray-500">{t('notifications.deliveryStatus')}</label>
                  <div className="mt-2 space-y-2">
                    {selectedNotification.channels.includes('email') && (
                      <div className="flex items-center justify-between bg-gray-50 p-2 rounded">
                        <div className="flex items-center gap-2">
                          <Mail className="h-4 w-4 text-gray-500" />
                          <span>{t('notifications.email')}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          {selectedNotification.deliveryStatus.email?.sent ? (
                            <CheckCircle className="h-4 w-4 text-green-500" />
                          ) : (
                            <XCircle className="h-4 w-4 text-red-500" />
                          )}
                          {selectedNotification.deliveryStatus.email?.error && (
                            <span className="text-xs text-red-500">{selectedNotification.deliveryStatus.email.error}</span>
                          )}
                        </div>
                      </div>
                    )}
                    {selectedNotification.channels.includes('sms') && (
                      <div className="flex items-center justify-between bg-gray-50 p-2 rounded">
                        <div className="flex items-center gap-2">
                          <MessageSquare className="h-4 w-4 text-gray-500" />
                          <span>{t('notifications.sms')}</span>
                        </div>
                        <div className="flex items-center gap-2">
                          {selectedNotification.deliveryStatus.sms?.sent ? (
                            <CheckCircle className="h-4 w-4 text-green-500" />
                          ) : (
                            <XCircle className="h-4 w-4 text-red-500" />
                          )}
                          {selectedNotification.deliveryStatus.sms?.error && (
                            <span className="text-xs text-red-500">{selectedNotification.deliveryStatus.sms.error}</span>
                          )}
                        </div>
                      </div>
                    )}
                    {selectedNotification.channels.includes('in_app') && (
                      <div className="flex items-center justify-between bg-gray-50 p-2 rounded">
                        <div className="flex items-center gap-2">
                          <Bell className="h-4 w-4 text-gray-500" />
                          <span>{t('notifications.inApp')}</span>
                        </div>
                        <div>
                          {selectedNotification.deliveryStatus.inApp?.sent ? (
                            <CheckCircle className="h-4 w-4 text-green-500" />
                          ) : (
                            <XCircle className="h-4 w-4 text-red-500" />
                          )}
                        </div>
                      </div>
                    )}
                  </div>
                </div>

                {selectedNotification.scheduledFor && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.scheduledFor')}</label>
                    <p className="text-gray-900">{formatDate(selectedNotification.scheduledFor)}</p>
                  </div>
                )}

                {selectedNotification.sentAt && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.sentAt')}</label>
                    <p className="text-gray-900">{formatDate(selectedNotification.sentAt)}</p>
                  </div>
                )}

                {selectedNotification.readAt && (
                  <div>
                    <label className="text-sm font-medium text-gray-500">{t('notifications.readAt')}</label>
                    <p className="text-gray-900">{formatDate(selectedNotification.readAt)}</p>
                  </div>
                )}
              </div>
              <div className="flex justify-end gap-2 p-4 border-t border-gray-200">
                {selectedNotification.status === 'failed' && (
                  <button
                    onClick={() => {
                      handleRetry(selectedNotification._id);
                      setShowDetailsModal(false);
                    }}
                    className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700"
                  >
                    {t('notifications.retrySend')}
                  </button>
                )}
                <button
                  onClick={() => setShowDetailsModal(false)}
                  className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200"
                >
                  {t('notifications.close')}
                </button>
              </div>
            </div>
          </div>
        )}
      </SidebarLayout>
    </ProtectedRoute>
  );
}
