/* global React, Icon, Button, Chip */

const INTEGRATIONS = [
  {
    id: "whatsapp",
    name: "WhatsApp Business",
    category: "Messaging",
    icon: "message-circle",
    iconColor: "#25D366",
    description: "Receive inbound enquiries and send automated follow-ups via the official WhatsApp Business API.",
    status: "connected",
    connectedAs: "+971 4 000 1234  ·  Smash Companies House",
    lastSync: "2 min ago",
    features: ["Auto-route inbound messages to Leads inbox", "Send quotation & payment links", "Renewal reminder messages", "Two-way message log in engagement timeline"],
  },
  {
    id: "facebook",
    name: "Facebook Lead Ads",
    category: "Lead capture",
    icon: "megaphone",
    iconColor: "#1877F2",
    description: "Auto-import leads from Facebook Lead Ad campaigns directly into the CRM inbox.",
    status: "connected",
    connectedAs: "Smash Companies House · Page ID 1023884412",
    lastSync: "8 min ago",
    features: ["Instant lead import on form submission", "Campaign and ad-set attribution", "Lead deduplication", "Source tag on lead record"],
  },
  {
    id: "stripe",
    name: "Stripe",
    category: "Payments",
    icon: "credit-card",
    iconColor: "#635BFF",
    description: "Generate payment links, collect card payments, and sync transaction status to engagement records.",
    status: "connected",
    connectedAs: "smashcompanieshouse · Live mode",
    lastSync: "Live",
    features: ["One-click payment link from quotation", "Automatic paid/partial status update", "Webhook-driven payment confirmation", "Refund initiation from CRM"],
  },
  {
    id: "email",
    name: "Email (SMTP)",
    category: "Notifications",
    icon: "mail",
    iconColor: "#E84393",
    description: "Send renewal reminders, quotations, and status updates to customers via your branded email domain.",
    status: "connected",
    connectedAs: "noreply@smashcompanieshouse.ae  ·  SMTP verified",
    lastSync: "Live",
    features: ["Renewal reminder automation", "Quotation delivery with PDF attachment", "Status update notifications", "Customer portal invite emails"],
  },
  {
    id: "google_drive",
    name: "Google Drive",
    category: "Documents",
    icon: "hard-drive",
    iconColor: "#34A853",
    description: "Automatically back up uploaded documents to a shared Google Drive folder organised by customer.",
    status: "disconnected",
    connectedAs: null,
    lastSync: null,
    features: ["Auto-sync uploaded documents", "Folder structure per customer", "Shared access for PRO officers", "Version history"],
  },
  {
    id: "xero",
    name: "Xero",
    category: "Accounting",
    icon: "bar-chart-2",
    iconColor: "#13B5EA",
    description: "Push invoices and payment records to Xero for reconciliation and financial reporting.",
    status: "disconnected",
    connectedAs: null,
    lastSync: null,
    features: ["Auto-create invoice on quotation approval", "Payment sync on Stripe confirmation", "Customer contact sync", "Monthly revenue reports"],
  },
  {
    id: "zapier",
    name: "Zapier",
    category: "Automation",
    icon: "zap",
    iconColor: "#FF4A00",
    description: "Connect the CRM to 5,000+ apps via Zapier webhooks for custom automation workflows.",
    status: "disconnected",
    connectedAs: null,
    lastSync: null,
    features: ["Trigger zaps on lead creation", "Trigger zaps on stage change", "Push data to Google Sheets, Slack, and more", "Inbound webhooks for external triggers"],
  },
  {
    id: "twilio",
    name: "Twilio SMS",
    category: "Messaging",
    icon: "smartphone",
    iconColor: "#F22F46",
    description: "Send SMS notifications and OTPs for document verification and renewal alerts.",
    status: "disconnected",
    connectedAs: null,
    lastSync: null,
    features: ["Renewal SMS alerts", "Payment confirmation SMS", "OTP for portal login", "Bulk SMS campaigns"],
  },
];

const CATEGORY_ORDER = ["Messaging", "Lead capture", "Payments", "Notifications", "Documents", "Accounting", "Automation"];

