'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { getExtensionSettings, updateExtensionSettings } from '@/features/extension/api.client';
import type { MyCalendar } from '@/features/meetings/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { needsReconnect } from '@/lib/utils/connection';
import type { Profile } from '../types';
import { DialogHead, SetDialog, SettingsForm, type SettingsSaveHandler } from './settings-ui';

type CalendarProvider = 'google' | 'outlook' | 'exchange';

const MEETING_LENGTHS = [15, 30, 45, 60];
const MEETING_BUFFERS = [0, 5, 10, 15, 30];

const CHECKLIST: { text: string; note?: string }[] = [
  { text: 'Send meetings directly from CRM' },
  { text: 'Log outgoing meetings automatically' },
  {
    text: 'Sync your calendar so contacts can schedule time with you',
    note: 'Requires Calendar Sync',
  },
  {
    text: 'See your CRM tasks in your calendar',
    note: 'Requires an additional step with task sync. Only available on Sales Starter and up plans.',
  },
];

type Props = {
  profile: Profile;
  calendar: MyCalendar | null;
  onSave: SettingsSaveHandler;
  onConnectGoogle: () => void | Promise<void>;
  onDisconnect: () => void;
  onReconnect: () => void | Promise<void>;
};

/**
 * Settings › General › Calendar (design: settings-profile.php #tab-calendar / Untitled-2).
 * Google Calendar uses real /calendars APIs. Outlook and Exchange are UI-only until backends exist.
 */
