"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { apiGet, apiPost } from "@/lib/api";

type TabKey = "EMAIL" | "GOOGLE_MAPS" | "TWILIO" | "QUICKBOOKS" | "STRIPE_CONNECT" | "OTHER";

type IntegrationTab = {
  key: TabKey;
  label: string;
  plainPurpose: string;
  neededWhen: string;
  providers: string[];
  configuredCount: number;
  connectedCount: number;
  simpleStatus: string;
  nextStep: string;
};

type IntegrationOverview = {
  tabs: IntegrationTab[];
  totals: {
    savedAccounts: number;
    connectedAccounts: number;
    emailAccounts: number;
    customSmtpAccounts: number;
  };
  safetyRule: string;
};

type ProviderAccount = {
  id: string;
  provider: string;
  rail: string;
  status: string;
  label: string;
  emailAddress?: string | null;
  displayName?: string | null;
  webhookBaseUrl?: string | null;
  smtpHost?: string | null;
  smtpPort?: number | null;
  imapHost?: string | null;
  imapPort?: number | null;
  secretLastFour?: string | null;
  isEnabled: boolean;
  lastCredentialCheckAt?: string | null;
  connectedAt?: string | null;
};

type SaveResult = {
  account: ProviderAccount;
  secretNote: string;
  encryptionReady: boolean;
};

type TestResult = {
  ok: boolean;
  simpleStatus: string;
  detail: string;
  checkedAt: string;
};

type SmtpForm = {
  emailAddress: string;
  displayName: string;
  smtpHost: string;
  smtpPort: string;
  smtpUser: string;
  smtpPassword: string;
  imapHost: string;
  imapPort: string;
};

type TwilioForm = {
  label: string;
  accountSid: string;
  authToken: string;
  fromNumber: string;
  messagingServiceSid: string;
  webhookBaseUrl: string;
};

const FALLBACK_TABS: IntegrationTab[] = [
  {
    key: "EMAIL",
    label: "Email",
    plainPurpose: "Connect Gmail, Outlook, or a company email address so CORI Mail can read, draft, and prepare replies.",
    neededWhen: "Needed when the workspace wants CORI to help with broker, driver, paperwork, and billing emails.",
    providers: ["GMAIL", "OUTLOOK", "CUSTOM_SMTP"],
    configuredCount: 0,
    connectedCount: 0,
    simpleStatus: "Not connected",
    nextStep: "Choose Gmail, Outlook, or Custom SMTP. Save the setup, then test the connection.",
  },
  {
    key: "GOOGLE_MAPS",
    label: "Google Maps API",
    plainPurpose: "Power routes, miles, Fleet Map display, geocoding, and future truck route checks.",
    neededWhen: "Needed for live route planning, Fleet Map display, mileage checks, and future route timing.",
    providers: ["GOOGLE_MAPS"],
    configuredCount: 0,
    connectedCount: 0,
    simpleStatus: "Not connected",
    nextStep: "Add the Google Maps browser key for Fleet Map display, then prepare server-side Routes API access when route timing is approved.",
  },
  {
    key: "TWILIO",
    label: "Twilio",
    plainPurpose: "Run business calling, browser dialer, inbound routing, voicemail, and CORI call support.",
    neededWhen: "Needed when the workspace wants managed business phone numbers and live call assistance.",
    providers: ["TWILIO"],
    configuredCount: 0,
    connectedCount: 0,
    simpleStatus: "Not connected",
    nextStep: "Add Twilio account details when the workspace is ready for phone numbers and calling.",
  },
  {
    key: "QUICKBOOKS",
    label: "QuickBooks API",
    plainPurpose: "Sync invoices, payments, customers, and accounting records without double entry.",
    neededWhen: "Useful for companies that already use QuickBooks for accounting.",
    providers: ["QUICKBOOKS"],
    configuredCount: 0,
    connectedCount: 0,
    simpleStatus: "Not connected",
    nextStep: "Connect QuickBooks when the workspace is ready to sync invoices and payments.",
  },
  {
    key: "STRIPE_CONNECT",
    label: "Stripe Connect",
    plainPurpose: "Let dispatcher workspaces bill carriers for dispatch services through their own connected Stripe path.",
    neededWhen: "Needed when a dispatcher company wants card or bank payments from carriers.",
    providers: ["STRIPE_CONNECT"],
    configuredCount: 0,
    connectedCount: 0,
    simpleStatus: "Not connected",
    nextStep: "Connect only for dispatcher-service billing. Platform subscriptions stay separate in Super Admin.",
  },
  {
    key: "OTHER",
    label: "Other APIs",
    plainPurpose: "Hold future integrations such as DAT, weather providers, ELDs, factoring, insurance, and compliance tools.",
    neededWhen: "Only needed when a workspace uses one of those services.",
    providers: ["DAT_LOAD_BOARD", "WEATHER_API", "ELD", "FACTORING", "OTHER"],
    configuredCount: 0,
    connectedCount: 0,
    simpleStatus: "Not connected",
    nextStep: "Add only the integrations the workspace actually uses so settings stay simple.",
  },
];

