import React, { useEffect, useState } from 'react';
import { Plus, Trash2, Activity, Edit } from 'lucide-react';
import webhookService, { Webhook, CreateWebhookData, UpdateWebhookData } from '../../features/integrations/services/webhookService';
import { toast } from 'react-toastify';
import Loading from '../../shared/components/Loading';
import { formatDate } from '../../shared/utils/format';

const WebhookManagementPage: React.FC = () => {
  const [webhooks, setWebhooks] = useState<Webhook[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [editingWebhook, setEditingWebhook] = useState<Webhook | null>(null);
  const [_selectedWebhook, _setSelectedWebhook] = useState<Webhook | null>(null);
  const [formData, setFormData] = useState<CreateWebhookData>({
    name: '',
    url: '',
    events: [],
    description: '',
    retry_count: 3,
    timeout_seconds: 30,
  });

  const availableEvents = [
    'booking.created',
    'booking.updated',
    'booking.cancelled',
    'payment.completed',
    'payment.failed',
    'invoice.created',
    'invoice.paid',
    'user.created',
    'user.updated',
  ];

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

  const fetchWebhooks = async () => {
    try {
      setLoading(true);
      const response = await webhookService.getWebhooks();
      setWebhooks(response.data.webhooks || []);
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to load webhooks');
    } finally {
      setLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      if (editingWebhook) {
        await webhookService.updateWebhook(editingWebhook.id, formData as UpdateWebhookData);
        toast.success('Webhook updated successfully');
      } else {
        const response = await webhookService.createWebhook(formData);
        toast.success('Webhook created successfully');
        // Show secret to user (only shown once)
        if (response.data.webhook.secret) {
          alert(`Webhook secret (save this - it won't be shown again): ${response.data.webhook.secret}`);
        }
      }
      setShowModal(false);
      setEditingWebhook(null);
      resetForm();
      fetchWebhooks();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || `Unable to ${editingWebhook ? 'update' : 'create'} webhook`);
    }
  };

  const handleEdit = (webhook: Webhook) => {
    setEditingWebhook(webhook);
    setFormData({
      name: webhook.name,
      url: webhook.url,
      events: webhook.events,
      description: webhook.description || '',
      retry_count: webhook.retry_count,
      timeout_seconds: webhook.timeout_seconds,
    });
    setShowModal(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Are you sure you want to delete this webhook?')) return;

    try {
      await webhookService.deleteWebhook(id);
      toast.success('Webhook deleted successfully');
      fetchWebhooks();
    } catch (error: unknown) {
      toast.error(getUserFriendlyError(error) || 'Unable to delete webhook');
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      url: '',
      events: [],
      description: '',
      retry_count: 3,
      timeout_seconds: 30,
    });
    setEditingWebhook(null);
  };

  const toggleEvent = (event: string) => {
    setFormData({
      ...formData,
      events: formData.events.includes(event)
        ? formData.events.filter(e => e !== event)
        : [...formData.events, event],
    });
  };

  if (loading && webhooks.length === 0) {
    return <Loading fullScreen text="Loading webhooks..." />;
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-50 px-3 sm:px-4 md:px-6 lg:px-8 py-6 sm:py-8 md:py-10">
      <div className="flex flex-col lg:flex-row justify-between items-start lg:items-center gap-4 sm:gap-6 mb-6 sm:mb-8 md:mb-10 animate-fade-in">
        <div className="w-full lg:w-auto">
          <div className="flex items-center gap-2 sm:gap-3 mb-2 sm:mb-3">
            <div className="h-1 w-12 sm:w-16 md:w-20 bg-gradient-to-r from-purple-400 via-indigo-500 to-blue-600 rounded-full"></div>
            <h1 className="text-2xl sm:text-3xl md:text-4xl font-bold bg-gradient-to-r from-slate-900 via-slate-800 to-slate-900 bg-clip-text text-transparent tracking-tight">
              Webhook Management
            </h1>
          </div>
          <p className="text-slate-600 mt-2 sm:mt-3 text-sm sm:text-base md:text-lg font-light">Manage webhooks for external integrations</p>
        </div>
        <button
          onClick={() => setShowModal(true)}
          className="w-full sm:w-auto px-4 sm:px-6 py-2 sm:py-2.5 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl transition-all duration-200 flex items-center justify-center gap-2 text-xs sm:text-sm"
        >
          <Plus className="w-4 h-4 sm:w-5 sm:h-5" />
          Create Webhook
        </button>
      </div>

      <div className="bg-white/90 backdrop-blur-md rounded-xl sm:rounded-2xl shadow-xl border border-slate-200/60 p-4 sm:p-5 md:p-6 animate-fade-in hover:shadow-2xl transition-all duration-300">
        {webhooks.length === 0 ? (
          <div className="text-center py-8 sm:py-12">
            <p className="text-slate-500 text-sm sm:text-base">No webhooks configured</p>
          </div>
        ) : (
          <div className="space-y-3 sm:space-y-4">
            {webhooks.map((webhook) => (
              <div
                key={webhook.id}
                className="bg-gradient-to-r from-slate-50 to-white border border-slate-200 rounded-lg sm:rounded-xl p-3 sm:p-4 hover:from-purple-50 hover:to-indigo-50 hover:border-purple-300 hover:shadow-lg transition-all duration-200"
              >
                <div className="flex items-start justify-between gap-3 sm:gap-4">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-wrap items-center gap-2 sm:gap-3 mb-2">
                      <Activity className="w-5 h-5 text-blue-500 flex-shrink-0" />
                      <h3 className="font-semibold text-sm sm:text-base md:text-lg truncate">{webhook.name}</h3>
                      <span className={`px-2 sm:px-3 py-1 rounded-full text-xs font-semibold border shadow-sm ${
                        webhook.status === 'active' ? 'bg-gradient-to-r from-emerald-50 to-green-50 text-emerald-800 border-emerald-200' :
                        'bg-gradient-to-r from-slate-50 to-gray-50 text-slate-700 border-slate-200'
                      }`}>
                        {webhook.status}
                      </span>
                    </div>
                    <p className="text-slate-600 text-xs sm:text-sm mb-1 sm:mb-2 truncate">{webhook.url}</p>
                    <p className="text-slate-500 text-xs line-clamp-1">
                      Events: {webhook.events.join(', ')}
                    </p>
                    <p className="text-slate-500 text-xs">
                      Created: {formatDate(webhook.created_at)}
                    </p>
                  </div>
                  <div className="flex gap-2 w-full sm:w-auto">
                    <button
                      onClick={() => handleEdit(webhook)}
                      className="p-2 sm:p-2.5 text-blue-600 hover:bg-blue-50 rounded-lg sm:rounded-xl transition-colors flex-shrink-0"
                      title="Edit webhook"
                    >
                      <Edit className="w-4 h-4 sm:w-5 sm:h-5" />
                    </button>
                    <button
                      onClick={() => handleDelete(webhook.id)}
                      className="p-2 sm:p-2.5 text-red-600 hover:bg-red-50 rounded-lg sm:rounded-xl transition-colors flex-shrink-0"
                      title="Delete webhook"
                    >
                      <Trash2 className="w-4 h-4 sm:w-5 sm:h-5" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {showModal && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-3 sm:p-4">
          <div className="bg-white/95 backdrop-blur-md rounded-xl sm:rounded-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto p-4 sm:p-5 md:p-6 shadow-2xl border border-slate-200/60">
            <h2 className="text-xl sm:text-2xl font-bold mb-4 sm:mb-5 md:mb-6 text-slate-900">
              {editingWebhook ? 'Edit Webhook' : 'Create Webhook'}
            </h2>
            <form onSubmit={handleSubmit} className="space-y-3 sm:space-y-4">
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Name</label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 sm:px-4 py-2 bg-white border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">URL</label>
                <input
                  type="url"
                  value={formData.url}
                  onChange={(e) => setFormData({ ...formData, url: e.target.value })}
                  className="w-full px-3 sm:px-4 py-2 bg-white border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Events</label>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3">
                  {availableEvents.map((event) => (
                    <label key={event} className="flex items-center gap-2 p-2 hover:bg-slate-50 rounded-lg cursor-pointer">
                      <input
                        type="checkbox"
                        checked={formData.events.includes(event)}
                        onChange={() => toggleEvent(event)}
                        className="w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500"
                      />
                      <span className="text-xs sm:text-sm text-slate-700">{event}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium mb-1 sm:mb-2 text-slate-700">Description</label>
                <textarea
                  value={formData.description}
                  onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                  className="w-full px-3 sm:px-4 py-2 bg-white border-2 border-slate-200 rounded-xl focus:border-blue-400 focus:ring-4 focus:ring-blue-100 transition-all duration-200 text-slate-700 font-medium shadow-sm hover:shadow-md text-sm sm:text-base"
                  rows={3}
                />
              </div>
              <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 sm:gap-4 pt-2">
                <button
                  type="button"
                  onClick={() => {
                    setShowModal(false);
                    resetForm();
                  }}
                  className="flex-1 sm:flex-none px-4 py-2 border-2 border-slate-300 rounded-xl hover:bg-slate-50 transition-all duration-200 text-slate-700 font-medium text-sm sm:text-base"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 sm:flex-none px-4 sm:px-6 py-2 bg-gradient-to-r from-blue-600 to-blue-700 text-white rounded-xl font-semibold hover:from-blue-700 hover:to-blue-800 shadow-lg hover:shadow-xl transition-all duration-200 text-sm sm:text-base"
                >
                  {editingWebhook ? 'Update' : 'Create'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

export default WebhookManagementPage;