export function GeneralCalendarTab({
  profile,
  calendar,
  onSave,
  onConnectGoogle,
  onDisconnect,
  onReconnect,
}: Props) {
  const toast = useToast();
  const connected = calendar?.connected === true;
  const [bannerDismissed, setBannerDismissed] = useState(false);
  const [providerOpen, setProviderOpen] = useState(false);
  const [provider, setProvider] = useState<CalendarProvider | null>(null);
  const [consent, setConsent] = useState<CalendarProvider | null>(null);

  const closeProvider = () => {
    setProviderOpen(false);
    setProvider(null);
  };

  const openConsent = () => {
    if (!provider) return;
    setProviderOpen(false);
    setConsent(provider);
  };

  const closeConsent = () => setConsent(null);

  const acceptConsent = () => {
    if (consent === 'google') {
      closeConsent();
      void onConnectGoogle();
      return;
    }
    const label =
      consent === 'outlook'
        ? 'Outlook calendar'
        : consent === 'exchange'
          ? 'Exchange calendar'
          : '';
    closeConsent();
    if (label) toast(`${label} connection is coming soon`, 'info');
  };

  return (
    <>
      <p className="set-preferences-note">These preferences only apply to you.</p>

      {!connected && !bannerDismissed ? (
        <div className="set-calendar-disconnected" role="status">
          <strong>Your calendar is disconnected.</strong>
          <span>Connect it to access all the features in the meetings tool.</span>
          <button
            type="button"
            className="set-calendar-disconnected__close"
            aria-label="Dismiss notice"
            onClick={() => setBannerDismissed(true)}
          >
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </div>
      ) : null}

      {!connected ? (
        <section className="set-calendar-section set-calendar-intro">
          <div className="set-calendar-copy">
            <h2 className="set-card__title">Calendar</h2>
            <p className="set-calendar-description">
              Connect your calendar to use CRM Meetings and calendar sync.
            </p>
            <ul className="set-calendar-checklist">
              {CHECKLIST.map((item) => (
                <li key={item.text}>
                  <svg
                    className="set-calendar-tick"
                    viewBox="0 0 16 16"
                    aria-hidden
                    focusable="false"
                  >
                    <path
                      d="m3.25 8.25 3.1 3.1 6.4-6.7"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="1.6"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                  <span>
                    {item.text}
                    {item.note ? <small>{item.note}</small> : null}
                  </span>
                </li>
              ))}
            </ul>
            <button
              type="button"
              className="btn-crm btn-crm--primary set-calendar-connect"
              disabled={calendar === null}
              onClick={() => {
                setProvider(null);
                setProviderOpen(true);
              }}
            >
              Connect your calendar
            </button>
          </div>
          <div className="set-calendar-art" aria-hidden="true">
            <img src="/crm/assets/img/crm-calendar.png" width={150} alt="" />
          </div>
        </section>
      ) : (
        <div className="card set-card crm-mb-4">
          <div className="connect-row">
            <span className="connect-row__icon">
              <CrmIcon name="calendar" />
            </span>
            <div className="connect-row__body">
              <p className="crm-fw-semibold">Google Calendar · {calendar.emailAddress}</p>
              <p className="field__help">{syncedText(calendar.lastSyncedAt, calendar.status)}</p>
            </div>
            <span
              className={cn(
                'badge',
                needsReconnect(calendar) ? 'badge--warning' : 'badge--success',
              )}
            >
              {statusText(calendar.status)}
            </span>
            {needsReconnect(calendar) ? (
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--sm"
                onClick={() => void onReconnect()}
              >
                Reconnect
              </button>
            ) : null}
            <button
              type="button"
              className="btn-crm btn-crm--outline btn-crm--sm su-danger"
              onClick={onDisconnect}
            >
              Disconnect
            </button>
          </div>
        </div>
      )}

      <SettingsForm className="set-calendar-form" onSave={onSave}>
        <section className="set-calendar-section">
          <h2 className="set-card__title">Calendar sync</h2>
          <p className="set-calendar-description">
            Keep CRM meetings in step with the calendar you connected.
          </p>
          <label className="check set-calendar-check">
            <input
              type="checkbox"
              name="calendar_sync"
              defaultChecked={profile.preferences.calendarSync !== false}
            />
            <span className="check__box" aria-hidden />
            <span>
              <strong>Sync calendar events</strong>
              <small>Log meetings from your connected calendar into CRM.</small>
            </span>
          </label>
        </section>
        <CalendarNeverLog />
        <section className="set-calendar-section">
          <h2 className="set-card__title">Meeting defaults</h2>
          <p className="set-calendar-description">Customize default meeting length and buffers.</p>
          <div className="set-grid">
            <div className="field">
              <label className="field__label" htmlFor="c-len">
                Default meeting length
              </label>
              <select
                className="input"
                id="c-len"
                name="meeting_length"
                defaultValue={String(profile.preferences.meetingDefaultMinutes)}
              >
                {MEETING_LENGTHS.map((m) => (
                  <option key={m} value={m}>
                    {m} minutes
                  </option>
                ))}
              </select>
            </div>
            <div className="field">
              <label className="field__label" htmlFor="c-buffer">
                Buffer between meetings
              </label>
              <select
                className="input"
                id="c-buffer"
                name="buffer"
                defaultValue={String(profile.preferences.meetingBufferMinutes)}
              >
                {MEETING_BUFFERS.map((m) => (
                  <option key={m} value={m}>
                    {m === 0 ? 'None' : `${m} minutes`}
                  </option>
                ))}
              </select>
            </div>
          </div>
          <div className="field set-calendar-field">
            <label className="field__label" htmlFor="availability-calendar">
              Availability calendars
            </label>
            <p className="field__help">
              Which connected calendar meetings can use when someone books time with you.
            </p>
            <select
              className="input"
              id="availability-calendar"
              name="availability_calendar"
              defaultValue={profile.preferences.availabilityCalendar ?? 'primary'}
            >
              <option value="primary">Primary calendar only</option>
              <option value="all">All connected calendars</option>
            </select>
          </div>
        </section>
        <section className="set-calendar-section">
          <h2 className="set-card__title">Out-of-office calendar sync</h2>
          <p className="set-calendar-description">
            Block booking time when your calendar says you are out of office.
          </p>
          <label className="check set-calendar-check">
            <input
              type="checkbox"
              name="ooo_sync"
              defaultChecked={profile.preferences.outOfOfficeSync !== false}
            />
            <span className="check__box" aria-hidden />
            <span>
              <strong>Sync out-of-office events</strong>
              <small>Those hours are unavailable on your meeting links.</small>
            </span>
          </label>
        </section>
        <section className="set-calendar-section">
          <h2 className="set-card__title">Meetings</h2>
          <p className="set-calendar-description">Customize your CRM Meetings URL.</p>
          <div className="field set-calendar-field">
            <label className="field__label" htmlFor="calendar-meetings-url">
              Meetings URL
            </label>
            <p className="field__help">
              Used on new meeting links. Links you already sent keep their old address.
            </p>
            <div className="set-calendar-url">
              <span>meetings.crm/</span>
              <input
                className="input"
                id="calendar-meetings-url"
                name="meetings_url"
                defaultValue={profile.preferences.meetingsSlug ?? ''}
                maxLength={80}
                placeholder="your-name"
                autoComplete="off"
              />
            </div>
          </div>
        </section>
      </SettingsForm>

      <SetDialog
        open={providerOpen}
        onClose={closeProvider}
        labelledBy="calendar-provider-title"
        className="set-modal set-calendar-provider-dialog"
      >
        <DialogHead
          id="calendar-provider-title"
          title="Connect your calendar"
          onClose={closeProvider}
        />
        <div className="set-calendar-provider-grid">
          <button
            type="button"
            className={cn('set-calendar-provider', provider === 'google' && 'is-selected')}
            aria-pressed={provider === 'google'}
            onClick={() => setProvider('google')}
          >
            <img
              className="set-calendar-provider__logo"
              src="/crm/assets/img/gmail.svg"
              width={50}
              height={50}
              alt=""
            />
            <span>Google / Gmail</span>
          </button>
          <button
            type="button"
            className={cn('set-calendar-provider', provider === 'outlook' && 'is-selected')}
            aria-pressed={provider === 'outlook'}
            onClick={() => setProvider('outlook')}
          >
            <OutlookLogo />
            <span>Microsoft Outlook</span>
          </button>
          <button
            type="button"
            className={cn('set-calendar-provider', provider === 'exchange' && 'is-selected')}
            aria-pressed={provider === 'exchange'}
            onClick={() => setProvider('exchange')}
          >
            <ExchangeLogo />
            <span>Microsoft Exchange</span>
          </button>
        </div>
        <div className="set-calendar-provider-footer">
          <button
            type="button"
            className="btn-crm btn-crm--primary"
            disabled={!provider}
            aria-disabled={!provider}
            onClick={openConsent}
          >
            Connect your calendar
          </button>
        </div>
      </SetDialog>

      <SetDialog
        open={consent === 'google'}
        onClose={closeConsent}
        labelledBy="calendar-google-title"
        className="set-modal set-calendar-consent-dialog"
      >
        <DialogHead
          id="calendar-google-title"
          title="Connect your Google account"
          onClose={closeConsent}
        />
        <div className="set-calendar-consent-body">
          <p>
            When you integrate your Google account with the CRM platform, you can connect a number
            of Google services to your CRM account. By doing so, CRM will be able to access data and
            information from your Google account. Those services and types of data are outlined
            below:
          </p>
          <ul>
            <li>
              <strong>Google Calendar:</strong> You can use the Meetings tool to create new or
              modify existing meetings on your primary Google Calendar.
            </li>
          </ul>
          <p>
            We&apos;ll only use your Google data to power different parts of our product that
            connect with the Google Workspace tools you use every day. It&apos;s your data. We just
            want to help you grow better.
          </p>
          <p>
            You can revoke CRM&apos;s access from within your Google account by following the
            instructions listed{' '}
            <a
              href="https://myaccount.google.com/permissions"
              className="link"
              target="_blank"
              rel="noreferrer"
            >
              here
            </a>
            .
          </p>
          <p>
            For more information on the Google integration and the types of data we can access,
            please see our{' '}
            <Link href="/privacy" className="link">
              Privacy Policy
            </Link>
            .
          </p>
        </div>
        <div className="set-calendar-consent-footer">
          <button type="button" className="btn-crm btn-crm--primary" onClick={acceptConsent}>
            Accept and connect to Google
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={closeConsent}>
            Cancel
          </button>
        </div>
      </SetDialog>

      <SetDialog
        open={consent === 'outlook'}
        onClose={closeConsent}
        labelledBy="calendar-outlook-title"
        className="set-modal set-calendar-consent-dialog"
      >
        <DialogHead
          id="calendar-outlook-title"
          title="Connect Your Outlook 365 Inbox"
          onClose={closeConsent}
        />
        <div className="set-calendar-consent-body set-calendar-consent-body--scroll">
          <p>
            Connect your Outlook 365 account to sync your calendar with CRM. Your team can work
            together, and emails that you send from CRM will also appear in your Outlook sent
            folder, so there&apos;ll be no confusion about which emails live where.
          </p>
          <p>
            This means that your CRM will have access to some information about your emails, like
            the email address you&apos;re sending them from, the email addresses of your recipients,
            what&apos;s in the subject line, and what&apos;s in the body of the email. We&apos;ll
            only use that access to power your CRM Outlook integration and make life easier for you,
            never for any nefarious purposes of our own. <strong>It&apos;s your data.</strong> We
            just want to help you use it better. You&apos;ll always be able to delete specific email
            records from your CRM with just a couple of clicks. CRM will also have access to view
            and create calendar events so we can ensure your CRM and calendar are perfectly in sync.
          </p>
          <p>
            <strong>
              You&apos;ll be able to make more sweeping changes to how your integration works
            </strong>{' '}
            (for instance, removing the integration or adding another email account) just by
            adjusting your settings. It&apos;s all up to you.
          </p>
        </div>
        <div className="set-calendar-consent-footer">
          <button type="button" className="btn-crm btn-crm--primary" onClick={acceptConsent}>
            Accept and connect to Outlook 365
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={closeConsent}>
            Cancel
          </button>
        </div>
      </SetDialog>

      <SetDialog
        open={consent === 'exchange'}
        onClose={closeConsent}
        labelledBy="calendar-exchange-title"
        className="set-modal set-calendar-consent-dialog"
      >
        <DialogHead
          id="calendar-exchange-title"
          title="Connect your Microsoft Exchange account"
          onClose={closeConsent}
        />
        <div className="set-calendar-consent-body">
          <p>
            Connect your Microsoft Exchange account to sync your calendar with CRM. CRM will request
            access to view and create calendar events so your meetings stay in sync.
          </p>
          <p>
            You can manage or revoke this access from your Microsoft account settings at any time.
          </p>
        </div>
        <div className="set-calendar-consent-footer">
          <button type="button" className="btn-crm btn-crm--primary" onClick={acceptConsent}>
            Accept and connect to Exchange
          </button>
          <button type="button" className="btn-crm btn-crm--outline" onClick={closeConsent}>
            Cancel
          </button>
        </div>
      </SetDialog>
    </>
  );
}