const EMPTY_SMTP_FORM: SmtpForm = {
  emailAddress: "dispatch@yourcompany.com",
  displayName: "Dispatch Team",
  smtpHost: "smtp.yourcompany.com",
  smtpPort: "587",
  smtpUser: "dispatch@yourcompany.com",
  smtpPassword: "",
  imapHost: "imap.yourcompany.com",
  imapPort: "993",
};

const EMPTY_TWILIO_FORM: TwilioForm = {
  label: "Twilio text alerts",
  accountSid: "",
  authToken: "",
  fromNumber: "+15555550123",
  messagingServiceSid: "",
  webhookBaseUrl: "",
};

function badgeClass(status: string) {
  if (status === "Connected") return "border-emerald-200 bg-emerald-50 text-emerald-800";
  if (status === "Staged") return "border-sky-200 bg-sky-50 text-sky-800";
  return "border-slate-200 bg-slate-50 text-slate-700";
}

function readableProvider(provider: string) {
  return provider
    .toLowerCase()
    .split("_")
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(" ");
}

export default function WorkspaceIntegrationsPage() {
  const [activeTab, setActiveTab] = useState<TabKey>("EMAIL");
  const [overview, setOverview] = useState<IntegrationOverview | null>(null);
  const [accounts, setAccounts] = useState<ProviderAccount[]>([]);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState("Loading integration settings...");
  const [smtpForm, setSmtpForm] = useState<SmtpForm>(EMPTY_SMTP_FORM);
  const [twilioForm, setTwilioForm] = useState<TwilioForm>(EMPTY_TWILIO_FORM);
  const [testingAccountId, setTestingAccountId] = useState<string | null>(null);

  useEffect(() => {
    let mounted = true;
    async function load() {
      try {
        setLoading(true);
        const [overviewData, accountData] = await Promise.all([
          apiGet<{ overview: IntegrationOverview }>("/api/workspace-integrations"),
          apiGet<{ accounts: ProviderAccount[] }>("/api/workspace-integrations/provider-accounts"),
        ]);
        if (!mounted) return;
        setOverview(overviewData.overview);
        setAccounts(accountData.accounts);
        setStatus("Integration settings loaded.");
      } catch (error: any) {
        if (!mounted) return;
        setOverview({
          tabs: FALLBACK_TABS,
          totals: { savedAccounts: 0, connectedAccounts: 0, emailAccounts: 0, customSmtpAccounts: 0 },
          safetyRule: "Integration storage is being prepared. The page is still usable as a setup map.",
        });
        setStatus(error?.message ?? "Integration settings are not connected yet.");
      } finally {
        if (mounted) setLoading(false);
      }
    }
    load();
    return () => {
      mounted = false;
    };
  }, []);

  const tabs = overview?.tabs?.length ? overview.tabs : FALLBACK_TABS;
  const active = useMemo<IntegrationTab>(() => tabs.find((tab) => tab.key === activeTab) ?? FALLBACK_TABS[0], [activeTab, tabs]);
  const activeAccounts = accounts.filter((account) => active.providers.includes(account.provider));

  function updateSmtpForm(field: keyof SmtpForm, value: string) {
    setSmtpForm((current) => ({ ...current, [field]: value }));
    setStatus("Email setup edited. Save it, then test the connection.");
  }

  function updateTwilioForm(field: keyof TwilioForm, value: string) {
    setTwilioForm((current) => ({ ...current, [field]: value }));
    setStatus("Twilio setup edited. Save it here before turning on text alerts for users.");
  }

  async function saveSmtpAccount() {
    if (!smtpForm.emailAddress.includes("@") || !smtpForm.smtpHost.trim() || !smtpForm.smtpUser.trim() || !smtpForm.smtpPassword.trim()) {
      setStatus("Add the from email, SMTP host, username, and app password before saving.");
      return;
    }

    try {
      const result = await apiPost<SaveResult>("/api/workspace-integrations/provider-accounts", {
        provider: "CUSTOM_SMTP",
        rail: "SMTP",
        status: "TEST_READY",
        label: "Custom domain email",
        emailAddress: smtpForm.emailAddress,
        displayName: smtpForm.displayName,
        smtpHost: smtpForm.smtpHost,
        smtpPort: smtpForm.smtpPort,
        imapHost: smtpForm.imapHost,
        imapPort: smtpForm.imapPort,
        secretPayload: {
          smtpUser: smtpForm.smtpUser,
          smtpPassword: smtpForm.smtpPassword,
        },
        publicConfigJson: {
          purpose: "CORI Mail custom domain email",
          sendRequiresUserApproval: true,
        },
      });
      setAccounts((current) => [result.account, ...current]);
      setSmtpForm((current) => ({ ...current, smtpPassword: "" }));
      setStatus(result.encryptionReady ? "Custom email setup saved." : result.secretNote);
    } catch (error: any) {
      setStatus(error?.message ?? "Custom SMTP could not be saved yet.");
    }
  }

  async function saveTwilioAccount() {
    if (!twilioForm.accountSid.trim() || !twilioForm.authToken.trim() || (!twilioForm.fromNumber.trim() && !twilioForm.messagingServiceSid.trim())) {
      setStatus("Add the Twilio Account SID, auth token, and either a from number or messaging service before saving.");
      return;
    }

    try {
      const result = await apiPost<SaveResult>("/api/workspace-integrations/provider-accounts", {
        provider: "TWILIO",
        rail: "ACCOUNT_SID",
        status: "TEST_READY",
        label: twilioForm.label || "Twilio text alerts",
        externalAccountId: twilioForm.accountSid,
        webhookBaseUrl: twilioForm.webhookBaseUrl,
        secretPayload: {
          accountSid: twilioForm.accountSid,
          authToken: twilioForm.authToken,
        },
        publicConfigJson: {
          fromNumber: twilioForm.fromNumber,
          messagingServiceSid: twilioForm.messagingServiceSid,
          purpose: "urgent notification text alerts",
          userOptInRequired: true,
        },
      });
      setAccounts((current) => [result.account, ...current]);
      setTwilioForm((current) => ({ ...current, authToken: "" }));
      setStatus(result.encryptionReady ? "Twilio setup saved for future urgent text alerts." : result.secretNote);
    } catch (error: any) {
      setStatus(error?.message ?? "Twilio setup could not be saved yet.");
    }
  }

  async function testSavedAccount(accountId: string) {
    try {
      setTestingAccountId(accountId);
      setStatus("Testing this saved SMTP account now. No email will be sent.");
      const data = await apiPost<{ result: TestResult }>(`/api/workspace-integrations/provider-accounts/${accountId}/test`, {});
      const [overviewData, accountData] = await Promise.all([
        apiGet<{ overview: IntegrationOverview }>("/api/workspace-integrations"),
        apiGet<{ accounts: ProviderAccount[] }>("/api/workspace-integrations/provider-accounts"),
      ]);
      setOverview(overviewData.overview);
      setAccounts(accountData.accounts);
      setStatus(data.result.ok ? "SMTP test passed. This company email is ready for guarded send preparation." : `SMTP test failed: ${data.result.detail}`);
    } catch (error: any) {
      setStatus(error?.message ?? "SMTP account could not be tested yet.");
    } finally {
      setTestingAccountId(null);
    }
  }


  return (
    <div className="space-y-6">
      <section className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
        <div className="flex flex-col gap-5 xl:flex-row xl:items-start xl:justify-between">
          <div className="max-w-3xl">
            <div className="inline-flex rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold uppercase tracking-[0.18em] text-slate-700">Workspace settings</div>
            <h1 className="mt-4 text-3xl font-semibold tracking-tight text-slate-950">Third-Party Integrations</h1>
            <p className="mt-3 text-base leading-7 text-slate-600">
              Connect only the outside services this workspace needs. Keep the setup simple for users, while Dispatch Spot stores tokens and passwords safely behind the scenes.
            </p>
          </div>
          <div className="grid gap-3 sm:grid-cols-3">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">Saved</div>
              <div className="mt-2 text-2xl font-semibold text-slate-950">{overview?.totals.savedAccounts ?? 0}</div>
            </div>
            <div className="rounded-2xl border border-emerald-200 bg-emerald-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.16em] text-emerald-700">Connected</div>
              <div className="mt-2 text-2xl font-semibold text-emerald-900">{overview?.totals.connectedAccounts ?? 0}</div>
            </div>
            <div className="rounded-2xl border border-sky-200 bg-sky-50 p-4">
              <div className="text-xs font-semibold uppercase tracking-[0.16em] text-sky-700">Email</div>
              <div className="mt-2 text-2xl font-semibold text-sky-900">{overview?.totals.emailAccounts ?? 0}</div>
            </div>
          </div>
        </div>
      </section>

      <section className="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm">
        <div className="flex gap-2 overflow-x-auto pb-2">
          {tabs.map((tab) => (
            <button
              key={tab.key}
              type="button"
              onClick={() => setActiveTab(tab.key)}
              className={`min-w-fit rounded-2xl px-4 py-3 text-sm font-semibold transition ${activeTab === tab.key ? "bg-slate-950 text-white" : "border border-slate-200 bg-white text-slate-700 hover:bg-slate-50"}`}
            >
              {tab.label}
            </button>
          ))}
        </div>
      </section>

      <section className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,0.85fr)]">
        <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
          <div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
            <div>
              <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">{active.label}</div>
              <h2 className="mt-2 text-2xl font-semibold text-slate-950">{active.label} setup</h2>
              <p className="mt-2 text-sm leading-6 text-slate-600">{active.plainPurpose}</p>
            </div>
            <span className={`rounded-full border px-3 py-1 text-xs font-semibold ${badgeClass(active.simpleStatus)}`}>{active.simpleStatus}</span>
          </div>

          <div className="mt-5 grid gap-3 md:grid-cols-2">
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-sm font-semibold text-slate-950">When needed</div>
              <p className="mt-1 text-sm leading-6 text-slate-600">{active.neededWhen}</p>
            </div>
            <div className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
              <div className="text-sm font-semibold text-slate-950">Next step</div>
              <p className="mt-1 text-sm leading-6 text-slate-600">{active.nextStep}</p>
            </div>
          </div>

          {active.key === "EMAIL" ? (
            <div className="mt-6 rounded-3xl border border-sky-200 bg-sky-50 p-5">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                <div>
                  <h3 className="text-xl font-semibold text-slate-950">Add company email with SMTP</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-700">Use this for addresses like dispatch@carrier.com. CORI can draft from this address, but every real send still needs user approval.</p>
                </div>
                <Link href="/cori/mail" className="rounded-2xl bg-white px-4 py-3 text-sm font-semibold text-slate-800 shadow-sm">Open CORI Mail</Link>
              </div>
              <div className="mt-5 grid gap-3 md:grid-cols-2">
                <label className="text-sm font-semibold text-slate-700">From email<input value={smtpForm.emailAddress} onChange={(event) => updateSmtpForm("emailAddress", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">Display name<input value={smtpForm.displayName} onChange={(event) => updateSmtpForm("displayName", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">SMTP host<input value={smtpForm.smtpHost} onChange={(event) => updateSmtpForm("smtpHost", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">SMTP port<input value={smtpForm.smtpPort} onChange={(event) => updateSmtpForm("smtpPort", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">SMTP username<input value={smtpForm.smtpUser} onChange={(event) => updateSmtpForm("smtpUser", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">App password<input type="password" value={smtpForm.smtpPassword} onChange={(event) => updateSmtpForm("smtpPassword", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">IMAP host<input value={smtpForm.imapHost} onChange={(event) => updateSmtpForm("imapHost", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">IMAP port<input value={smtpForm.imapPort} onChange={(event) => updateSmtpForm("imapPort", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
              </div>
              <div className="mt-4 flex flex-wrap gap-2">
                <button type="button" onClick={() => setStatus("SMTP setup looks ready. Save it first, then click Test SMTP connection on the saved account. No email will be sent during the test.")} className="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700">Check setup</button>
                <button type="button" onClick={saveSmtpAccount} className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white">Save email setup</button>
              </div>
            </div>
          ) : active.key === "TWILIO" ? (
            <div className="mt-6 rounded-3xl border border-violet-200 bg-violet-50 p-5">
              <div className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between">
                <div>
                  <h3 className="text-xl font-semibold text-slate-950">Add Twilio for text alerts</h3>
                  <p className="mt-1 text-sm leading-6 text-slate-700">Use this for future urgent text alerts. Users still need to opt in before any text is sent.</p>
                </div>
                <Link href="/notifications" className="rounded-2xl bg-white px-4 py-3 text-sm font-semibold text-slate-800 shadow-sm">Open Notifications</Link>
              </div>
              <div className="mt-5 grid gap-3 md:grid-cols-2">
                <label className="text-sm font-semibold text-slate-700">Label<input value={twilioForm.label} onChange={(event) => updateTwilioForm("label", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">Account SID<input value={twilioForm.accountSid} onChange={(event) => updateTwilioForm("accountSid", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">Auth token<input type="password" value={twilioForm.authToken} onChange={(event) => updateTwilioForm("authToken", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">From number<input value={twilioForm.fromNumber} onChange={(event) => updateTwilioForm("fromNumber", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">Messaging service SID<input value={twilioForm.messagingServiceSid} onChange={(event) => updateTwilioForm("messagingServiceSid", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
                <label className="text-sm font-semibold text-slate-700">Webhook base URL<input value={twilioForm.webhookBaseUrl} onChange={(event) => updateTwilioForm("webhookBaseUrl", event.target.value)} className="mt-2 h-11 w-full rounded-2xl border border-slate-200 px-4 text-sm font-normal outline-none focus:border-slate-400" /></label>
              </div>
              <div className="mt-4 flex flex-wrap gap-2">
                <button type="button" onClick={() => setStatus("Twilio setup looks ready to save. Text alerts still require each user to opt in.")} className="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700">Check setup</button>
                <button type="button" onClick={saveTwilioAccount} className="rounded-2xl bg-slate-950 px-4 py-3 text-sm font-semibold text-white">Save Twilio setup</button>
              </div>
            </div>
          ) : (
            <div className="mt-6 rounded-3xl border border-slate-200 bg-slate-50 p-5">
              <h3 className="text-xl font-semibold text-slate-950">{active.label} belongs here</h3>
              <p className="mt-2 text-sm leading-6 text-slate-600">This tab is the single home for {active.label} setup. Any older duplicate setup area should be removed from daily pages and Workspace Settings.</p>
              <div className="mt-4 rounded-2xl border border-slate-200 bg-white p-4 text-sm leading-6 text-slate-600">
                Keep connection details and tests here. Main work pages should only show simple results, warnings, and next steps.
              </div>
            </div>
          )}
        </div>

        <div className="space-y-4">
          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Setup status</div>
            <p className="mt-2 text-sm leading-6 text-slate-600">{loading ? "Loading..." : status}</p>
            <div className="mt-4 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm leading-6 text-amber-800">{overview?.safetyRule}</div>
          </div>

          <div className="rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="text-xs font-semibold uppercase tracking-[0.18em] text-slate-400">Saved accounts</div>
                <h3 className="mt-2 text-xl font-semibold text-slate-950">{active.label}</h3>
              </div>
              <span className="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{activeAccounts.length}</span>
            </div>
            <div className="mt-4 space-y-3">
              {activeAccounts.length ? activeAccounts.map((account) => (
                <div key={account.id} className="rounded-2xl border border-slate-200 bg-slate-50 p-4">
                  <div className="flex items-start justify-between gap-3">
                    <div>
                      <div className="text-sm font-semibold text-slate-950">{account.label}</div>
                      <div className="mt-1 text-xs text-slate-500">{readableProvider(account.provider)} · {account.rail}</div>
                    </div>
                    <span className="rounded-full bg-white px-3 py-1 text-xs font-semibold text-slate-700">{account.status}</span>
                  </div>
                  {account.emailAddress ? <p className="mt-2 text-sm text-slate-600">{account.emailAddress}</p> : null}
                  {account.smtpHost ? <p className="mt-1 text-xs text-slate-500">SMTP: {account.smtpHost}:{account.smtpPort ?? ""}</p> : null}
                  {account.secretLastFour ? <p className="mt-1 text-xs text-slate-500">Saved password ends in {account.secretLastFour}</p> : null}
                  {account.provider === "CUSTOM_SMTP" ? (
                    <button
                      type="button"
                      onClick={() => testSavedAccount(account.id)}
                      disabled={testingAccountId === account.id}
                      className="mt-3 rounded-2xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 disabled:cursor-wait disabled:bg-slate-100"
                    >
                      {testingAccountId === account.id ? "Testing..." : "Test SMTP connection"}
                    </button>
                  ) : null}
                  {account.lastCredentialCheckAt ? <p className="mt-2 text-xs text-slate-500">Last checked: {new Date(account.lastCredentialCheckAt).toLocaleString()}</p> : null}
                </div>
              )) : (
                <div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-4 text-sm leading-6 text-slate-500">No saved account for this tab yet.</div>
              )}
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
