'use client';

import Link from 'next/link';
import { useEffect, useState, type ReactNode } from 'react';
import { getBusinessSettings } from '@/features/settings/api.client';
import type {
  SequenceSettings,
  SequenceSharedWith,
  SequenceVisibility,
} from '@/features/sequences/types';
import { SequenceSharingPickers } from './SequenceSharingPickers';
import { DEFAULT_REMINDER_TIME, SEND_WINDOW_ERROR } from './shared';
import { cn } from '@/lib/utils/cn';

type Weekday = SequenceSettings['sendWindow']['days'][number];

const ALL_DAYS: Weekday[] = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
const BUSINESS_DAYS: Weekday[] = ['mon', 'tue', 'wed', 'thu', 'fri'];
const DAY_LABEL: Record<Weekday, string> = {
  mon: 'Mon',
  tue: 'Tue',
  wed: 'Wed',
  thu: 'Thu',
  fri: 'Fri',
  sat: 'Sat',
  sun: 'Sun',
};

const isBusinessDaysOnly = (days: Weekday[]) =>
  days.length === BUSINESS_DAYS.length && BUSINESS_DAYS.every((d) => days.includes(d));

/** The design's ON ✓ / OFF switch. */
function OnOff({
  on,
  label,
  disabled,
  onChange,
}: {
  on: boolean;
  label: string;
  disabled?: boolean;
  onChange: (on: boolean) => void;
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={on}
      aria-label={label}
      className={cn('seqst-switch', on && 'is-on')}
      disabled={disabled}
      onClick={() => onChange(!on)}
    >
      <span>{on ? 'ON' : ''}</span>
      <span>{on ? '✓' : 'OFF'}</span>
    </button>
  );
}

function Row({
  title,
  text,
  control,
  children,
}: {
  title: string;
  text?: string;
  control?: ReactNode;
  children?: ReactNode;
}) {
  return (
    <div className="seqst-row">
      <div className="seqst-row__head">
        <div>
          <h4>{title}</h4>
          {text ? <p>{text}</p> : null}
        </div>
        {control}
      </div>
      {children}
    </div>
  );
}

function ClockIcon() {
  return (
    <svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" aria-hidden>
      <circle cx="8" cy="8" r="6.2" strokeWidth="1.4" />
      <path d="M8 4.8V8l2.2 1.4" strokeWidth="1.4" strokeLinecap="round" />
    </svg>
  );
}

/**
 * Settings tab of the sequence editor (design: Follow-up emails, Tasks). Edits the editor's
 * settings; they are saved with the header's Save.
 */
