'use client';

import { useState, useEffect } from 'react';
import { Webhook, Plus, Trash2, CheckCircle, XCircle, Clock, ChevronDown, ChevronUp, Copy, Eye, EyeOff, X, Save, AlertCircle, Loader2 } from 'lucide-react';
import { listWebhooks, createWebhook, deleteWebhook, updateWebhook, listDeliveryLogs, Webhook as WebhookType, DeliveryLog } from '@client/api/webhooks';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

const allEvents = [
  'order.created', 'order.updated', 'order.cancelled', 'order.completed',
  'booking.created', 'booking.updated', 'booking.cancelled',
  'ai.escalation', 'ai.conversation.ended',
  'customer.created', 'customer.updated',
  'staff.login', 'staff.created',
];

const deliveryStatusConfig: Record<string, { color: string; bg: string; icon: React.ReactNode }> = {
  success: { color: 'hsl(142, 72%, 29%)', bg: 'hsl(142, 72%, 96%)', icon: <CheckCircle size={12} /> },
  failed: { color: 'hsl(0, 84%, 44%)', bg: 'hsl(0, 84%, 97%)', icon: <XCircle size={12} /> },
  pending: { color: 'hsl(38, 92%, 40%)', bg: 'hsl(38, 100%, 96%)', icon: <Clock size={12} /> },
};

