"use client";

// ============================================================
// Org Settings → Integrations. Today: SMS (Twilio) — a tenant
// brings its OWN Twilio credentials, which be-crm seals in IIOS
// (per-scope) and resolves at send time. The auth token is
// write-only: sealed in IIOS, never read back, so status shows
// only masked hints (from-number + SID last-4). Email (SMTP) is
// the next provider on the same generic credential registry.
// ============================================================

import { useState } from "react";
import { Btn, Field, Icon, PageHead, Pill, useToast } from "./ui";
import { useSmsSettings } from "@/lib/sms-settings-api";
import { useSmtpSettings } from "@/lib/smtp-settings-api";

const SID_RE = /^AC[0-9a-fA-F]{32}$/;
const E164_RE = /^\+[1-9]\d{6,14}$/;
const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

export function Settings() {
  return (
    <div className="view">
      <PageHead
        eyebrow="Configuration"
        title="Org Settings"
        subtitle="Integrations and workspace configuration"
        icon="settings"
      />
      <section className="settings-section">
        <h3 className="settings-section-title">Integrations</h3>
        <div className="settings-grid">
          <TwilioCard />
          <SmtpCard />
        </div>
      </section>
    </div>
  );
}

function TwilioCard() {
  const toast = useToast();
  const { status, loading, live, configure } = useSmsSettings();
  const [editing, setEditing] = useState(false);
  const [accountSid, setAccountSid] = useState("");
  const [authToken, setAuthToken] = useState("");
  const [fromNumber, setFromNumber] = useState("");
  const [errors, setErrors] = useState<{ accountSid?: string; authToken?: string; fromNumber?: string }>({});
  const [saving, setSaving] = useState(false);

  const showForm = editing || (!loading && !status.configured);

  function validate(): boolean {
    const e: typeof errors = {};
    if (!SID_RE.test(accountSid.trim())) e.accountSid = "Must be a Twilio Account SID (AC + 32 hex chars).";
    if (!authToken.trim()) e.authToken = "Auth token is required.";
    if (!E164_RE.test(fromNumber.trim())) e.fromNumber = "Must be E.164, e.g. +15551234567.";
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function save() {
    if (!validate()) return;
    setSaving(true);
    try {
      await configure({ accountSid: accountSid.trim(), authToken: authToken.trim(), fromNumber: fromNumber.trim() });
      toast.push({ tone: "success", title: "Twilio connected", desc: "Your SMS credentials are saved and encrypted." });
      setAccountSid(""); setAuthToken(""); setFromNumber(""); setErrors({}); setEditing(false);
    } catch (err) {
      toast.push({ tone: "error", title: "Couldn't save credentials", desc: (err as Error).message });
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="settings-card">
      <div className="settings-card-head">
        <span className="settings-card-ic" aria-hidden="true"><Icon name="send" size={20} /></span>
        <div className="settings-card-titles">
          <div className="settings-card-name">
            SMS <span className="settings-card-sub">· Twilio</span>
          </div>
          <div className="settings-card-desc">Send texts from your own Twilio number.</div>
        </div>
        {status.configured
          ? <Pill tone="green">Connected</Pill>
          : <Pill tone="muted">Not connected</Pill>}
      </div>

      {status.configured && !editing ? (
        <div className="settings-card-body">
          <dl className="settings-kv">
            <div><dt>From number</dt><dd>{status.fromNumber ?? "—"}</dd></div>
            <div><dt>Account SID</dt><dd>{status.sidLast4 ? `AC ···· ${status.sidLast4}` : "—"}</dd></div>
            <div><dt>Status</dt><dd>{status.enabled ? "Active" : "Disabled"}</dd></div>
          </dl>
          <Btn variant="outline" icon="settings" onClick={() => setEditing(true)}>Update credentials</Btn>
        </div>
      ) : null}

      {showForm ? (
        <div className="settings-card-body">
          <Field label="Account SID" required error={errors.accountSid} hint="Twilio Console → Account Info.">
            <input className="ds-input" value={accountSid} onChange={(e) => setAccountSid(e.target.value)} placeholder="ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" autoComplete="off" />
          </Field>
          <Field label="Auth Token" required error={errors.authToken} hint="Encrypted on save and never shown again.">
            <input className="ds-input" type="password" value={authToken} onChange={(e) => setAuthToken(e.target.value)} placeholder="••••••••••••••••••••••••••••••••" autoComplete="off" />
          </Field>
          <Field label="From number" required error={errors.fromNumber} hint="A Twilio number in E.164 format.">
            <input className="ds-input" value={fromNumber} onChange={(e) => setFromNumber(e.target.value)} placeholder="+15551234567" autoComplete="off" />
          </Field>
          <div className="settings-card-actions">
            <Btn icon="check-circle" onClick={save} disabled={saving}>{saving ? "Saving…" : status.configured ? "Update" : "Connect Twilio"}</Btn>
            {status.configured ? <Btn variant="ghost" onClick={() => { setEditing(false); setErrors({}); }}>Cancel</Btn> : null}
          </div>
        </div>
      ) : null}

      {!live ? <div className="settings-card-note">Demo mode — credentials are stored locally and not sent to Twilio.</div> : null}
    </div>
  );
}

function SmtpCard() {
  const toast = useToast();
  const { status, loading, live, configure } = useSmtpSettings();
  const [editing, setEditing] = useState(false);
  const [host, setHost] = useState("");
  const [port, setPort] = useState("587");
  const [secure, setSecure] = useState(false);
  const [user, setUser] = useState("");
  const [pass, setPass] = useState("");
  const [fromEmail, setFromEmail] = useState("");
  const [fromName, setFromName] = useState("");
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [saving, setSaving] = useState(false);

  const showForm = editing || (!loading && !status.configured);

  function validate(): boolean {
    const e: Record<string, string> = {};
    if (!host.trim()) e.host = "SMTP host is required.";
    const p = Number(port);
    if (!Number.isInteger(p) || p < 1 || p > 65535) e.port = "Port must be 1–65535.";
    if (!user.trim()) e.user = "Username is required.";
    if (!pass.trim()) e.pass = "Password is required.";
    if (!EMAIL_RE.test(fromEmail.trim())) e.fromEmail = "A valid from-address is required.";
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function save() {
    if (!validate()) return;
    setSaving(true);
    try {
      await configure({ host: host.trim(), port: Number(port), secure, user: user.trim(), pass: pass.trim(), fromEmail: fromEmail.trim(), ...(fromName.trim() ? { fromName: fromName.trim() } : {}) });
      toast.push({ tone: "success", title: "SMTP connected", desc: "Outbound email now sends from your server." });
      setHost(""); setPort("587"); setSecure(false); setUser(""); setPass(""); setFromEmail(""); setFromName(""); setErrors({}); setEditing(false);
    } catch (err) {
      toast.push({ tone: "error", title: "Couldn't save SMTP settings", desc: (err as Error).message });
    } finally {
      setSaving(false);
    }
  }

  return (
    <div className="settings-card">
      <div className="settings-card-head">
        <span className="settings-card-ic" aria-hidden="true"><Icon name="mail" size={20} /></span>
        <div className="settings-card-titles">
          <div className="settings-card-name">Email <span className="settings-card-sub">· SMTP</span></div>
          <div className="settings-card-desc">Send external email from your own mail server.</div>
        </div>
        {status.configured ? <Pill tone="green">Connected</Pill> : <Pill tone="muted">Not connected</Pill>}
      </div>

      {status.configured && !editing ? (
        <div className="settings-card-body">
          <dl className="settings-kv">
            <div><dt>From</dt><dd>{status.fromName ? `${status.fromName} · ` : ""}{status.fromEmail ?? "—"}</dd></div>
            <div><dt>Server</dt><dd>{status.host ?? "—"}{status.port ? `:${status.port}` : ""}</dd></div>
            <div><dt>Status</dt><dd>{status.enabled ? "Active" : "Disabled"}</dd></div>
          </dl>
          <Btn variant="outline" icon="settings" onClick={() => setEditing(true)}>Update credentials</Btn>
        </div>
      ) : null}

      {showForm ? (
        <div className="settings-card-body">
          <Field label="SMTP host" required error={errors.host} hint="e.g. smtp.sendgrid.net or your mail server.">
            <input className="ds-input" value={host} onChange={(e) => setHost(e.target.value)} placeholder="smtp.example.com" autoComplete="off" />
          </Field>
          <Field label="Port" required error={errors.port} hint="587 (STARTTLS) or 465 (SSL).">
            <input className="ds-input" value={port} onChange={(e) => setPort(e.target.value)} placeholder="587" autoComplete="off" />
          </Field>
          <label className="settings-check">
            <input type="checkbox" checked={secure} onChange={(e) => setSecure(e.target.checked)} /> Use SSL/TLS (port 465)
          </label>
          <Field label="Username" required error={errors.user} hint="Often your email or an API key.">
            <input className="ds-input" value={user} onChange={(e) => setUser(e.target.value)} placeholder="apikey / user@example.com" autoComplete="off" />
          </Field>
          <Field label="Password" required error={errors.pass} hint="Encrypted on save and never shown again.">
            <input className="ds-input" type="password" value={pass} onChange={(e) => setPass(e.target.value)} placeholder="••••••••••••" autoComplete="off" />
          </Field>
          <Field label="From address" required error={errors.fromEmail}>
            <input className="ds-input" value={fromEmail} onChange={(e) => setFromEmail(e.target.value)} placeholder="no-reply@example.com" autoComplete="off" />
          </Field>
          <Field label="From name" hint="Optional display name on outgoing mail.">
            <input className="ds-input" value={fromName} onChange={(e) => setFromName(e.target.value)} placeholder="Acme Roofing" autoComplete="off" />
          </Field>
          <div className="settings-card-actions">
            <Btn icon="check-circle" onClick={save} disabled={saving}>{saving ? "Saving…" : status.configured ? "Update" : "Connect SMTP"}</Btn>
            {status.configured ? <Btn variant="ghost" onClick={() => { setEditing(false); setErrors({}); }}>Cancel</Btn> : null}
          </div>
        </div>
      ) : null}

      {!live ? <div className="settings-card-note">Demo mode — credentials are stored locally and no email is sent.</div> : null}
    </div>
  );
}