export function SequenceSettingsTab({
  settings,
  canEdit,
  onChange,
  visibility,
  onVisibilityChange,
  sharedWith,
  onSharedWithChange,
}: {
  settings: SequenceSettings;
  canEdit: boolean;
  onChange: (settings: SequenceSettings) => void;
  visibility: SequenceVisibility;
  onVisibilityChange: (visibility: SequenceVisibility) => void;
  sharedWith: SequenceSharedWith;
  onSharedWithChange: (next: SequenceSharedWith) => void;
}) {
  const win = settings.sendWindow;
  const setWindow = (patch: Partial<SequenceSettings['sendWindow']>) =>
    onChange({ ...settings, sendWindow: { ...win, ...patch } });
  const businessOnly = isBusinessDaysOnly(win.days);
  const toggleDay = (day: Weekday, on: boolean) =>
    setWindow({
      days: ALL_DAYS.filter((d) => (d === day ? on : win.days.includes(d))),
    });
  const badWindow = win.startTime >= win.endTime;
  /**
   * The unsubscribe footer shows the company's postal address, which anti-spam law asks for;
   * say so when Account Defaults has none (QA 16 Oct #141). Null until known.
   */
  const [hasAddress, setHasAddress] = useState<boolean | null>(null);
  /**
   * #48 / #30: sequence emails are tracked (opens and clicks) only while the account's tracking
   * is on with a tracking domain. Null until known.
   */
  const [account, setAccount] = useState<{ tracked: boolean } | null>(null);
  useEffect(() => {
    let alive = true;
    getBusinessSettings().then(
      (b) => {
        if (!alive) return;
        setHasAddress(Boolean(b.addressLine1?.trim() || b.city?.trim()));
        setAccount({ tracked: b.trackingEnabled && Boolean(b.trackingDomain) });
      },
      () => {},
    );
    return () => {
      alive = false;
    };
  }, []);

  return (
    <div className="seqst">
      <h3 className="seqst__title">Follow-up emails</h3>
      <section className="seqst-card">
        <Row
          title="Execute steps on business days only"
          text="If enabled, emails will be sent and tasks will be created on business days only. A wait set in business days always skips weekends and holidays; set it in days to count every day."
          control={
            <OnOff
              on={businessOnly}
              label="Execute steps on business days only"
              disabled={!canEdit}
              onChange={(on) => setWindow({ days: on ? BUSINESS_DAYS : ALL_DAYS })}
            />
          }
        >
          {businessOnly ? null : (
            <div className="seqst-days" role="group" aria-label="Days steps can run">
              {ALL_DAYS.map((day) => (
                <label key={day} className={cn('seqst-day', win.days.includes(day) && 'is-on')}>
                  <input
                    type="checkbox"
                    checked={win.days.includes(day)}
                    disabled={!canEdit || (win.days.length === 1 && win.days.includes(day))}
                    onChange={(e) => toggleDay(day, e.target.checked)}
                  />
                  {DAY_LABEL[day]}
                </label>
              ))}
            </div>
          )}
        </Row>

        <Row
          title="Automated email send window"
          text="When enrolling a contact, you can customize the specific send time & time zone."
        >
          <p className="seqst-label">Send window</p>
          <div className="seqst-window">
            <label className="seqst-time">
              <ClockIcon />
              <input
                type="time"
                aria-label="Send window start"
                step={1800}
                value={win.startTime}
                disabled={!canEdit}
                onChange={(e) => setWindow({ startTime: e.target.value })}
              />
            </label>
            <span aria-hidden>→</span>
            <label className="seqst-time">
              <ClockIcon />
              <input
                type="time"
                aria-label="Send window end"
                step={1800}
                min={win.startTime}
                value={win.endTime}
                disabled={!canEdit}
                onChange={(e) => setWindow({ endTime: e.target.value })}
              />
            </label>
          </div>
          {badWindow ? (
            // Sequences QA steps BUG-05: the design's message, also on Save and from the API.
            <p className="seqst-hint crm-text-danger" role="alert">
              {SEND_WINDOW_ERROR}
            </p>
          ) : (
            <p className="seqst-hint">Automated emails go out during this window only.</p>
          )}
          <div className="seqst-fields">
            <label className="seqst-field">
              <span>Time zone</span>
              <select
                className="input"
                value={win.timezone}
                disabled={!canEdit}
                onChange={(e) => setWindow({ timezone: e.target.value as 'contact' | 'owner' })}
              >
                <option value="owner">Sender&apos;s time zone</option>
                <option value="contact">Contact&apos;s time zone</option>
              </select>
            </label>
          </div>
          {/* Sequences SQ-5 (Q-05): HubSpot's sequence Settings has no email-limit text; the
              sender's limits and usage are on Sequences › Scheduled. */}
        </Row>

        <Row
          title="Skip holidays"
          text="No steps run on your company's holidays; they wait for the next allowed day."
          control={
            <OnOff
              on={win.skipHolidays}
              label="Skip holidays"
              disabled={!canEdit}
              onChange={(on) => setWindow({ skipHolidays: on })}
            />
          }
        >
          <p className="seqst-hint">
            US federal holidays are always included. Add your own in{' '}
            <Link href="/settings/account-defaults#holidays">
              Settings › Account Defaults › Company Holidays
            </Link>
            .
          </p>
        </Row>

        <Row
          title="Include an unsubscribe link"
          text="Automated emails end with a link the contact can use to stop getting emails."
          control={
            <OnOff
              on={settings.unsubscribeLink}
              label="Include an unsubscribe link"
              disabled={!canEdit}
              onChange={(on) => onChange({ ...settings, unsubscribeLink: on })}
            />
          }
        >
          {settings.unsubscribeLink && hasAddress === false ? (
            <p className="seqst-hint crm-text-danger">
              The footer has no postal address, which anti-spam laws require. Add your company
              address in <Link href="/settings/account-defaults">Settings › Account Defaults</Link>.
            </p>
          ) : null}
        </Row>

        {/* #48 / #30: as HubSpot, sequence emails are tracked by default; here that is the
            account's open and click tracking (HUB-170). */}
        <Row
          title="Open and click tracking"
          text="Automated emails are tracked when open and click tracking is on for your account."
        >
          {account === null ? null : account.tracked ? (
            <p className="seqst-hint">Tracking is on: opens and clicks are recorded.</p>
          ) : (
            <p className="seqst-hint crm-text-danger">
              Tracking is off for your account, so opens and clicks of these emails are not
              recorded. Turn it on in{' '}
              <Link href="/settings/email-provider">Settings › Email Service Provider</Link>.
            </p>
          )}
        </Row>
      </section>

      <h3 className="seqst__title">Tasks</h3>
      <section className="seqst-card">
        <Row
          title="Assign tasks to"
          text="Who gets the tasks this sequence creates. The contact owner must be an active user; otherwise the sender gets them."
          control={
            <select
              className="input seqst-select"
              aria-label="Assign tasks to"
              value={settings.taskAssignment}
              disabled={!canEdit}
              onChange={(e) =>
                onChange({
                  ...settings,
                  taskAssignment: e.target.value as 'sender' | 'contact_owner',
                })
              }
            >
              <option value="sender">The sender</option>
              <option value="contact_owner">The contact owner</option>
            </select>
          }
        />
        {/* Sequences QA steps BUG-07: HubSpot's and the design's text, and the Reminder time
            (the task's due day, at that time in the zone of the person who gets the task). */}
        <Row
          title="Email reminders"
          text="Receive an email reminder at the time you choose."
          control={
            <OnOff
              on={Boolean(settings.taskReminders)}
              label="Email reminders"
              disabled={!canEdit}
              onChange={(on) => onChange({ ...settings, taskReminders: on })}
            />
          }
        >
          {settings.taskReminders ? (
            <div className="seqst-fields">
              <label className="seqst-field">
                <span>Reminder time</span>
                <span className="seqst-time">
                  <ClockIcon />
                  <input
                    type="time"
                    aria-label="Reminder time"
                    value={settings.reminderTime ?? DEFAULT_REMINDER_TIME}
                    disabled={!canEdit}
                    required
                    onChange={(e) =>
                      onChange({
                        ...settings,
                        reminderTime: e.target.value || DEFAULT_REMINDER_TIME,
                      })
                    }
                  />
                </span>
              </label>
            </div>
          ) : null}
        </Row>
      </section>

      <h3 className="seqst__title">Sharing</h3>
      <section className="seqst-card">
        <Row
          title="Who can use this sequence"
          text="Shared sequences can be used by everyone in the team, and by workflows and automations."
          control={
            <select
              className="input seqst-select"
              aria-label="Who can use this sequence"
              value={visibility}
              disabled={!canEdit}
              onChange={(e) => onVisibilityChange(e.target.value as SequenceVisibility)}
            >
              {/* Sequences QA manage BUG-05: the Manage sharing drawer's names (design, HubSpot). */}
              <option value="personal">Private</option>
              <option value="shared">Everyone</option>
              <option value="specific">Specific users or teams</option>
            </select>
          }
        />
        {visibility === 'specific' ? (
          <div className="seqst-row seqst-row--block">
            <SequenceSharingPickers
              idPrefix="seqSettings"
              sharedWith={sharedWith}
              onChange={onSharedWithChange}
              disabled={!canEdit}
            />
          </div>
        ) : null}
      </section>
    </div>
  );
}