function statusText(s: MyCalendar['status']) {
  return s === 'needs_reauth'
    ? 'Needs reconnecting'
    : s === 'syncing'
      ? 'Syncing'
      : s === 'error'
        ? 'Sync error'
        : 'Connected';
}

function syncedText(iso: string | null, status?: string | null) {
  return iso
    ? `last synced ${new Date(iso).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}`
    : status === 'syncing'
      ? 'connected, first sync in progress'
      : 'not synced yet';
}

function OutlookLogo() {
  return (
    <svg className="set-calendar-provider__logo" viewBox="0 0 48 48" aria-hidden>
      <defs>
        <linearGradient id="cal-outlook-a" x1="0" y1="0" x2="1" y2="1">
          <stop stopColor="#36C5F0" />
          <stop offset="1" stopColor="#2457D6" />
        </linearGradient>
      </defs>
      <rect x="17" y="5" width="27" height="38" rx="6" fill="url(#cal-outlook-a)" />
      <path fill="#0A3C91" d="M22 13h17v22H22z" />
      <path fill="#fff" d="M25 18h6c5 0 7 3 7 6s-2 6-7 6h-6zm4 3v6h2c2 0 3-1 3-3s-1-3-3-3z" />
      <rect x="3" y="11" width="25" height="27" rx="4" fill="#0875D1" />
      <path fill="#fff" d="M8 17h7c5 0 8 3 8 8s-3 8-8 8H8zm5 4v8h2c2 0 3-1 3-4s-1-4-3-4z" />
    </svg>
  );
}

