import { createSignal, createMemo, For, Show, onMount } from "solid-js";
import { Bell, BellOff, Calendar, Link, Plus, Slack, Trash2, Webhook, ExternalLink } from "lucide-solid";

import Modal from "~/components/modal";
import { useApp } from "~/lib/app-context";
import {
  apiListIntegrations,
  apiCreateIntegration,
  apiDeleteIntegration,
  apiListWebhooks,
  apiCreateWebhook,
  apiDeleteWebhook,
  apiConnectGoogleCalendar,
  apiConnectSlack,
  apiDisconnectIntegration
} from "~/lib/api-integrations";
import type { Integration, Webhook } from "~/lib/types-integrations";

const integrationProviders = [
  { id: "google_calendar", name: "Google Calendar", icon: Calendar, description: "Sync events with Google Calendar", oauth: true },
  { id: "slack", name: "Slack", icon: Slack, description: "Send notifications to Slack channels", oauth: true },
  { id: "webhook", name: "Custom Webhook", icon: Webhook, description: "Send events to any HTTP endpoint", oauth: false }
];

const webhookEvents = [
  { id: "task.created", label: "Task Created" },
  { id: "task.completed", label: "Task Completed" },
  { id: "task.assigned", label: "Task Assigned" },
  { id: "event.created", label: "Event Created" },
  { id: "comment.created", label: "Comment Created" }
];