function ConfigModal({ integration, onClose }) {
  const isConnected = integration.status === "connected";
  const [apiKey, setApiKey] = React.useState("");
  const [webhook, setWebhook] = React.useState("");

  return (
    <>
      <div className="scrim" onClick={onClose} />
      <div className="modal" role="dialog" aria-modal="true">
        <div className="modal-head">
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--ink-50)", border: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name={integration.icon} size={18} />
            </div>
            <div>
              <div className="eyebrow" style={{ marginBottom: 2 }}>{integration.category}</div>
              <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>{integration.name}</h2>
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        <div className="modal-body">
          {isConnected ? (
            <>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 14px", background: "var(--success-50)", border: "1px solid var(--success-500)", borderRadius: 8 }}>
                <Icon name="check-circle" size={16} />
                <div style={{ fontSize: 13, color: "var(--success-700)" }}>
                  Connected as <b>{integration.connectedAs}</b>
                  {integration.lastSync && <span style={{ marginLeft: 8, opacity: 0.7 }}>· Last sync {integration.lastSync}</span>}
                </div>
              </div>
              <div className="field">
                <label>Webhook URL</label>
                <input value="https://crm.smashcompanieshouse.ae/webhooks/inbound" readOnly style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-3)" }} />
              </div>
              <div className="field">
                <label>API key</label>
                <input value="sk_live_••••••••••••••••••••••••••••" readOnly style={{ fontFamily: "var(--font-mono)", fontSize: 12, color: "var(--fg-3)" }} />
              </div>
              <div className="modal-footer">
                <Button variant="secondary" type="button" onClick={onClose} icon="unlink">Disconnect</Button>
                <Button onClick={onClose}>Save changes</Button>
              </div>
            </>
          ) : (
            <>
              <p style={{ margin: 0, fontSize: 13.5, color: "var(--fg-2)", lineHeight: 1.6 }}>{integration.description}</p>
              <div className="field">
                <label>API key / Access token</label>
                <input placeholder="Paste your API key here…" value={apiKey} onChange={e => setApiKey(e.target.value)} autoFocus style={{ fontFamily: "var(--font-mono)", fontSize: 13 }} />
              </div>
              <div className="field">
                <label>Webhook URL <span style={{ color: "var(--fg-3)", fontWeight: 400 }}>(optional)</span></label>
                <input placeholder="https://…" value={webhook} onChange={e => setWebhook(e.target.value)} style={{ fontFamily: "var(--font-mono)", fontSize: 13 }} />
              </div>
              <div style={{ background: "var(--ink-50)", border: "1px solid var(--border-subtle)", borderRadius: 8, padding: "12px 14px" }}>
                <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.12em", color: "var(--fg-3)", fontWeight: 600, marginBottom: 8 }}>What you'll unlock</div>
                {integration.features.map(f => (
                  <div key={f} style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13, color: "var(--fg-2)", marginBottom: 5 }}>
                    <Icon name="check" size={13} /> {f}
                  </div>
                ))}
              </div>
              <div className="modal-footer">
                <Button variant="secondary" type="button" onClick={onClose}>Cancel</Button>
                <Button icon="plug" onClick={onClose}>Connect</Button>
              </div>
            </>
          )}
        </div>
      </div>
    </>
  );
}

function IntegrationCard({ integration, onConfigure }) {
  const connected = integration.status === "connected";
  return (
    <div className="card card-pad" style={{ display: "flex", gap: 16, alignItems: "flex-start" }}>
      <div style={{ width: 44, height: 44, borderRadius: 10, background: "var(--ink-50)", border: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, color: integration.iconColor }}>
        <Icon name={integration.icon} size={22} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 4 }}>
          <div style={{ fontWeight: 600, fontSize: 14.5 }}>{integration.name}</div>
          <Chip kind={connected ? "success" : "default"}>{connected ? "Connected" : "Not connected"}</Chip>
        </div>
        <div style={{ fontSize: 13, color: "var(--fg-3)", lineHeight: 1.5, marginBottom: connected ? 8 : 0 }}>
          {integration.description}
        </div>
        {connected && (
          <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 12, color: "var(--fg-3)", fontFamily: "var(--font-mono)" }}>
            <Icon name="check-circle" size={12} />
            {integration.connectedAs}
            {integration.lastSync && <span style={{ marginLeft: 6 }}>· Synced {integration.lastSync}</span>}
          </div>
        )}
      </div>
      <button
        className={connected ? "btn btn-secondary btn-sm" : "btn btn-primary btn-sm"}
        style={{ flexShrink: 0 }}
        onClick={() => onConfigure(integration)}
      >
        <Icon name={connected ? "settings" : "plug"} size={13} />
        {connected ? "Configure" : "Connect"}
      </button>
    </div>
  );
}

function IntegrationsPage() {
  const [activeConfig, setActiveConfig] = React.useState(null);

  const connected    = INTEGRATIONS.filter(i => i.status === "connected").length;
  const disconnected = INTEGRATIONS.filter(i => i.status === "disconnected").length;

  const byCategory = CATEGORY_ORDER.reduce((acc, cat) => {
    const items = INTEGRATIONS.filter(i => i.category === cat);
    if (items.length) acc[cat] = items;
    return acc;
  }, {});

  return (
    <>
    <div className="page">
      <div className="page-head">
        <div>
          <div className="eyebrow">Setup</div>
          <h1 className="page-title">Integrations</h1>
          <div className="page-sub">{connected} connected &nbsp;·&nbsp; {disconnected} available to connect</div>
        </div>
      </div>

      {/* Status strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14, marginBottom: 28 }}>
        {INTEGRATIONS.filter(i => i.status === "connected").map(i => (
          <div key={i.id} className="kpi" style={{ flexDirection: "row", alignItems: "center", gap: 12, padding: "14px 16px" }}>
            <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--ink-50)", border: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0, color: i.iconColor }}>
              <Icon name={i.icon} size={18} />
            </div>
            <div>
              <div style={{ fontSize: 12, fontWeight: 600 }}>{i.name}</div>
              <div style={{ fontSize: 11, color: "var(--success-700)", marginTop: 2, display: "flex", alignItems: "center", gap: 4 }}>
                <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--success-500)", display: "inline-block" }} />
                Synced {i.lastSync}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Cards by category */}
      {Object.entries(byCategory).map(([category, items]) => (
        <div key={category} style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: "0.14em", fontWeight: 600, color: "var(--fg-3)", marginBottom: 10 }}>
            {category}
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {items.map(i => (
              <IntegrationCard key={i.id} integration={i} onConfigure={setActiveConfig} />
            ))}
          </div>
        </div>
      ))}
    </div>

    {activeConfig && <ConfigModal integration={activeConfig} onClose={() => setActiveConfig(null)} />}
    </>
  );
}

Object.assign(window, { IntegrationsPage });