function ExchangeLogo() {
  return (
    <svg className="set-calendar-provider__logo" viewBox="0 0 48 48" aria-hidden>
      <rect x="7" y="8" width="31" height="32" rx="5" fill="#149BDD" />
      <path fill="#0874C9" d="M29 8h9a5 5 0 0 1 5 5v22a5 5 0 0 1-5 5h-9z" />
      <rect x="3" y="15" width="23" height="19" rx="2" fill="#0078D4" />
      <path fill="#fff" d="M9 19h11v3h-4v9h-3v-9H9z" />
    </svg>
  );
}

/** Never Log on the Calendar tab uses the same list as Email (#503). */
function CalendarNeverLog() {
  const toast = useToast();
  const [emails, setEmails] = useState<string[]>([]);
  const [domains, setDomains] = useState<string[]>([]);
  const [draft, setDraft] = useState('');
  const [ready, setReady] = useState(false);

  useEffect(() => {
    getExtensionSettings().then(
      (ext) => {
        setEmails(ext.user.neverLogEmails);
        setDomains(ext.user.neverLogDomains);
        setReady(true);
      },
      () => setReady(true),
    );
  }, []);

  const save = async (nextEmails: string[], nextDomains: string[]) => {
    try {
      const ext = await updateExtensionSettings({
        neverLogEmails: nextEmails,
        neverLogDomains: nextDomains,
      });
      setEmails(ext.user.neverLogEmails);
      setDomains(ext.user.neverLogDomains);
      return true;
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    }
  };

  const add = async () => {
    const value = draft.trim().toLowerCase().replace(/^\*@/, '');
    if (!value) return;
    const email = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i.test(value);
    const domain = /^[a-z0-9.-]+\.[a-z]{2,}$/i.test(value);
    if (!email && !domain) {
      toast('Enter an email address or a domain', 'danger');
      return;
    }
    const nextEmails = email ? [...new Set([...emails, value])] : emails;
    const nextDomains = email ? domains : [...new Set([...domains, value])];
    if (await save(nextEmails, nextDomains)) setDraft('');
  };

  const items = [
    ...emails.map((value) => ({ value, kind: 'email' as const })),
    ...domains.map((value) => ({ value: `*@${value}`, kind: 'domain' as const })),
  ];

  return (
    <section className="set-calendar-section">
      <h2 className="set-card__title">Never Log</h2>
      <p className="set-calendar-description">
        Emails and meetings with these addresses or domains are not logged to CRM. Account admins
        can also manage this list in email logging settings.
      </p>
      <div className="set-calendar-exclusions">
        {items.map((item) => (
          <span key={`${item.kind}:${item.value}`} className="set-calendar-exclusion">
            {item.value}
            <button
              type="button"
              aria-label={`Remove ${item.value}`}
              onClick={() =>
                void save(
                  item.kind === 'email' ? emails.filter((row) => row !== item.value) : emails,
                  item.kind === 'domain'
                    ? domains.filter((row) => `*@${row}` !== item.value)
                    : domains,
                )
              }
            >
              ×
            </button>
          </span>
        ))}
      </div>
      <div className="set-calendar-url">
        <input
          className="input"
          value={draft}
          placeholder="name@example.com or example.com"
          aria-label="Email or domain to never log"
          disabled={!ready}
          onChange={(event) => setDraft(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === 'Enter') {
              event.preventDefault();
              void add();
            }
          }}
        />
        <button
          type="button"
          className="btn-crm btn-crm--outline btn-crm--sm"
          disabled={!ready}
          onClick={() => void add()}
        >
          Add
        </button>
      </div>
    </section>
  );
}