export default function IntegrationsRoute() {
  const app = useApp();
  const workspaceSlug = () => app.primaryWorkspace()?.slug ?? "personal";

  const [integrations, setIntegrations] = createSignal<Integration[]>([]);
  const [webhooks, setWebhooks] = createSignal<Webhook[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [showAddIntegration, setShowAddIntegration] = createSignal(false);
  const [showAddWebhook, setShowAddWebhook] = createSignal(false);

  // Integration form
  const [selectedProvider, setSelectedProvider] = createSignal("webhook");
  const [integrationName, setIntegrationName] = createSignal("");
  const [integrationConfig, setIntegrationConfig] = createSignal("");
  const [integrationCredentials, setIntegrationCredentials] = createSignal("");

  // Webhook form
  const [webhookName, setWebhookName] = createSignal("");
  const [webhookUrl, setWebhookUrl] = createSignal("");
  const [selectedEvents, setSelectedEvents] = createSignal<string[]>(["task.created", "task.completed"]);

  const loadData = async () => {
    setLoading(true);
    try {
      const [ints, hooks] = await Promise.all([
        apiListIntegrations(workspaceSlug()),
        apiListWebhooks(workspaceSlug())
      ]);
      setIntegrations(ints);
      setWebhooks(hooks);
    } catch (e) {
      console.error("Failed to load integrations", e);
    }
    setLoading(false);
  };

  onMount(loadData);

  const resetIntegrationForm = () => {
    setSelectedProvider("webhook");
    setIntegrationName("");
    setIntegrationConfig("");
    setIntegrationCredentials("");
  };

  const resetWebhookForm = () => {
    setWebhookName("");
    setWebhookUrl("");
    setSelectedEvents(["task.created", "task.completed"]);
  };

  const handleAddIntegration = async () => {
    if (!integrationName().trim() || !integrationCredentials().trim()) return;

    const integration = await apiCreateIntegration({
      workspaceSlug: workspaceSlug(),
      provider: selectedProvider(),
      name: integrationName(),
      config: integrationConfig(),
      credentials: integrationCredentials()
    });

    setIntegrations([...integrations(), integration]);
    setShowAddIntegration(false);
    resetIntegrationForm();
  };

  const handleDeleteIntegration = async (id: string) => {
    await apiDeleteIntegration(id);
    setIntegrations(integrations().filter(i => i.id !== id));
  };

  const handleConnectGoogleCalendar = async () => {
    try {
      const result = await apiConnectGoogleCalendar(workspaceSlug());
      window.location.href = result.authUrl;
    } catch (e) {
      console.error("Failed to connect Google Calendar", e);
    }
  };

  const handleConnectSlack = async () => {
    try {
      const result = await apiConnectSlack(workspaceSlug());
      window.location.href = result.authUrl;
    } catch (e) {
      console.error("Failed to connect Slack", e);
    }
  };

  const handleDisconnectIntegration = async (id: string) => {
    try {
      await apiDisconnectIntegration(id);
      setIntegrations(integrations().filter(i => i.id !== id));
    } catch (e) {
      console.error("Failed to disconnect integration", e);
    }
  };

  const handleAddWebhook = async () => {
    if (!webhookName().trim() || !webhookUrl().trim()) return;

    const webhook = await apiCreateWebhook({
      workspaceSlug: workspaceSlug(),
      name: webhookName(),
      url: webhookUrl(),
      events: selectedEvents()
    });

    setWebhooks([...webhooks(), webhook]);
    setShowAddWebhook(false);
    resetWebhookForm();
  };

  const handleDeleteWebhook = async (id: string) => {
    await apiDeleteWebhook(id);
    setWebhooks(webhooks().filter(w => w.id !== id));
  };

  const toggleEvent = (eventId: string) => {
    const events = selectedEvents();
    if (events.includes(eventId)) {
      setSelectedEvents(events.filter(e => e !== eventId));
    } else {
      setSelectedEvents([...events, eventId]);
    }
  };

  return (
    <div class="max-w-4xl mx-auto space-y-8">
      <div>
        <h1 class="text-2xl font-semibold">Integrations</h1>
        <p class="mt-1 text-sm text-[var(--text-muted)]">Connect external services and automate workflows</p>
      </div>

      {/* Quick Connect */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3">
          <h2 class="text-sm font-medium">Quick Connect</h2>
        </div>
        <div class="p-4 grid grid-cols-2 gap-3">
          <button
            onClick={handleConnectGoogleCalendar}
            class="flex items-center gap-3 p-4 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)] transition-colors"
          >
            <Calendar class="w-6 h-6 text-blue-500" />
            <div class="text-left">
              <p class="font-medium">Google Calendar</p>
              <p class="text-xs text-[var(--text-muted)]">Sync events bidirectionally</p>
            </div>
            <ExternalLink class="w-4 h-4 ml-auto text-[var(--text-muted)]" />
          </button>
          <button
            onClick={handleConnectSlack}
            class="flex items-center gap-3 p-4 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)] transition-colors"
          >
            <Slack class="w-6 h-6 text-purple-500" />
            <div class="text-left">
              <p class="font-medium">Slack</p>
              <p class="text-xs text-[var(--text-muted)]">Send notifications to channels</p>
            </div>
            <ExternalLink class="w-4 h-4 ml-auto text-[var(--text-muted)]" />
          </button>
        </div>
      </div>

      {/* Integrations */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3 flex items-center justify-between">
          <h2 class="text-sm font-medium">Connected Services</h2>
          <button
            onClick={() => { resetIntegrationForm(); setShowAddIntegration(true); }}
            class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--accent)] text-white text-sm hover:opacity-90"
          >
            <Plus class="w-4 h-4" />
            Add Integration
          </button>
        </div>
        <div class="divide-y divide-[var(--border)]">
          <Show when={!loading() && integrations().length === 0}>
            <div class="px-4 py-8 text-center text-sm text-[var(--text-muted)]">
              No integrations connected yet
            </div>
          </Show>
          <For each={integrations()}>
            {integration => {
              const provider = integrationProviders.find(p => p.id === integration.provider);
              const Icon = provider?.icon || Link;
              const isOAuth = provider?.oauth;
              return (
                <div class="flex items-center justify-between px-4 py-3">
                  <div class="flex items-center gap-3">
                    <div class="w-10 h-10 rounded-lg bg-[var(--bg-subtle)] flex items-center justify-center">
                      <Icon class="w-5 h-5 text-[var(--text-muted)]" />
                    </div>
                    <div>
                      <p class="font-medium">{integration.name}</p>
                      <p class="text-sm text-[var(--text-muted)]">{provider?.name || integration.provider}</p>
                    </div>
                  </div>
                  <div class="flex items-center gap-2">
                    <span class={`px-2 py-0.5 rounded text-xs ${
                      integration.status === "active" ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-700"
                    }`}>
                      {integration.status}
                    </span>
                    <button
                      onClick={() => isOAuth ? handleDisconnectIntegration(integration.id) : handleDeleteIntegration(integration.id)}
                      class="p-1.5 rounded text-[var(--text-muted)] hover:text-red-500 hover:bg-red-50"
                      title={isOAuth ? "Disconnect" : "Delete"}
                    >
                      <Trash2 class="w-4 h-4" />
                    </button>
                  </div>
                </div>
              );
            }}
          </For>
        </div>
      </div>

      {/* Webhooks */}
      <div class="rounded-lg border border-[var(--border)] bg-[var(--surface)]">
        <div class="border-b border-[var(--border)] px-4 py-3 flex items-center justify-between">
          <h2 class="text-sm font-medium">Webhooks</h2>
          <button
            onClick={() => { resetWebhookForm(); setShowAddWebhook(true); }}
            class="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-[var(--accent)] text-white text-sm hover:opacity-90"
          >
            <Plus class="w-4 h-4" />
            Add Webhook
          </button>
        </div>
        <div class="divide-y divide-[var(--border)]">
          <Show when={!loading() && webhooks().length === 0}>
            <div class="px-4 py-8 text-center text-sm text-[var(--text-muted)]">
              No webhooks configured yet
            </div>
          </Show>
          <For each={webhooks()}>
            {webhook => (
              <div class="flex items-center justify-between px-4 py-3">
                <div>
                  <p class="font-medium">{webhook.name}</p>
                  <p class="text-sm text-[var(--text-muted)] truncate max-w-md">{webhook.url}</p>
                  <div class="flex gap-1 mt-1">
                    <For each={webhook.events?.slice?.(0, 3) || []}>
                      {(event: string) => (
                        <span class="px-1.5 py-0.5 rounded bg-[var(--bg-subtle)] text-xs text-[var(--text-muted)]">
                          {event}
                        </span>
                      )}
                    </For>
                    <Show when={(webhook.events?.length || 0) > 3}>
                      <span class="text-xs text-[var(--text-muted)]">
                        +{(webhook.events?.length || 0) - 3} more
                      </span>
                    </Show>
                  </div>
                </div>
                <div class="flex items-center gap-2">
                  <span class={`px-2 py-0.5 rounded text-xs ${
                    webhook.active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-700"
                  }`}>
                    {webhook.active ? "Active" : "Inactive"}
                  </span>
                  <button
                    onClick={() => handleDeleteWebhook(webhook.id)}
                    class="p-1.5 rounded text-[var(--text-muted)] hover:text-red-500 hover:bg-red-50"
                  >
                    <Trash2 class="w-4 h-4" />
                  </button>
                </div>
              </div>
            )}
          </For>
        </div>
      </div>

      {/* Add Integration Modal */}
      <Modal open={showAddIntegration()} onClose={() => setShowAddIntegration(false)} title="Add Integration">
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Provider</label>
            <div class="grid grid-cols-3 gap-2">
              <For each={integrationProviders}>
                {provider => (
                  <button
                    onClick={() => setSelectedProvider(provider.id)}
                    class={`p-3 rounded-lg border text-center transition-colors ${
                      selectedProvider() === provider.id
                        ? "border-[var(--accent)] bg-[var(--accent-muted)]"
                        : "border-[var(--border)] hover:bg-[var(--surface-hover)]"
                    }`}
                  >
                    <provider.icon class="w-6 h-6 mx-auto mb-1" />
                    <span class="text-xs">{provider.name}</span>
                  </button>
                )}
              </For>
            </div>
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Name</label>
            <input
              type="text"
              value={integrationName()}
              onInput={e => setIntegrationName(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
              placeholder="My Integration"
            />
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Configuration (JSON)</label>
            <textarea
              value={integrationConfig()}
              onInput={e => setIntegrationConfig(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] min-h-[60px] font-mono text-sm"
              placeholder='{"calendar_id": "primary"}'
            />
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">Credentials</label>
            <textarea
              value={integrationCredentials()}
              onInput={e => setIntegrationCredentials(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)] min-h-[60px] font-mono text-sm"
              placeholder="API key or OAuth token"
            />
          </div>
          <div class="flex justify-end gap-2 pt-2">
            <button
              onClick={() => setShowAddIntegration(false)}
              class="px-4 py-2 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)]"
            >
              Cancel
            </button>
            <button
              onClick={handleAddIntegration}
              class="px-4 py-2 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
            >
              Add Integration
            </button>
          </div>
        </div>
      </Modal>

      {/* Add Webhook Modal */}
      <Modal open={showAddWebhook()} onClose={() => setShowAddWebhook(false)} title="Add Webhook">
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">Name</label>
            <input
              type="text"
              value={webhookName()}
              onInput={e => setWebhookName(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
              placeholder="Slack Notifications"
            />
          </div>
          <div>
            <label class="block text-sm font-medium mb-1">URL</label>
            <input
              type="url"
              value={webhookUrl()}
              onInput={e => setWebhookUrl(e.currentTarget.value)}
              class="w-full px-3 py-2 rounded-lg border border-[var(--border)] bg-[var(--surface)]"
              placeholder="https://hooks.slack.com/services/..."
            />
          </div>
          <div>
            <label class="block text-sm font-medium mb-2">Events</label>
            <div class="space-y-2">
              <For each={webhookEvents}>
                {event => (
                  <label class="flex items-center gap-2 cursor-pointer">
                    <input
                      type="checkbox"
                      checked={selectedEvents().includes(event.id)}
                      onChange={() => toggleEvent(event.id)}
                      class="rounded"
                    />
                    <span class="text-sm">{event.label}</span>
                  </label>
                )}
              </For>
            </div>
          </div>
          <div class="flex justify-end gap-2 pt-2">
            <button
              onClick={() => setShowAddWebhook(false)}
              class="px-4 py-2 rounded-lg border border-[var(--border)] hover:bg-[var(--surface-hover)]"
            >
              Cancel
            </button>
            <button
              onClick={handleAddWebhook}
              class="px-4 py-2 rounded-lg bg-[var(--accent)] text-white hover:opacity-90"
            >
              Add Webhook
            </button>
          </div>
        </div>
      </Modal>
    </div>
  );
}