'use client';

import { cn } from '@/lib/utils/cn';
import { useEffect, useMemo, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { actionErrorText } from '@/features/contacts/ui/actions/shared';
import type { Owner } from '@/features/owners/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { getSlackConnection } from '@/features/workflows/api.client';
import {
  createDashboardShare,
  listSlackChannels,
  listSlackUsers,
  type SlackTarget,
} from '../api.client';
import type { CreateDashboardShareBody, Dashboard, DashboardShareFrequency } from '../types';
import { isEmail, splitEmails, timeLabel, zoneLabel } from './model';
import { useEscape } from './useDropdown';

/** The design's "Time of day" choices. */
const TIMES = ['06:00', '07:00', '08:00', '09:00', '10:00', '12:00', '14:00', '17:00', '20:00'];
const EVERY: Record<DashboardShareFrequency, string> = {
  daily: 'every day',
  weekly: 'every week',
  monthly: 'every month',
};

type Method = 'email' | 'slack';

/**
 * QA #571 "Share › Email dashboard": the design's Share via drawer (`#shareViaDrawer`). Step 1
 * picks Email or Slack (Slack only when the business connected it); step 2 sends now or sets up
 * a recurring send at a time of day in the user's time zone.
 */
export function ShareDrawer({
  open,
  dashboard,
  owners,
  onClose,
}: {
  open: boolean;
  dashboard: Dashboard;
  owners: Owner[];
  onClose: () => void;
}) {
  const toast = useToast();
  const { timeZone } = useUserPrefs();
  const [step, setStep] = useState<1 | 2>(1);
  const [method, setMethod] = useState<Method>('email');
  const [slackConnected, setSlackConnected] = useState<boolean | null>(null);
  const [recurring, setRecurring] = useState(false);
  const [nickname, setNickname] = useState('');
  const [recipients, setRecipients] = useState<string[]>([]);
  const [typed, setTyped] = useState('');
  const [attachment, setAttachment] = useState<'none' | 'csv'>('none');
  const [others, setOthers] = useState('');
  const [subject, setSubject] = useState(dashboard.name);
  const [message, setMessage] = useState('');
  const [frequency, setFrequency] = useState<DashboardShareFrequency>('daily');
  const [time, setTime] = useState('08:00');
  const [destination, setDestination] = useState<'channel' | 'user'>('channel');
  const [channels, setChannels] = useState<SlackTarget[]>([]);
  const [slackUsers, setSlackUsers] = useState<SlackTarget[]>([]);
  const [targetId, setTargetId] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    if (!open) return;
    setStep(1);
    setMethod('email');
    setRecurring(false);
    setNickname('');
    setRecipients([]);
    setTyped('');
    setAttachment('none');
    setOthers('');
    setSubject(dashboard.name);
    setMessage('');
    setFrequency('daily');
    setTime('08:00');
    setDestination('channel');
    setTargetId('');
    setError(null);
    let alive = true;
    getSlackConnection().then(
      (c) => alive && setSlackConnected(c.connected),
      () => alive && setSlackConnected(false),
    );
    return () => {
      alive = false;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  useEffect(() => {
    if (!open || step !== 2 || method !== 'slack') return;
    let alive = true;
    Promise.all([listSlackChannels(), listSlackUsers()]).then(
      ([c, u]) => {
        if (!alive) return;
        setChannels(c);
        setSlackUsers(u);
      },
      (err: unknown) => alive && setError(actionErrorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [open, step, method]);

  useEscape(open, onClose);

  const members = useMemo(() => owners.filter((o) => o.active), [owners]);
  const memberByEmail = useMemo(
    () => new Map(members.map((m) => [m.email.toLowerCase(), m])),
    [members],
  );
  const zone = zoneLabel(timeZone);

  const addRecipient = () => {
    const value = typed.trim().replace(/,/g, '');
    if (!value) return;
    const lower = value.toLowerCase();
    const member =
      memberByEmail.get(lower) ?? members.find((m) => m.name.toLowerCase() === lower) ?? null;
    if (!member) {
      setError(
        isEmail(value)
          ? `${value} is not a user of this business. Add other people under Other recipients.`
          : 'Type the email of a user of this business and press Enter.',
      );
      return;
    }
    if (!recipients.includes(member.email.toLowerCase())) {
      setRecipients((r) => [...r, member.email.toLowerCase()]);
    }
    setTyped('');
    setError(null);
  };

  const submit = async () => {
    if (step === 1) {
      setStep(2);
      setError(null);
      return;
    }
    if (busy) return;
    if (recurring && !nickname.trim()) {
      setError('Enter a nickname for the recurring share.');
      return;
    }
    const schedule = recurring ? { frequency, timeOfDay: time, timeZone } : null;
    let body: CreateDashboardShareBody;
    if (method === 'email') {
      if (recipients.length === 0) {
        setError('Add at least one internal recipient.');
        return;
      }
      const { emails, bad } = splitEmails(others);
      if (bad.length) {
        setError(`Not an email address: ${bad.join(', ')}`);
        return;
      }
      body = {
        channel: 'email',
        recipients,
        otherRecipients: emails,
        attachment,
        ...(subject.trim() && { subject: subject.trim() }),
        ...(message.trim() && { message: message.trim() }),
        ...(schedule && { schedule, nickname: nickname.trim() }),
      };
    } else {
      if (!targetId) {
        setError(destination === 'channel' ? 'Select a channel.' : 'Select a user.');
        return;
      }
      const list = destination === 'channel' ? channels : slackUsers;
      body = {
        channel: 'slack',
        destination,
        targetId,
        targetName: list.find((t) => t.id === targetId)?.name,
        ...(message.trim() && { message: message.trim() }),
        ...(schedule && { schedule, nickname: nickname.trim() }),
      };
    }
    setBusy(true);
    try {
      await createDashboardShare(dashboard.id, body);
      toast(
        recurring
          ? `Scheduled: ${EVERY[frequency]} at ${timeLabel(time)} ${zone}.`
          : method === 'email'
            ? 'Dashboard email is on its way.'
            : 'Dashboard is on its way to Slack.',
      );
      onClose();
    } catch (err) {
      setError(actionErrorText(err));
    } finally {
      setBusy(false);
    }
  };

  const submitLabel =
    step === 1
      ? 'Next'
      : recurring
        ? method === 'email'
          ? 'Schedule email'
          : 'Schedule message'
        : 'Send now';

  const scheduleFields = (kind: 'email' | 'message') =>
    recurring ? (
      <>
        <div className="field">
          <label className="field__label" htmlFor={`share-${kind}-schedule`}>
            Schedule
          </label>
          <select
            id={`share-${kind}-schedule`}
            className="input crm-w-100"
            value={frequency}
            onChange={(e) => setFrequency(e.target.value as DashboardShareFrequency)}
          >
            <option value="daily">Daily</option>
            <option value="weekly">Weekly</option>
            <option value="monthly">Monthly</option>
          </select>
        </div>
        <div className="field">
          <label className="field__label" htmlFor={`share-${kind}-time`}>
            Time of day <span className="crm-text-danger">*</span>
          </label>
          <span className="crm-text-muted crm-fs-sm">
            The dashboard is read when the {kind} is sent, so it shows the numbers at that time.
          </span>
          <div className="share-via-time-row">
            <select
              id={`share-${kind}-time`}
              className="input crm-flex-1"
              value={time}
              onChange={(e) => setTime(e.target.value)}
            >
              {TIMES.map((t) => (
                <option key={t} value={t}>
                  {timeLabel(t)}
                </option>
              ))}
            </select>
            <span className="share-via-tz" title={timeZone}>
              {zone}
            </span>
          </div>
          <span className="crm-text-muted crm-fs-sm crm-mt-1">
            This {kind} is scheduled to send {EVERY[frequency]} at {timeLabel(time)} {zone}.
          </span>
        </div>
      </>
    ) : null;

  const recurringChoice = (kind: 'email' | 'message') => (
    <div className="field">
      <span className="field__label">Is this a recurring {kind}?</span>
      <div className="crm-d-flex crm-flex-column crm-gap-2 crm-mt-1">
        <label className="check">
          <input
            type="radio"
            name={`${kind}_recurring`}
            checked={!recurring}
            onChange={() => setRecurring(false)}
          />
          <span className="check__box check__box--radio" />
          <span>No, this {kind} will only be sent once</span>
        </label>
        <label className="check">
          <input
            type="radio"
            name={`${kind}_recurring`}
            checked={recurring}
            onChange={() => setRecurring(true)}
          />
          <span className="check__box check__box--radio" />
          <span>Yes, this is a recurring {kind}</span>
        </label>
      </div>
    </div>
  );

  const nicknameField = (placeholder: string) =>
    recurring ? (
      <div className="field">
        <label className="field__label" htmlFor="shareNickname">
          Nickname <span className="crm-text-danger">*</span>
        </label>
        <span className="crm-text-muted crm-fs-sm">Recipients won&apos;t see this name</span>
        <input
          type="text"
          id="shareNickname"
          className="input"
          maxLength={191}
          placeholder={placeholder}
          value={nickname}
          onChange={(e) => setNickname(e.target.value)}
        />
      </div>
    ) : null;

  const methodCard = (m: Method, title: string, icon: React.ReactNode, disabled: boolean) => (
    <div
      className={cn('share-via-method-card', method === m ? 'is-selected' : '')}
      role="radio"
      aria-checked={method === m}
      aria-disabled={disabled || undefined}
      tabIndex={disabled ? -1 : 0}
      title={disabled ? 'Connect Slack in Settings › Integrations to share to Slack' : undefined}
      style={disabled ? { opacity: 0.5, cursor: 'not-allowed' } : undefined}
      onClick={() => !disabled && setMethod(m)}
      onKeyDown={(e) => {
        if (!disabled && (e.key === 'Enter' || e.key === ' ')) {
          e.preventDefault();
          setMethod(m);
        }
      }}
    >
      <div className="share-via-method-icon">{icon}</div>
      <div className="share-via-method-info">
        <span className="share-via-method-title">{title}</span>
        {disabled ? <span className="crm-fs-8 crm-text-muted">Slack is not connected</span> : null}
      </div>
      <div className="share-via-radio-circle">
        <div className="share-via-radio-inner" />
      </div>
    </div>
  );

  const title =
    step === 1 ? 'Share via' : method === 'email' ? 'Share via Email' : 'Share via Slack';

  return (
    <>
      <div
        className={cn(
          'popup-overlay reports-dashboard-settings-backdrop',
          open ? 'is-visible' : '',
        )}
        hidden={!open}
        aria-hidden="true"
        onClick={onClose}
      />
      <aside
        className="popup-drawer reports-dashboard-settings-drawer share-via-drawer"
        id="shareViaDrawer"
        hidden={!open}
        role="dialog"
        aria-modal="true"
        aria-hidden={!open}
        aria-labelledby="shareViaDrawerTitle"
      >
        <header className="drawer-header reports-dashboard-filter-drawer__header">
          <div className="drawer-header-content">
            <h2 className="drawer-title" id="shareViaDrawerTitle">
              {title}
            </h2>
          </div>
          <button
            type="button"
            className="drawer-close"
            aria-label="Close share drawer"
            onClick={onClose}
          >
            ×
          </button>
        </header>

        <div className={cn('share-via-stepper', step === 2 ? 'is-step-2' : '')}>
          <div className="share-via-stepper-inner">
            <div className="share-via-stepper__line" />
            {(
              [
                [1, 'Sharing Method'],
                [2, 'Configuration'],
              ] as const
            ).map(([n, label]) => (
              <div
                key={n}
                className={cn(
                  'share-via-step',
                  step === n ? 'is-active' : step > n ? 'is-completed' : '',
                )}
                role="button"
                tabIndex={0}
                aria-label={`Step ${n}: ${label}`}
                onClick={() => n === 1 && setStep(1)}
                onKeyDown={(e) => {
                  if (n === 1 && (e.key === 'Enter' || e.key === ' ')) setStep(1);
                }}
              >
                <div className="share-via-step__circle">
                  <span className="share-via-step__dot" />
                </div>
                <span className="share-via-step__label">{label}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="reports-dashboard-filter-drawer__body share-via-body">
          <div className="share-via-step-pane" hidden={step !== 1}>
            <h3 className="share-via-heading">Share your latest updates with others</h3>
            <p className="share-via-subheading">
              Choose a sharing method and send a message with your report.
            </p>
            <div className="share-via-methods" role="radiogroup" aria-label="Choose sharing method">
              {methodCard('email', 'Email', <EmailIcon />, false)}
              {methodCard('slack', 'Slack', <SlackIcon />, slackConnected !== true)}
            </div>
          </div>

          <div className="share-via-step-pane" hidden={step !== 2 || method !== 'email'}>
            <h3 className="share-via-heading">Share via Email</h3>
            <p className="share-via-subheading">Choose who receives this dashboard by email.</p>
            <form
              className="crm-d-flex crm-flex-column crm-gap-3"
              onSubmit={(e) => {
                e.preventDefault();
                void submit();
              }}
            >
              {recurringChoice('email')}
              {nicknameField('e.g. Weekly Executive Report')}
              <div className="field">
                <label className="field__label" htmlFor="shareEmailRecipients">
                  Internal recipients <span className="crm-text-danger">*</span>
                </label>
                <div className="share-via-tags-box">
                  {recipients.map((email) => {
                    const m = memberByEmail.get(email);
                    return (
                      <span key={email} className="share-via-tag">
                        <span>{m ? `${m.name} (${email})` : email}</span>
                        <button
                          type="button"
                          className="share-via-tag-remove"
                          aria-label="Remove recipient"
                          onClick={() => setRecipients((r) => r.filter((x) => x !== email))}
                        >
                          ×
                        </button>
                      </span>
                    );
                  })}
                  <input
                    type="text"
                    id="shareEmailRecipients"
                    className="share-via-tags-input"
                    placeholder="Type email and press enter..."
                    list="shareEmailMembers"
                    value={typed}
                    onChange={(e) => setTyped(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter' || e.key === ',') {
                        e.preventDefault();
                        addRecipient();
                      }
                    }}
                    onBlur={() => typed.trim() && addRecipient()}
                  />
                  <datalist id="shareEmailMembers">
                    {members.map((m) => (
                      <option key={m.userId} value={m.email}>
                        {m.name}
                      </option>
                    ))}
                  </datalist>
                </div>
              </div>
              <div className="field">
                <label className="field__label" htmlFor="shareEmailAttachment">
                  Attach downloadable file <span className="crm-text-danger">*</span>
                </label>
                <select
                  id="shareEmailAttachment"
                  className="input crm-w-100"
                  value={attachment}
                  onChange={(e) => setAttachment(e.target.value as 'none' | 'csv')}
                >
                  <option value="none">No attachment</option>
                  <option value="csv">CSV</option>
                </select>
              </div>
              <div className="field">
                <label className="field__label" htmlFor="shareEmailOtherRecipients">
                  Other recipients
                </label>
                <input
                  type="text"
                  id="shareEmailOtherRecipients"
                  className="input"
                  placeholder="Comma separated external email addresses"
                  value={others}
                  onChange={(e) => setOthers(e.target.value)}
                />
              </div>
              <div className="field">
                <label className="field__label" htmlFor="shareEmailSubject">
                  Email subject
                </label>
                <input
                  type="text"
                  id="shareEmailSubject"
                  className="input"
                  maxLength={191}
                  value={subject}
                  onChange={(e) => setSubject(e.target.value)}
                />
              </div>
              <div className="field">
                <label className="field__label" htmlFor="shareEmailMessage">
                  Email message
                </label>
                <textarea
                  id="shareEmailMessage"
                  className="input"
                  rows={4}
                  maxLength={5000}
                  placeholder="Add an optional message for the recipients..."
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                />
              </div>
              {scheduleFields('email')}
            </form>
          </div>

          <div className="share-via-step-pane" hidden={step !== 2 || method !== 'slack'}>
            <h3 className="share-via-heading">Share via Slack</h3>
            <p className="share-via-subheading">
              Choose which Slack channel and user to share your report to.
            </p>
            <form
              className="crm-d-flex crm-flex-column crm-gap-3"
              onSubmit={(e) => {
                e.preventDefault();
                void submit();
              }}
            >
              {recurringChoice('message')}
              {nicknameField('e.g. Daily Metrics Pulse')}
              <div className="field">
                <span className="field__label">Sharing to Slack channel or user?</span>
                <div className="crm-d-flex crm-flex-column crm-gap-2 crm-mt-1">
                  {(['channel', 'user'] as const).map((d) => (
                    <label key={d} className="check">
                      <input
                        type="radio"
                        name="slack_destination"
                        checked={destination === d}
                        onChange={() => {
                          setDestination(d);
                          setTargetId('');
                        }}
                      />
                      <span className="check__box check__box--radio" />
                      <span>{d === 'channel' ? 'Slack channel' : 'User'}</span>
                    </label>
                  ))}
                </div>
              </div>
              <div className="field">
                <label className="field__label" htmlFor="shareSlackTarget">
                  {destination === 'channel' ? 'Share to channel' : 'Share to user'}
                </label>
                <select
                  id="shareSlackTarget"
                  className="input crm-w-100"
                  value={targetId}
                  onChange={(e) => setTargetId(e.target.value)}
                >
                  <option value="">
                    {destination === 'channel' ? 'Select a channel' : 'Select a user'}
                  </option>
                  {(destination === 'channel' ? channels : slackUsers).map((t) => (
                    <option key={t.id} value={t.id}>
                      {t.name}
                    </option>
                  ))}
                </select>
              </div>
              <div className="field">
                <label className="field__label" htmlFor="shareSlackMessage">
                  Message
                </label>
                <textarea
                  id="shareSlackMessage"
                  className="input"
                  rows={4}
                  maxLength={5000}
                  placeholder="Add an optional note..."
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                />
              </div>
              {scheduleFields('message')}
            </form>
          </div>

          {error ? (
            <p className="crm-fs-8 crm-text-danger crm-mt-2" role="alert">
              {error}
            </p>
          ) : null}
        </div>

        <footer className="drawer-footer reports-dashboard-filter-drawer__footer share-via-footer">
          <button
            type="button"
            className="btn-crm btn-crm--outline"
            style={{ visibility: step === 1 ? 'hidden' : 'visible' }}
            disabled={step === 1}
            onClick={() => {
              setStep(1);
              setError(null);
            }}
          >
            Back
          </button>
          <div className="drawer-footer-actions">
            <button
              type="button"
              className="btn-crm btn-crm--primary"
              disabled={busy}
              onClick={() => void submit()}
            >
              {submitLabel}
            </button>
          </div>
        </footer>
      </aside>
    </>
  );
}

function EmailIcon() {
  return (
    <svg width="44" height="44" viewBox="0 0 48 48" fill="none" aria-hidden="true">
      <path
        d="M10 16L24 27L38 16"
        stroke="#0284c7"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <rect
        x="8"
        y="14"
        width="32"
        height="22"
        rx="4"
        fill="#e0f2fe"
        stroke="#0284c7"
        strokeWidth="2"
      />
      <path d="M8 16L24 27L40 16" stroke="#0284c7" strokeWidth="2" strokeLinecap="round" />
      <path
        d="M14 14V10C14 8.89543 14.8954 8 16 8H26"
        stroke="#0369a1"
        strokeWidth="2"
        strokeLinecap="round"
      />
      <circle cx="34" cy="12" r="6" fill="#0d9488" />
      <path
        d="M32 12H36M36 12L34 10M36 12L34 14"
        stroke="#ffffff"
        strokeWidth="1.8"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <path d="M26 6L27 3L28 6L31 7L28 8L27 11L26 8L23 7L26 6Z" fill="#f59e0b" />
    </svg>
  );
}

function SlackIcon() {
  return (
    <svg width="38" height="38" viewBox="0 0 128 128" aria-hidden="true">
      <path
        d="M26.7 80.3c0 7.4-6 13.4-13.4 13.4s-13.3-6-13.3-13.4c0-7.4 6-13.4 13.4-13.4h13.3v13.4z"
        fill="#E01E5A"
      />
      <path
        d="M33.4 80.3c0-7.4 6-13.4 13.4-13.4s13.4 6 13.4 13.4v33.4c0 7.4-6 13.4-13.4 13.4s-13.4-6-13.4-13.4V80.3z"
        fill="#E01E5A"
      />
      <path
        d="M46.8 26.7c-7.4 0-13.4-6-13.4-13.4s6-13.3 13.4-13.3c7.4 0 13.4 6 13.4 13.4v13.3H46.8z"
        fill="#36C5F0"
      />
      <path
        d="M46.8 33.4c7.4 0 13.4 6 13.4 13.4s-6 13.4-13.4 13.4H13.4C6 60.2 0 54.2 0 46.8s6-13.4 13.4-13.4h33.4z"
        fill="#36C5F0"
      />
      <path
        d="M101.3 46.8c0-7.4 6-13.4 13.4-13.4s13.4 6 13.4 13.4-6 13.4-13.4 13.4h-13.4V46.8z"
        fill="#2EB67D"
      />
      <path
        d="M94.6 46.8c0 7.4-6 13.4-13.4 13.4s-13.4-6-13.4-13.4V13.4C67.8 6 73.8 0 81.2 0s13.4 6 13.4 13.4v33.4z"
        fill="#2EB67D"
      />
      <path
        d="M81.2 101.3c7.4 0 13.4 6 13.4 13.4s-6 13.4-13.4 13.4c-7.4 0-13.4-6-13.4-13.4v-13.4h13.4z"
        fill="#ECB22E"
      />
      <path
        d="M81.2 94.6c-7.4 0-13.4-6-13.4-13.4s6-13.4 13.4-13.4h33.4c7.4 0 13.4 6 13.4 13.4s-6 13.4-13.4 13.4H81.2z"
        fill="#ECB22E"
      />
    </svg>
  );
}