export default function WebhooksPage() {
  const { t } = useLanguage();
  usePageHeader(t('webhooks.title', "Webhooks"), t('webhooks.subtitle', "Configure webhook endpoints to push events to third-party systems"));
  const [webhooks, setWebhooks] = useState<WebhookType[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [showAddForm, setShowAddForm] = useState(false);
  const [revealedKeys, setRevealedKeys] = useState<Set<string>>(new Set());
  const [expandedLogs, setExpandedLogs] = useState(false);
  const [deliveryLogs, setDeliveryLogs] = useState<DeliveryLog[]>([]);
  const [logsLoading, setLogsLoading] = useState(false);
  const [newWebhook, setNewWebhook] = useState({ url: '', events: [] as string[] });
  const [webhookErrors, setWebhookErrors] = useState<{ url?: string; events?: string }>({});
  const [webhookTouched, setWebhookTouched] = useState<Record<string, boolean>>({});
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [copiedSecret, setCopiedSecret] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    listWebhooks()
      .then(res => { setWebhooks(res.webhooks); setError(null); })
      .catch(e => setError(e.message))
      .finally(() => setLoading(false));
  }, []);

  const validateUrl = (url: string) => {
    if (!url.trim()) return t('webhooks.validation.urlRequired', 'Endpoint URL is required');
    try {
      const u = new URL(url);
      if (!['http:', 'https:'].includes(u.protocol)) return t('webhooks.validation.urlProtocol', 'URL must use HTTP or HTTPS protocol');
    } catch {
      return t('webhooks.validation.urlInvalid', 'Please enter a valid URL (e.g. https://your-app.com/webhooks)');
    }
  };

  const validateEvents = (events: string[]) => {
    if (events.length === 0) return t('webhooks.validation.eventsRequired', 'Please select at least one event');
  };

  const handleUrlBlur = () => {
    setWebhookTouched(prev => ({ ...prev, url: true }));
    setWebhookErrors(prev => ({ ...prev, url: validateUrl(newWebhook.url) }));
  };

  const handleUrlChange = (url: string) => {
    setNewWebhook(prev => ({ ...prev, url }));
    if (webhookTouched.url) setWebhookErrors(prev => ({ ...prev, url: validateUrl(url) }));
  };

  const toggleEvent = (event: string) => {
    const next = newWebhook.events.includes(event)
      ? newWebhook.events.filter(e => e !== event)
      : [...newWebhook.events, event];
    setNewWebhook(prev => ({ ...prev, events: next }));
    if (webhookTouched.events) setWebhookErrors(prev => ({ ...prev, events: validateEvents(next) }));
  };

  const handleSave = async () => {
    const urlErr = validateUrl(newWebhook.url);
    const eventsErr = validateEvents(newWebhook.events);
    setWebhookErrors({ url: urlErr, events: eventsErr });
    setWebhookTouched({ url: true, events: true });
    if (urlErr || eventsErr) return;
    setSaving(true);
    try {
      const res = await createWebhook({ endpoint_url: newWebhook.url, events: newWebhook.events });
      setWebhooks(prev => [res.webhook, ...prev]);
      setShowAddForm(false);
      setNewWebhook({ url: '', events: [] });
      setWebhookErrors({});
      setWebhookTouched({});
    } catch (e) {
      setError(e instanceof Error ? e.message : t('webhooks.error.saveFailed', 'Failed to save webhook'));
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async (id: string) => {
    setDeletingId(id);
    try {
      await deleteWebhook(id);
      setWebhooks(prev => prev.filter(w => w.id !== id));
    } catch (e) {
      setError(e instanceof Error ? e.message : t('webhooks.error.deleteFailed', 'Failed to delete webhook'));
    } finally {
      setDeletingId(null);
    }
  };

  const handleToggleStatus = async (id: string, currentStatus: string) => {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    try {
      const res = await updateWebhook(id, { status: newStatus });
      setWebhooks(prev => prev.map(w => w.id === id ? res.webhook : w));
    } catch (e) {
      setError(e instanceof Error ? e.message : t('webhooks.error.updateFailed', 'Failed to update webhook'));
    }
  };

  const handleToggleLogs = async () => {
    const next = !expandedLogs;
    setExpandedLogs(next);
    if (next && deliveryLogs.length === 0) {
      setLogsLoading(true);
      try {
        const res = await listDeliveryLogs();
        setDeliveryLogs(res.logs);
      } catch {
        // silently ignore
      } finally {
        setLogsLoading(false);
      }
    }
  };

  const copySecret = (id: string, secret: string) => {
    navigator.clipboard.writeText(secret).catch(() => {});
    setCopiedSecret(id);
    setTimeout(() => setCopiedSecret(null), 2000);
  };

  const toggleKey = (id: string) => {
    setRevealedKeys(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
  };

  const activeCount = webhooks.filter(w => w.status === 'active').length;
  const totalDeliveries = webhooks.reduce((s, w) => s + (w.totalDeliveries ?? 0), 0);
  const avgSuccess = webhooks.length > 0
    ? (webhooks.reduce((s, w) => s + (w.successRate ?? 100), 0) / webhooks.length).toFixed(1)
    : '—';

  return (
    <>
      {/* Stats */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-6">
        {[
          { label: t('webhooks.stats.activeEndpoints', 'Active Endpoints'), value: activeCount, color: 'hsl(142, 72%, 29%)' },
          { label: t('webhooks.stats.totalEndpoints', 'Total Endpoints'), value: webhooks.length, color: 'hsl(210, 100%, 40%)' },
          { label: t('webhooks.stats.totalDeliveries', 'Total Deliveries'), value: totalDeliveries.toLocaleString(), color: 'hsl(var(--primary))' },
          { label: t('webhooks.stats.avgSuccessRate', 'Avg Success Rate'), value: `${avgSuccess}%`, color: 'hsl(var(--primary))' },
        ].map(stat => (
          <div key={stat.label} className="rounded-xl p-4" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
            <p className="text-xl font-bold" style={{ color: stat.color }}>{stat.value}</p>
            <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>{stat.label}</p>
          </div>
        ))}
      </div>

      {error && (
        <div className="mb-4 px-4 py-3 rounded-xl text-sm flex items-center gap-2" style={{ backgroundColor: 'hsl(var(--danger-bg))', color: 'hsl(var(--danger))', border: '1px solid hsl(var(--danger-border))' }}>
          <AlertCircle size={14} /> {error}
          <button className="ml-auto" onClick={() => setError(null)}><X size={14} /></button>
        </div>
      )}

      {/* Header actions */}
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.endpoints.title', 'Webhook Endpoints')}</h3>
        <button className="btn-primary text-sm" onClick={() => setShowAddForm(!showAddForm)}>
          <Plus size={15} /> {t('webhooks.endpoints.add', 'Add Endpoint')}
        </button>
      </div>

      {/* Add form */}
      {showAddForm && (
        <div className="rounded-2xl p-5 mb-5" style={{ backgroundColor: 'hsl(var(--surface))', border: '2px solid hsl(var(--primary))' }}>
          <div className="flex items-center justify-between mb-4">
            <h4 className="font-semibold text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.addForm.title', 'New Webhook Endpoint')}</h4>
            <button onClick={() => { setShowAddForm(false); setWebhookErrors({}); setWebhookTouched({}); }}>
              <X size={16} style={{ color: 'hsl(var(--muted-foreground))' }} />
            </button>
          </div>
          <div className="space-y-4">
            <div>
              <label className="block text-xs font-semibold mb-1.5" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('webhooks.addForm.urlLabel', 'Endpoint URL *')}</label>
              <input
                type="url"
                placeholder={t('webhooks.urlPlaceholder', 'https://your-app.com/webhooks')}
                value={newWebhook.url}
                onChange={e => handleUrlChange(e.target.value)}
                onBlur={handleUrlBlur}
                className="input-field w-full font-mono"
                style={{
                  borderColor: webhookTouched.url && webhookErrors.url ? 'hsl(0, 84%, 44%)' : undefined,
                }}
              />
              {webhookTouched.url && webhookErrors.url && (
                <p className="flex items-center gap-1 text-xs mt-1.5 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
                  <AlertCircle size={12} />{webhookErrors.url}
                </p>
              )}
            </div>
            <div>
              <label className="block text-xs font-semibold mb-2" style={{ color: 'hsl(var(--foreground-secondary))' }}>{t('webhooks.addForm.eventsLabel', 'Subscribe to Events *')}</label>
              <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                {allEvents.map(event => (
                  <label key={event} className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={newWebhook.events.includes(event)} onChange={() => toggleEvent(event)} className="rounded" />
                    <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>{event}</span>
                  </label>
                ))}
              </div>
              {webhookTouched.events && webhookErrors.events && (
                <p className="flex items-center gap-1 text-xs mt-2 font-medium" style={{ color: 'hsl(0, 84%, 44%)' }}>
                  <AlertCircle size={12} />{webhookErrors.events}
                </p>
              )}
            </div>
            <div className="flex gap-3">
              <button className="btn-primary" onClick={handleSave} disabled={saving}>
                {saving ? <Loader2 size={15} className="animate-spin" /> : <Save size={15} />}
                {t('webhooks.addForm.submit', 'Save Endpoint')}
              </button>
              <button className="btn-secondary" onClick={() => { setShowAddForm(false); setWebhookErrors({}); setWebhookTouched({}); }}>{t('common.cancel', 'Cancel')}</button>
            </div>
          </div>
        </div>
      )}

      {/* Webhooks list */}
      {loading ? (
        <div className="flex items-center justify-center py-16 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Loader2 size={20} className="animate-spin" /> {t('webhooks.loading', 'Loading webhooks…')}
        </div>
      ) : (
        <div className="space-y-3 mb-8">
          {webhooks.length === 0 ? (
            <div className="text-center py-16 rounded-2xl" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
              <Webhook size={32} className="mx-auto mb-3 opacity-30" style={{ color: 'hsl(var(--muted-foreground))' }} />
              <p className="font-medium text-sm" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.noEndpoints.title', 'No webhook endpoints configured')}</p>
              <p className="text-xs mt-1" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('webhooks.noEndpoints.subtitle', 'Add an endpoint to start receiving event notifications')}</p>
            </div>
          ) : webhooks.map(webhook => {
            const isRevealed = revealedKeys.has(webhook.id);
            const events = Array.isArray(webhook.events) ? webhook.events : [];
            return (
              <div key={webhook.id} className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="flex items-start gap-4 p-4">
                  <div
                    className="w-9 h-9 rounded-xl flex items-center justify-center shrink-0 mt-0.5 cursor-pointer"
                    title={t('webhooks.endpoints.toggleStatus', 'Click to toggle status')}
                    style={{
                      backgroundColor: webhook.status === 'active' ? 'hsl(142, 72%, 96%)' : 'hsl(220, 9%, 96%)',
                      color: webhook.status === 'active' ? 'hsl(142, 72%, 29%)' : 'hsl(220, 9%, 46%)',
                    }}
                    onClick={() => handleToggleStatus(webhook.id, webhook.status)}
                  >
                    <Webhook size={16} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <p className="text-sm font-mono font-semibold truncate" style={{ color: 'hsl(var(--foreground))' }}>{webhook.endpointUrl}</p>
                      <span
                        className="text-xs font-semibold px-2 py-0.5 rounded-full shrink-0 cursor-pointer"
                        style={{
                          backgroundColor: webhook.status === 'active' ? 'hsl(142, 72%, 96%)' : 'hsl(220, 9%, 96%)',
                          color: webhook.status === 'active' ? 'hsl(142, 72%, 29%)' : 'hsl(220, 9%, 46%)',
                        }}
                        onClick={() => handleToggleStatus(webhook.id, webhook.status)}
                      >
                        {webhook.status === 'active' ? t('common.active', 'active') : t('common.inactive', 'inactive')}
                      </span>
                    </div>
                    <div className="flex flex-wrap gap-1 mb-2">
                      {events.map(e => (
                        <span key={e} className="text-xs font-mono px-1.5 py-0.5 rounded" style={{ backgroundColor: 'hsl(var(--muted))', color: 'hsl(var(--foreground-secondary))' }}>{e}</span>
                      ))}
                    </div>
                    <div className="flex items-center gap-4">
                      <div className="flex items-center gap-1.5">
                        <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('webhooks.endpoints.secretLabel', 'Secret:')}</span>
                        <span className="text-xs font-mono" style={{ color: 'hsl(var(--foreground-secondary))' }}>
                          {isRevealed ? webhook.secret : '••••••••••••••••'}
                        </span>
                        <button onClick={() => toggleKey(webhook.id)} className="p-0.5">
                          {isRevealed ? <EyeOff size={12} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <Eye size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                        </button>
                        <button className="p-0.5" title={t('common.copySecret', 'Copy secret')} onClick={() => copySecret(webhook.id, webhook.secret)}>
                          {copiedSecret === webhook.id
                            ? <CheckCircle size={12} style={{ color: 'hsl(142, 72%, 29%)' }} />
                            : <Copy size={12} style={{ color: 'hsl(var(--muted-foreground))' }} />}
                        </button>
                      </div>
                      <span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>
                        {t('webhooks.endpoints.created', 'Created')} {new Date(webhook.createdAt).toLocaleDateString()}
                      </span>
                    </div>
                  </div>
                  <div className="flex items-center gap-1 shrink-0">
                    <button
                      className="p-1.5 rounded-lg hover:bg-red-50 transition-colors"
                      title={t('common.delete', 'Delete')}
                      onClick={() => handleDelete(webhook.id)}
                      disabled={deletingId === webhook.id}
                    >
                      {deletingId === webhook.id
                        ? <Loader2 size={14} className="animate-spin" style={{ color: 'hsl(var(--danger))' }} />
                        : <Trash2 size={14} style={{ color: 'hsl(var(--danger))' }} />}
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Delivery logs */}
      {!loading && webhooks.length > 0 && (
        <div>
          <button className="flex items-center gap-2 w-full text-left mb-3" onClick={handleToggleLogs}>
            <h3 className="text-sm font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{t('webhooks.logs.title', 'Delivery Logs')}</h3>
            {logsLoading && <Loader2 size={13} className="animate-spin ml-1" style={{ color: 'hsl(var(--muted-foreground))' }} />}
            <div className="ml-auto">
              {expandedLogs ? <ChevronUp size={15} style={{ color: 'hsl(var(--muted-foreground))' }} /> : <ChevronDown size={15} style={{ color: 'hsl(var(--muted-foreground))' }} />}
            </div>
          </button>
          {expandedLogs && (
            logsLoading ? (
              <div className="flex items-center justify-center py-8 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
                <Loader2 size={16} className="animate-spin" /> {t('webhooks.logs.loading', 'Loading logs…')}
              </div>
            ) : deliveryLogs.length === 0 ? (
              <div className="rounded-2xl p-6 text-center" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <p className="text-sm" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('webhooks.logs.empty', 'No delivery logs yet. Logs will appear here as events are triggered.')}</p>
              </div>
            ) : (
              <div className="rounded-2xl overflow-hidden" style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))' }}>
                <div className="overflow-x-auto">
                  <table className="w-full">
                    <thead>
                      <tr style={{ borderBottom: '1px solid hsl(var(--border))', backgroundColor: 'hsl(var(--muted))' }}>
                        {[
                          t('webhooks.logs.table.event', 'Event'),
                          t('webhooks.logs.table.endpoint', 'Endpoint'),
                          t('webhooks.logs.table.status', 'Status'),
                          t('webhooks.logs.table.response', 'Response'),
                          t('webhooks.logs.table.duration', 'Duration'),
                          t('webhooks.logs.table.timestamp', 'Timestamp')
                        ].map(h => (
                          <th key={h} className="text-left px-4 py-2.5 text-xs font-semibold uppercase tracking-wide" style={{ color: 'hsl(var(--muted-foreground))' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {deliveryLogs.map((log, idx) => {
                        const sc = deliveryStatusConfig[log.status] ?? deliveryStatusConfig.failed;
                        return (
                          <tr key={log.id} style={{ borderBottom: idx < deliveryLogs.length - 1 ? '1px solid hsl(var(--border))' : 'none' }}>
                            <td className="px-4 py-3"><span className="text-xs font-mono font-semibold" style={{ color: 'hsl(var(--foreground))' }}>{log.event}</span></td>
                            <td className="px-4 py-3"><span className="text-xs font-mono truncate max-w-32 block" style={{ color: 'hsl(var(--muted-foreground))' }}>{log.endpointUrl?.replace('https://', '').split('/')[0]}</span></td>
                            <td className="px-4 py-3">
                              <span className="flex items-center gap-1 text-xs font-semibold px-2 py-0.5 rounded-full w-fit" style={{ backgroundColor: sc.bg, color: sc.color }}>
                                {sc.icon} {log.status}
                              </span>
                            </td>
                            <td className="px-4 py-3"><span className="text-xs font-mono font-semibold" style={{ color: log.responseCode && log.responseCode < 300 ? 'hsl(142, 72%, 29%)' : 'hsl(0, 84%, 44%)' }}>{log.responseCode ?? '—'}</span></td>
                            <td className="px-4 py-3"><span className="text-xs font-mono" style={{ color: 'hsl(var(--muted-foreground))' }}>{log.durationMs != null ? `${log.durationMs}ms` : '—'}</span></td>
                            <td className="px-4 py-3"><span className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>{new Date(log.triggeredAt).toLocaleString()}</span></td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            )
          )}
        </div>
      )}
    </>
  );
}
