'use client';

import Link from 'next/link';
import { useCallback, useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { errorText, isApiError } from '@/lib/api/errors';
import { getBusinessSettings, updateBusinessSettings } from '../api.client';
import type { BusinessSettings, UpdateBusinessSettingsBody } from '../types';
import {
  ComingSoon,
  SetTabs,
  SettingsForm,
  SettingsFormsProvider,
  SuField,
  SuRadio,
  TabPanel,
  useHashTab,
} from './settings-ui';

/**
 * Settings > Integrations > Email Service Provider (design: settings-email-provider.php).
 * Email from the CRM goes out through each user's connected Gmail; what the API lets an
 * admin set here is open / click tracking (tracking domain + switch) and the sending
 * limits, all on GET/PATCH /business/settings. Sending domains and SMTP are not in the
 * API yet and are shown disabled.
 */

const TABS = [
  { id: 'esp-domains', label: 'Sending domains' },
  { id: 'esp-provider', label: 'Provider' },
  { id: 'esp-defaults', label: 'Defaults' },
];

const field = (form: HTMLFormElement, name: string) =>
  (form.elements.namedItem(name) as HTMLInputElement | null)?.value ?? '';
const checked = (form: HTMLFormElement, name: string) =>
  !!(form.elements.namedItem(name) as HTMLInputElement | null)?.checked;

/** Shown when the daily limit is below the hourly one (QA #548; the API refuses it too). */
const dailyBelowHourly = (hourly: number) =>
  `Must be at least the hourly limit (${hourly.toLocaleString('en-US')}): emails per day can't be fewer than emails per hour`;

/** The hourly and daily limits typed in the form (NaN while a box is empty). */
const limitsOf = (form: HTMLFormElement) => ({
  hourly: Number(field(form, 'hourly_limit') || NaN),
  daily: Number(field(form, 'daily_limit') || NaN),
});

const isDailyBelowHourly = ({ hourly, daily }: { hourly: number; daily: number }) =>
  Number.isFinite(hourly) && Number.isFinite(daily) && daily < hourly;

const postalAddress = (s: BusinessSettings) =>
  [s.name, s.addressLine1, s.addressLine2, s.city, s.state, s.postalCode, s.country]
    .filter(Boolean)
    .join(', ');

export function EmailProviderSettingsView() {
  const me = useCurrentUser();
  const toast = useToast();
  const [tab, setTab] = useHashTab(TABS);
  const isAdmin = me.role === 'admin';
  const [settings, setSettings] = useState<BusinessSettings | null>(null);
  const updatedAt = useRef<string | undefined>(undefined);
  /** The limits as typed, for the inline daily ≥ hourly check; null = as saved. */
  const [limits, setLimits] = useState<{ hourly: number; daily: number } | null>(null);
  const hourlyNow = limits?.hourly ?? settings?.emailHourlyLimit ?? 1;
  const dailyBad = isDailyBelowHourly(
    limits ?? {
      hourly: settings?.emailHourlyLimit ?? NaN,
      daily: settings?.emailDailyLimit ?? NaN,
    },
  );

  /** Re-checks the two limits as they are typed and flags the daily one inline. */
  const checkLimits = (e: React.FormEvent<HTMLInputElement>) => {
    const form = e.currentTarget.form;
    if (!form) return;
    const next = limitsOf(form);
    setLimits(next);
    const day = form.querySelector<HTMLInputElement>('#limit-day');
    const bad = isDailyBelowHourly(next);
    // Out of range values keep the field's own error; this only adds or clears "below hourly".
    if (day && (bad || day.closest('.field')?.classList.contains('is-invalid'))) {
      const invalid = bad || day.validity.rangeOverflow || day.validity.valueMissing;
      day.closest('.field')?.classList.toggle('is-invalid', invalid);
      day.setAttribute('aria-invalid', invalid ? 'true' : 'false');
    }
  };

  useEffect(() => {
    getBusinessSettings().then(
      (s) => {
        updatedAt.current = s.updatedAt;
        setSettings(s);
      },
      (err) => toast(errorText(err), 'danger'),
    );
  }, [toast]);

  const save = useCallback(
    async (body: UpdateBusinessSettingsBody) => {
      try {
        const s = await updateBusinessSettings({ ...body, updatedAt: updatedAt.current });
        updatedAt.current = s.updatedAt;
        setSettings(s);
      } catch (err) {
        toast(
          isApiError(err) && err.isConflict
            ? 'These settings changed somewhere else. Reload the page to see the latest values.'
            : errorText(err),
          'danger',
        );
        return false;
      }
    },
    [toast],
  );

  const saveTracking = useCallback(
    (form: HTMLFormElement) => {
      const domain = field(form, 'tracking_domain').trim().toLowerCase();
      const enabled = checked(form, 'tracking_enabled');
      if (enabled && !domain) {
        toast('Add a tracking domain before turning tracking on', 'danger');
        return false;
      }
      const typed = limitsOf(form);
      if (isDailyBelowHourly(typed)) {
        toast(dailyBelowHourly(typed.hourly), 'danger');
        return false;
      }
      return save({
        trackingDomain: domain || null,
        trackingEnabled: enabled,
        emailHourlyLimit: Number(field(form, 'hourly_limit')),
        emailDailyLimit: Number(field(form, 'daily_limit')),
      });
    },
    [save, toast],
  );

  const header = (
    <>
      <header className="set-head">
        <div>
          <h1 className="set-head__title">Email Service Provider</h1>
          <p className="set-head__sub">
            Choose how marketing and automated emails are sent, and prove they really come from your
            domain.
          </p>
        </div>
      </header>
      <SetTabs label="Email sending" tabs={TABS} active={tab} onSelect={setTab} boxed />
    </>
  );

  return (
    <SettingsFormsProvider>
      {header}

      {/* ===================================================== SENDING DOMAINS */}
      <TabPanel id="esp-domains" active={tab}>
        <p className="set-intro">
          Connect the domains you send from. Verified SPF, DKIM and DMARC records keep your email
          out of spam folders.
        </p>
        <div className="su-section__head">
          <h2 className="su-section__title">Domains (0)</h2>
          <button type="button" className="btn-crm btn-crm--primary btn-crm--sm" disabled>
            <CrmIcon name="plus" className="iconSize-16" />
            Connect a domain
          </button>
        </div>
        <div className="card set-table-card">
          <p className="su-empty">
            Sending domains are coming soon. Today each user&apos;s email goes out through their own
            connected Gmail, so Google&apos;s SPF and DKIM apply.
          </p>
        </div>
      </TabPanel>

      {/* =========================================================== PROVIDER */}
      <TabPanel id="esp-provider" active={tab}>
        <SettingsForm readOnly>
          <div className="su-section">
            <h2 className="su-section__title crm-mb-3">Send email through</h2>
            <div className="su-list" style={{ maxWidth: 620 }}>
              <SuRadio
                name="provider"
                value="gmail"
                title="Each user's Gmail (current)"
                desc="Email is sent from the address the user connected in Settings › General › Email."
                defaultChecked
              />
              <SuRadio
                name="provider"
                value="smtp"
                title="Your own SMTP server"
                desc="Amazon SES, SendGrid, Mailgun or your mail server. Coming soon."
              />
            </div>
          </div>
        </SettingsForm>
        <p className="field__help">
          <Link className="link" href="/settings/profile#tab-email">
            Manage your connected Gmail
          </Link>
        </p>
      </TabPanel>

      {/* =========================================================== DEFAULTS */}
      <TabPanel id="esp-defaults" active={tab}>
        {settings === null ? (
          <p className="crm-text-muted">Loading…</p>
        ) : (
          <SettingsForm onSave={saveTracking} onReset={() => setLimits(null)} readOnly={!isAdmin}>
            {!isAdmin ? <p className="set-intro">Only admins can change these settings.</p> : null}
            <div className="su-section">
              <h2 className="su-section__title crm-mb-3">Open and click tracking</h2>
              <div className="su-toggle">
                <label className="switch">
                  <input
                    type="checkbox"
                    id="tg-tracking"
                    name="tracking_enabled"
                    defaultChecked={settings.trackingEnabled}
                  />
                  <span className="switch__track" />
                </label>
                <div className="su-toggle__body">
                  <label className="su-toggle__title" htmlFor="tg-tracking">
                    Track opens and clicks
                  </label>
                  <p className="su-toggle__desc">
                    Applies to email sent from the CRM. Each email can still be sent untracked.
                  </p>
                </div>
              </div>
            </div>
            <div className="set-stack">
              <SuField
                label="Tracking domain"
                htmlFor="track-domain"
                help="A host name your IT points (CNAME) at the CRM, e.g. t.yourcompany.com. Needed for tracking."
                error="Enter a host name like t.yourcompany.com"
              >
                <input
                  className="input"
                  id="track-domain"
                  name="tracking_domain"
                  defaultValue={settings.trackingDomain ?? ''}
                  pattern="^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$"
                  placeholder="t.yourcompany.com"
                />
              </SuField>
              <SuField
                label="Emails per hour (per user)"
                htmlFor="limit-hour"
                error="Enter a number from 1 to 10,000"
              >
                <input
                  className="input"
                  id="limit-hour"
                  name="hourly_limit"
                  type="number"
                  min={1}
                  max={10000}
                  required
                  defaultValue={settings.emailHourlyLimit}
                  onInput={checkLimits}
                />
              </SuField>
              <SuField
                label="Emails per day (per user)"
                htmlFor="limit-day"
                help="Can't be lower than emails per hour."
                error={dailyBad ? dailyBelowHourly(hourlyNow) : 'Enter a number from 1 to 100,000'}
              >
                <input
                  className="input"
                  id="limit-day"
                  name="daily_limit"
                  type="number"
                  // The hourly limit as typed: a lower daily one fails the form's check on save.
                  min={Math.max(1, Number.isFinite(hourlyNow) ? hourlyNow : 1)}
                  max={100000}
                  required
                  defaultValue={settings.emailDailyLimit}
                  onInput={checkLimits}
                />
              </SuField>
              <div className="field">
                <label className="field__label" htmlFor="def-footer">
                  Company address in email footer
                </label>
                <textarea
                  className="input"
                  id="def-footer"
                  rows={2}
                  value={postalAddress(settings)}
                  readOnly
                  disabled
                />
                <p className="field__help">
                  Used in the unsubscribe footer. Change it in{' '}
                  <Link className="link" href="/settings/account-defaults">
                    Account Defaults
                  </Link>
                  .
                </p>
              </div>
            </div>
            <div className="set-stack crm-mt-4">
              <div className="field">
                <label className="field__label" htmlFor="def-from">
                  Default &quot;From&quot; and reply-to addresses
                </label>
                <input
                  className="input"
                  id="def-from"
                  value="The sender's connected Gmail address"
                  readOnly
                  disabled
                />
                <ComingSoon>Custom From and reply-to defaults are coming soon.</ComingSoon>
              </div>
            </div>
          </SettingsForm>
        )}
      </TabPanel>
    </SettingsFormsProvider>
  );
}
