import React, { useState, useEffect } from 'react';
import { X } from 'lucide-react';
import { toast } from 'react-toastify';
import notificationService from '../../services/api/notificationService';

interface SendNotificationModalProps {
  onClose: () => void;
  onSuccess: () => void;
  initialData?: {
    user_id?: number;
    booking_id?: number;
    payment_id?: number;
  };
}

const SendNotificationModal: React.FC<SendNotificationModalProps> = ({ onClose, onSuccess, initialData }) => {
  const [formData, setFormData] = useState({
    user_id: initialData?.user_id?.toString() || '',
    notification_type: 'custom',
    channel: 'email',
    subject: '',
    content: '',
    priority: 'normal',
    scheduled_at: '',
    booking_id: initialData?.booking_id?.toString() || '',
    payment_id: initialData?.payment_id?.toString() || '',
  });
  const [loading, setLoading] = useState(false);
  const [templates, setTemplates] = useState<any[]>([]);
  const [selectedTemplate, setSelectedTemplate] = useState<string>('');

  useEffect(() => {
    loadTemplates();
  }, [formData.notification_type, formData.channel]);

  const loadTemplates = async () => {
    try {
      const response = await notificationService.getTemplates({
        notification_type: formData.notification_type,
        channel: formData.channel,
      });
      setTemplates(response.data.data || []);
    } catch (error) {
      // Ignore errors
    }
  };

  const handleTemplateSelect = (templateId: string) => {
    const template = templates.find(t => t.id.toString() === templateId);
    if (template) {
      setFormData({
        ...formData,
        subject: template.subject || '',
        content: template.content || '',
      });
      setSelectedTemplate(templateId);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!formData.content.trim()) {
      toast.error('Content is required');
      return;
    }

    try {
      setLoading(true);
      await notificationService.sendNotification({
        user_id: formData.user_id ? parseInt(formData.user_id) : undefined,
        notification_type: formData.notification_type,
        channel: formData.channel,
        content: formData.content,
        subject: formData.subject || undefined,
        priority: formData.priority,
        scheduled_at: formData.scheduled_at || undefined,
        booking_id: formData.booking_id ? parseInt(formData.booking_id) : undefined,
        payment_id: formData.payment_id ? parseInt(formData.payment_id) : undefined,
      });
      toast.success('Notification sent successfully');
      onSuccess();
    } catch (error: any) {
      toast.error(error.message || 'Failed to send notification');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="sticky top-0 bg-white border-b border-gray-200 p-6 flex items-center justify-between">
          <h2 className="text-2xl font-bold text-gray-900">Send Notification</h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Type</label>
              <select
                value={formData.notification_type}
                onChange={(e) => setFormData({ ...formData, notification_type: e.target.value, selectedTemplate: '' })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <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>
                <option value="custom">Custom</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Channel</label>
              <select
                value={formData.channel}
                onChange={(e) => setFormData({ ...formData, channel: e.target.value, selectedTemplate: '' })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <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>

          {templates.length > 0 && (
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Use Template</label>
              <select
                value={selectedTemplate}
                onChange={(e) => handleTemplateSelect(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="">Select a template...</option>
                {templates.map((template) => (
                  <option key={template.id} value={template.id.toString()}>
                    {template.name}
                  </option>
                ))}
              </select>
            </div>
          )}

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">User ID</label>
            <input
              type="number"
              value={formData.user_id}
              onChange={(e) => setFormData({ ...formData, user_id: e.target.value })}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              placeholder="Leave empty for system-wide"
            />
          </div>

          {(formData.channel === 'email' || formData.channel === 'push') && (
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Subject</label>
              <input
                type="text"
                value={formData.subject}
                onChange={(e) => setFormData({ ...formData, subject: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
            </div>
          )}

          <div>
            <label className="block text-sm font-semibold text-gray-700 mb-2">
              Content <span className="text-red-500">*</span>
            </label>
            <textarea
              value={formData.content}
              onChange={(e) => setFormData({ ...formData, content: e.target.value })}
              rows={6}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              required
            />
          </div>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Priority</label>
              <select
                value={formData.priority}
                onChange={(e) => setFormData({ ...formData, priority: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              >
                <option value="low">Low</option>
                <option value="normal">Normal</option>
                <option value="high">High</option>
                <option value="urgent">Urgent</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-semibold text-gray-700 mb-2">Schedule (optional)</label>
              <input
                type="datetime-local"
                value={formData.scheduled_at}
                onChange={(e) => setFormData({ ...formData, scheduled_at: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500"
              />
            </div>
          </div>

          <div className="flex items-center justify-end gap-3 pt-4 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={loading}
              className="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 disabled:opacity-50"
            >
              {loading ? 'Sending...' : 'Send Notification'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default SendNotificationModal;

