'use client';

import { useCallback, useEffect, useState } from 'react';
import { BrandLogo } from '@/components/crm/BrandLogo';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  DialogHead,
  SetDialog,
  SetTabs,
  SettingsForm,
  SettingsFormsProvider,
  SuToggle,
  TabPanel,
  useHashTab,
} from '@/features/settings/ui/settings-ui';
import { apiDelete, apiGet, apiPatch, apiPost } from '@/lib/api/client';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

type Domain = { id: string; domain: string; type: 'hosted' | 'external' };

type Settings = {
  publicKey: string;
  scriptPath: string;
  consentRequired: boolean;
  crossDomainLinking: boolean;
  limitToListedDomains: boolean;
  limitCookiesToSubdomains: boolean;
  secureCookiesOnly: boolean;
  botFiltering: boolean;
  smsBotFiltering: boolean;
  intentDataAccess: boolean;
  excludeIps: string;
  excludeReferrers: string;
  domains: Domain[];
  callerIp: string | null;
};

const TABS = [
  { id: 'tc-code', label: 'Tracking code' },
  { id: 'tc-advanced', label: 'Advanced tracking' },
];

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

const text = (form: HTMLFormElement, name: string) =>
  String((form.elements.namedItem(name) as HTMLTextAreaElement | null)?.value ?? '');

/**
 * Settings › Tracking & Analysis › Tracking Code
 * Design: settings-tracking-code.php
 */
