import React, { useState } from 'react';
import {
  Bell,
  Mail,
  MessageSquare,
  Smartphone,
  Plus,
  Eye,
  Filter,
  CheckCircle2,
  Clock,
  XCircle,
} from 'lucide-react';
import Loading from '../../shared/components/Loading';
import EmptyState from '../../shared/components/EmptyState';
import { useAsync } from '../../shared/hooks/useAsync';
import notificationService, { Notification } from '../../features/notifications/services/notificationService';
import { formatDate } from '../../shared/utils/format';
import SendNotificationModal from '../../features/notifications/components/SendNotificationModal';
import NotificationTemplatesModal from '../../features/notifications/components/NotificationTemplatesModal';

const NotificationManagementPage: React.FC = () => {
  const [showSendModal, setShowSendModal] = useState(false);
  const [showTemplatesModal, setShowTemplatesModal] = useState(false);
  const [filters, setFilters] = useState({
    notification_type: '',
    channel: '',
    status: '',
  });

  const { data: notifications, loading, execute: fetchNotifications } = useAsync<Notification[]>(
    async () => {
      const r = await notificationService.getNotifications({
        notification_type: filters.notification_type || undefined,
        channel: filters.channel || undefined,
        status: filters.status || undefined,
        limit: 100,
      });
      return Array.isArray(r.data) ? r.data : (r.data?.data || []);
    },
    { immediate: true }
  );

  const getChannelIcon = (channel: string) => {
    switch (channel) {
      case 'email':
        return <Mail className="w-5 h-5 text-blue-500" />;
      case 'sms':
        return <MessageSquare className="w-5 h-5 text-green-500" />;
      case 'push':
        return <Bell className="w-5 h-5 text-purple-500" />;
      case 'whatsapp':
        return <Smartphone className="w-5 h-5 text-emerald-500" />;
      default:
        return <Bell className="w-5 h-5 text-gray-500" />;
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'sent':
      case 'delivered':
        return <CheckCircle2 className="w-5 h-5 text-green-500" />;
      case 'read':
        return <Eye className="w-5 h-5 text-blue-500" />;
      case 'failed':
        return <XCircle className="w-5 h-5 text-red-500" />;
      default:
        return <Clock className="w-5 h-5 text-amber-500" />;
    }
  };

  const getStatusBadge = (status: string) => {
    const baseClasses = 'px-3 py-1 rounded-full text-xs font-semibold';
    switch (status) {
      case 'sent':
      case 'delivered':
        return `${baseClasses} bg-green-100 text-green-800 border border-green-200`;
      case 'read':
        return `${baseClasses} bg-blue-100 text-blue-800 border border-blue-200`;
      case 'failed':
        return `${baseClasses} bg-red-100 text-red-800 border border-red-200`;
      default:
        return `${baseClasses} bg-amber-100 text-amber-800 border border-amber-200`;
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 space-y-6">
        {/* Header */}
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
            <div>
              <h1 className="text-3xl font-bold text-gray-900 mb-2">Notification Management</h1>
              <p className="text-gray-600">Manage and send multi-channel notifications</p>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={() => setShowTemplatesModal(true)}
                className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition-colors flex items-center gap-2"
              >
                <Bell className="w-5 h-5" />
                Templates
              </button>
              <button
                onClick={() => setShowSendModal(true)}
                className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors flex items-center gap-2"
              >
                <Plus className="w-5 h-5" />
                Send Notification
              </button>
            </div>
          </div>
        </div>

        {/* Filters */}
        <div className="bg-white rounded-xl shadow-lg p-6 border border-gray-100">
          <div className="flex items-center gap-3 mb-4">
            <Filter className="w-5 h-5 text-gray-500" />
            <h3 className="text-lg font-semibold text-gray-900">Filters</h3>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Type</label>
              <select
                value={filters.notification_type}
                onChange={(e) => setFilters({ ...filters, notification_type: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="">All Types</option>
                <option value="booking_confirmation">Booking Confirmation</option>
                <option value="payment_receipt">Payment Receipt</option>
                <option value="pre_arrival_reminder">Pre-Arrival Reminder</option>
                <option value="check_in_reminder">Check-In Reminder</option>
                <option value="check_out_reminder">Check-Out Reminder</option>
                <option value="marketing_campaign">Marketing Campaign</option>
                <option value="loyalty_update">Loyalty Update</option>
                <option value="system_alert">System Alert</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Channel</label>
              <select
                value={filters.channel}
                onChange={(e) => setFilters({ ...filters, channel: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="">All Channels</option>
                <option value="email">Email</option>
                <option value="sms">SMS</option>
                <option value="push">Push</option>
                <option value="whatsapp">WhatsApp</option>
                <option value="in_app">In-App</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Status</label>
              <select
                value={filters.status}
                onChange={(e) => setFilters({ ...filters, status: e.target.value })}
                className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="">All Statuses</option>
                <option value="pending">Pending</option>
                <option value="sent">Sent</option>
                <option value="delivered">Delivered</option>
                <option value="read">Read</option>
                <option value="failed">Failed</option>
              </select>
            </div>
          </div>
        </div>

        {/* Notifications List */}
        {loading ? (
          <Loading fullScreen text="Loading notifications..." />
        ) : !notifications || !Array.isArray(notifications) || notifications.length === 0 ? (
          <div className="bg-white rounded-xl shadow-lg p-8 border border-gray-100">
            <EmptyState
              title="No notifications found"
              description="Send your first notification or adjust your filters"
              action={{
                label: 'Send Notification',
                onClick: () => setShowSendModal(true),
              }}
            />
          </div>
        ) : (
          <div className="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gradient-to-r from-gray-50 to-gray-100">
                  <tr>
                    <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Notification</th>
                    <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Channel</th>
                    <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Type</th>
                    <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Status</th>
                    <th className="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Sent At</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {notifications.map((notification) => (
                    <tr key={notification.id} className="hover:bg-gray-50 transition-colors">
                      <td className="px-6 py-4">
                        <div>
                          <p className="text-sm font-semibold text-gray-900">
                            {notification.subject || notification.notification_type.replace('_', ' ')}
                          </p>
                          <p className="text-xs text-gray-500 line-clamp-1 mt-1">{notification.content}</p>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          {getChannelIcon(notification.channel)}
                          <span className="text-sm text-gray-700 capitalize">{notification.channel}</span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        <span className="text-sm text-gray-700 capitalize">
                          {notification.notification_type.replace('_', ' ')}
                        </span>
                      </td>
                      <td className="px-6 py-4">
                        <div className="flex items-center gap-2">
                          {getStatusIcon(notification.status)}
                          <span className={getStatusBadge(notification.status)}>
                            {notification.status}
                          </span>
                        </div>
                      </td>
                      <td className="px-6 py-4">
                        {notification.sent_at ? (
                          <span className="text-sm text-gray-700">
                            {formatDate(new Date(notification.sent_at), 'short')}
                          </span>
                        ) : (
                          <span className="text-sm text-gray-400">Not sent</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </div>

      {/* Send Notification Modal */}
      {showSendModal && (
        <SendNotificationModal
          onClose={() => setShowSendModal(false)}
          onSuccess={() => {
            setShowSendModal(false);
            fetchNotifications();
          }}
        />
      )}

      {/* Templates Modal */}
      {showTemplatesModal && (
        <NotificationTemplatesModal
          onClose={() => setShowTemplatesModal(false)}
        />
      )}
    </div>
  );
};

export default NotificationManagementPage;