export function TrackingCodeSettingsView() {
  const toast = useToast();
  const me = useCurrentUser();
  const [tab, setTab] = useHashTab(TABS, 'tc-code');
  const [settings, setSettings] = useState<Settings | null>(null);
  const [wpOpen, setWpOpen] = useState(false);
  const [emailOpen, setEmailOpen] = useState(false);
  const [domainOpen, setDomainOpen] = useState(false);
  const [emailPreview, setEmailPreview] = useState(false);
  const [devEmail, setDevEmail] = useState('');
  const [emailInvalid, setEmailInvalid] = useState(false);
  const [newDomain, setNewDomain] = useState('');
  const [validateUrl, setValidateUrl] = useState('');
  const [validateMsg, setValidateMsg] = useState<{ ok: boolean; text: string } | null>(null);

  const load = useCallback(async () => {
    try {
      setSettings(await apiGet<Settings>('/website-tracking/settings'));
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  }, [toast]);

  useEffect(() => {
    void load();
  }, [load]);

  const base = typeof window !== 'undefined' ? window.location.origin : '';
  const snippet = settings
    ? `<!-- Start of AdMedia CRM tracking code -->\n<script type="text/javascript" id="crm-script-loader" async defer src="${base}${settings.scriptPath}"></script>\n<!-- End of AdMedia CRM tracking code -->`
    : '';

  const copy = (textValue: string, what: string) =>
    void navigator.clipboard
      .writeText(textValue)
      .then(() => toast(`${what} copied`, 'success'))
      .catch(() => toast(`Could not copy the ${what.toLowerCase()}`, 'danger'));

  const saveAdvanced = async (form: HTMLFormElement) => {
    try {
      const next = await apiPatch<Settings>('/website-tracking/settings', {
        crossDomainLinking: checked(form, 'tc_cross_domain'),
        limitToListedDomains: checked(form, 'tc_limit_domains'),
        limitCookiesToSubdomains: checked(form, 'tc_subdomains'),
        secureCookiesOnly: checked(form, 'tc_secure'),
        botFiltering: checked(form, 'tc_bot_filter'),
        smsBotFiltering: checked(form, 'tc_sms_filter'),
        intentDataAccess: checked(form, 'tc_intent'),
        excludeIps: text(form, 'exclude_ips'),
        excludeReferrers: text(form, 'exclude_referrers'),
      });
      setSettings(next);
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const validate = async (e: React.FormEvent) => {
    e.preventDefault();
    const url = validateUrl.trim();
    if (!url.startsWith('https://')) {
      setValidateMsg({ ok: false, text: 'Enter a full https:// URL.' });
      return;
    }
    try {
      const res = await apiPost<{ ok: boolean; message: string }>('/website-tracking/validate', {
        url,
      });
      setValidateMsg({ ok: res.ok, text: res.message });
    } catch (err) {
      setValidateMsg({ ok: false, text: errorText(err) });
    }
  };

  const closeEmail = () => {
    setEmailOpen(false);
    setDevEmail('');
    setEmailInvalid(false);
    setEmailPreview(false);
  };

  const sendEmail = async (e: React.FormEvent) => {
    e.preventDefault();
    const email = devEmail.trim();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      setEmailInvalid(true);
      return;
    }
    try {
      const res = await apiPost<{ ok: true; message: string }>('/website-tracking/email-snippet', {
        email,
      });
      toast(res.message || 'Tracking code email prepared', 'success');
      closeEmail();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const addDomain = async (e: React.FormEvent) => {
    e.preventDefault();
    const domain = newDomain.trim().toLowerCase();
    if (!domain) return;
    try {
      const created = await apiPost<Domain>('/website-tracking/domains', { domain });
      setSettings((cur) => (cur ? { ...cur, domains: [...cur.domains, created] } : cur));
      setDomainOpen(false);
      setNewDomain('');
      toast('Domain added', 'success');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const removeDomain = async (id: string) => {
    try {
      await apiDelete(`/website-tracking/domains/${id}`);
      setSettings((cur) =>
        cur ? { ...cur, domains: cur.domains.filter((d) => d.id !== id) } : cur,
      );
      toast('Domain removed', 'info');
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  if (!settings) {
    return (
      <div className="tc-page">
        <header className="set-head">
          <div>
            <h1 className="set-head__title">Reports &amp; Analytics Tracking</h1>
            <p className="set-head__sub">Loading…</p>
          </div>
        </header>
      </div>
    );
  }

  return (
    <SettingsFormsProvider>
      <div className="tc-page">
        <header className="set-head">
          <div>
            <h1 className="set-head__title">Reports &amp; Analytics Tracking</h1>
          </div>
        </header>

        <SetTabs
          label="Reports & Analytics Tracking"
          tabs={TABS}
          active={tab}
          onSelect={setTab}
          boxed
        />

        <TabPanel id="tc-code" active={tab}>
          <section className="tc-panel" aria-label="Tracking code">
            <div className="tc-section">
              <h2 className="tc-heading">Tracking code installation</h2>
              <p className="tc-copy">
                Copy and paste this tracking code onto every page of your site, just before the
                closing <code>&lt;/body&gt;</code> tag.
              </p>
              <div className="tc-field-heading">Embed code</div>
              <p className="tc-copy tc-copy--small">
                Detailed instructions for installing tracking code can be found{' '}
                <button
                  type="button"
                  className="link"
                  onClick={() => toast('Tracking install help is coming soon.', 'info')}
                >
                  here
                </button>
                . Tips for validating your tracking code installation can be found{' '}
                <button
                  type="button"
                  className="link"
                  onClick={() => toast('Validation tips are coming soon.', 'info')}
                >
                  here
                </button>
                .
              </p>
              <div className="tc-codebox">
                <pre id="tc-snippet">{snippet}</pre>
              </div>
              <div className="tc-actions">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  onClick={() => copy(snippet, 'Tracking code')}
                >
                  Copy
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  onClick={() => setEmailOpen(true)}
                >
                  <CrmIcon name="mail" className="iconSize-16" /> <span>Email to developer</span>
                </button>
              </div>
            </div>

            <div className="tc-section tc-validate">
              <h2 className="tc-heading">Validate your tracking code</h2>
              <p className="tc-copy">
                Enter the full URL of your website page. We&apos;ll check if the tracking code is
                correctly installed and reporting data to your account.
              </p>
              <form className="tc-validate-form" onSubmit={(e) => void validate(e)} noValidate>
                <label className="field__label" htmlFor="tc-validate-url">
                  Enter a URL
                </label>
                <p className="field__help">(https:// required)</p>
                <input
                  className="input crm-mb-2"
                  id="tc-validate-url"
                  type="url"
                  placeholder="https://example.com/page"
                  required
                  value={validateUrl}
                  onChange={(e) => setValidateUrl(e.target.value)}
                />
                {validateMsg ? (
                  <p className={`tc-feedback ${validateMsg.ok ? 'is-ok' : 'is-bad'}`} role="status">
                    {validateMsg.text}
                  </p>
                ) : null}
                <button className="btn-crm btn-crm--outline" type="submit">
                  Validate URL
                </button>
              </form>
            </div>

            <div className="tc-section tc-wordpress">
              <button
                className="tc-accordion"
                type="button"
                aria-expanded={wpOpen}
                aria-controls="tc-wordpress-content"
                onClick={() => setWpOpen((v) => !v)}
              >
                <span className="tc-accordion__chevron" aria-hidden="true">
                  <CrmIcon name="chevron-right" className="iconSize-16" />
                </span>
                <span>WordPress installation</span>
              </button>
              <div id="tc-wordpress-content" className="tc-accordion__content" hidden={!wpOpen}>
                <p className="tc-copy">
                  Install the CRM tracking plugin on your WordPress website to add your tracking
                  code automatically.
                </p>
                <p>
                  <button
                    type="button"
                    className="link"
                    onClick={() => toast('WordPress plugin download is coming soon.', 'info')}
                  >
                    Download the WordPress plugin
                  </button>
                </p>
                <div className="tc-portal-row">
                  <div className="field">
                    <label className="field__label" htmlFor="tc-portal-id">
                      Your portal ID
                    </label>
                    <input
                      className="input"
                      id="tc-portal-id"
                      value={settings.publicKey}
                      readOnly
                    />
                  </div>
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline"
                    onClick={() => copy(settings.publicKey, 'Portal ID')}
                  >
                    Copy
                  </button>
                </div>
              </div>
            </div>
          </section>
        </TabPanel>

        <TabPanel id="tc-advanced" active={tab}>
          <section className="tc-panel" aria-label="Advanced tracking">
            <h2 className="tc-heading">Additional site domains</h2>
            <p className="tc-copy">
              We&apos;ll count the domains listed here as part of your site. This will allow us to
              handle cross-domain traffic properly if you have multiple domains.
            </p>

            <SettingsForm onSave={saveAdvanced}>
              <div className="tc-domain-section">
                <div className="tc-domain-list">
                  <div className="tc-domain-header">
                    <span>DOMAIN</span>
                    <span>TYPE</span>
                    <span />
                  </div>
                  {settings.domains.map((d) => (
                    <div key={d.id} className="tc-domain-row">
                      <span>{d.domain}</span>
                      <span className="tc-domain-type">
                        {d.type === 'hosted' ? 'Hosted' : 'External'}
                      </span>
                      <span>
                        {d.type === 'external' ? (
                          <button
                            type="button"
                            className="btn-crm btn-crm--outline btn-crm--xs"
                            onClick={() => void removeDomain(d.id)}
                          >
                            Remove
                          </button>
                        ) : null}
                      </span>
                    </div>
                  ))}
                </div>
                <button type="button" className="tc-add-domain" onClick={() => setDomainOpen(true)}>
                  <CrmIcon name="plus" className="iconSize-16" /> Add domain
                </button>
              </div>

              <div className="tc-settings-list">
                <SuToggle
                  name="tc_cross_domain"
                  title="Automatic cross-domain linking"
                  desc="Modify links on your pages to enable link-tracking between domains."
                  defaultChecked={settings.crossDomainLinking}
                />
                <SuToggle
                  name="tc_limit_domains"
                  title="Limit tracking to these domains"
                  desc="Only allow tracking on the domains listed here."
                  defaultChecked={settings.limitToListedDomains}
                />
                <SuToggle
                  name="tc_subdomains"
                  title="Limit cookies to subdomains"
                  desc="Limit the CRM tracking cookie to the subdomain placing it. As opposed to the entire root domain. This means something like blog.yourcompany.com would be the referrer in the sources tool, and not yourcompany.com."
                  defaultChecked={settings.limitCookiesToSubdomains}
                />
                <SuToggle
                  name="tc_secure"
                  title="Use secure cookies only"
                  desc="Only use CRM tracking cookies on pages with a secure connection. This will only work on pages using HTTPS."
                  defaultChecked={settings.secureCookiesOnly}
                />
                <SuToggle
                  name="tc_bot_filter"
                  title="Bot filtering"
                  desc="Filter activity from known internet bots on emails, forms, social posts, pages, CTAs, and workflow enrollments. Turning it on will ensure more reliable performance metrics."
                  defaultChecked={settings.botFiltering}
                />
                <SuToggle
                  name="tc_sms_filter"
                  title="SMS Bot filtering"
                  desc="Filter activity from known SMS bots. Turning it on will ensure more reliable SMS performance metrics."
                  defaultChecked={settings.smsBotFiltering}
                />
                <SuToggle
                  name="tc_intent"
                  title="Intent data access"
                  desc="Enable intent data access and data sharing for your account. You can review this knowledge base article to learn more about data access through the CRM."
                  defaultChecked={settings.intentDataAccess}
                />
              </div>

              <div className="tc-exclude-section">
                <h2 className="tc-heading">Exclude Traffic</h2>
                <p className="tc-copy">Your IP address</p>
                <p className="tc-ip-value">{settings.callerIp || 'Unavailable'}</p>
                <div className="field tc-exclude-field">
                  <label className="field__label" htmlFor="tc-exclude-ips">
                    IP Addresses to Exclude
                  </label>
                  <p className="field__help">
                    Use commas to separate different IP addresses. For example: 63.139.127.5,
                    63.139.127.23
                  </p>
                  <p className="field__help">
                    Use dashes to represent entire ranges of IP addresses. For example: 63.139.127.0
                    - 63.139.127.255
                  </p>
                  <textarea
                    className="input"
                    id="tc-exclude-ips"
                    name="exclude_ips"
                    rows={4}
                    defaultValue={settings.excludeIps}
                  />
                </div>
                <div className="field tc-exclude-field">
                  <label className="field__label" htmlFor="tc-exclude-referrers">
                    From these referrers:
                  </label>
                  <p className="field__help">
                    Use commas to separate different referrer domains or referrer IP addresses.
                  </p>
                  <textarea
                    className="input"
                    id="tc-exclude-referrers"
                    name="exclude_referrers"
                    rows={4}
                    defaultValue={settings.excludeReferrers}
                  />
                </div>
              </div>
            </SettingsForm>
          </section>
        </TabPanel>
      </div>

      <SetDialog
        id="dev-dialog"
        open={emailOpen}
        onClose={closeEmail}
        labelledBy="dev-title"
        className="tc-dialog"
      >
        <form noValidate data-tc-email-form onSubmit={(e) => void sendEmail(e)}>
          <DialogHead id="dev-title" title="Send tracking code" onClose={closeEmail} />
          <div className="set-modal__body tc-email-body">
            <div className={cn('field', emailInvalid && 'is-invalid')}>
              <label className="field__label" htmlFor="dev-email">
                Email address to send to
              </label>
              <input
                className="input"
                id="dev-email"
                name="email"
                type="email"
                required
                placeholder="email@example.com"
                value={devEmail}
                onChange={(e) => {
                  setDevEmail(e.target.value);
                  setEmailInvalid(false);
                }}
              />
              <p className="field__error">Enter a valid email address.</p>
            </div>
            <button
              className="tc-preview-toggle"
              type="button"
              aria-expanded={emailPreview}
              aria-controls="tc-email-preview"
              onClick={() => setEmailPreview((v) => !v)}
            >
              <span className="tc-preview-chevron" aria-hidden="true">
                <CrmIcon name="chevron-right" className="iconSize-14" />
              </span>
              <span>Preview email</span>
            </button>
            <div className="tc-email-preview" id="tc-email-preview" hidden={!emailPreview}>
              <div className="crm-d-flex crm-justify-content-center crm-mb-2 crm-pt-2">
                <BrandLogo variant="light" />
              </div>
              <div className="tc-email-content">
                <p>Hi there,</p>
                <p>
                  We&apos;re starting to use CRM software to manage our marketing analytics, and
                  I&apos;m hoping you can help with some of the technical setup steps necessary to
                  get us up and running.
                </p>
                <p>
                  Specifically, we&apos;ll need to insert some tracking code into every page of our
                  website, just before the &lt;/body&gt; tag. The code for that is right here:
                </p>
                <pre>{snippet}</pre>
                <p>
                  If you encounter any difficulties or have any questions at all, please call CRM
                  Support at 1-888-CRM.
                </p>
                <p>Please let me know when this is done so I can complete our CRM setup.</p>
                <p>Thank you,</p>
                <p>
                  <strong>{me.user.name || 'CRM User'}</strong>
                </p>
                <p>Some helpful links:</p>
                <ul>
                  <li>
                    What is CRM?{' '}
                    <a href="https://www.admedia.com" target="_blank" rel="noopener noreferrer">
                      http://www.admedia.com ↗
                    </a>
                  </li>
                  <li>
                    CRM Help:{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={() => toast('Help Center is coming soon.', 'info')}
                    >
                      Help Center ↗
                    </button>
                  </li>
                  <li>
                    CRM Tracking Code Tutorial:{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={() => toast('Tracking code tutorial is coming soon.', 'info')}
                    >
                      knowledge.admedia.com ↗
                    </button>
                  </li>
                  <li>
                    Analytics &amp; Tracking Settings:{' '}
                    <button
                      type="button"
                      className="link"
                      onClick={() => toast('Analytics and tracking help is coming soon.', 'info')}
                    >
                      Analytics and tracking ↗
                    </button>
                  </li>
                </ul>
              </div>
            </div>
          </div>
          <div className="set-modal__foot tc-email-foot">
            <button type="submit" className="btn-crm btn-crm--primary">
              Send
            </button>
          </div>
        </form>
      </SetDialog>

      <SetDialog
        id="tc-domain-dialog"
        open={domainOpen}
        onClose={() => setDomainOpen(false)}
        labelledBy="tc-domain-title"
        className="tc-dialog tc-domain-dialog"
      >
        <form noValidate onSubmit={(e) => void addDomain(e)}>
          <DialogHead
            id="tc-domain-title"
            title="Add an external domain"
            onClose={() => setDomainOpen(false)}
          />
          <div className="set-modal__body">
            <div className="field">
              <label className="field__label" htmlFor="tc-new-domain">
                Domain
              </label>
              <input
                className="input"
                id="tc-new-domain"
                type="text"
                placeholder="example.com"
                autoComplete="off"
                value={newDomain}
                onChange={(e) => setNewDomain(e.target.value)}
              />
            </div>
          </div>
          <div className="set-modal__foot">
            <button type="submit" className="btn-crm btn-crm--primary" disabled={!newDomain.trim()}>
              Add
            </button>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              onClick={() => setDomainOpen(false)}
            >
              Cancel
            </button>
          </div>
        </form>
      </SetDialog>
    </SettingsFormsProvider>
  );
}
