'use client';

/**
 * Team inboxes (HUB-366): shared addresses such as support@. People with "Connect channels"
 * create one and connect its Gmail; people with "Manage team inboxes" choose who can read it,
 * whether a new conversation gets a ticket, and whether it is assigned in turn (HUB-715). With both, its other channels: live
 * chat on a website, website forms and logged calls.
 */
import { useCallback, useEffect, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import {
  connectSharedInbox,
  createSharedInbox,
  listSharedInboxes,
  listWebsiteForms,
  updateSharedInbox,
} from '@/features/inbox/api.client';
import type {
  InboxChannels,
  InboxRouting,
  SharedInbox,
  SharedInboxList,
} from '@/features/inbox/types';
import { useOwners } from '@/features/owners/useOwners';
import { errorText } from '@/lib/api/errors';
import { fallbackEmailHelp, fallbackEmailProblem } from './fallback-email';
import { RoutingFields, routingOf, routingProblem } from './RoutingFields';

interface Person {
  id: string;
  name: string;
}

interface WebsiteForm {
  id: string;
  name: string;
}

const check = { display: 'flex', gap: 6, alignItems: 'center', marginTop: 8 } as const;
const bare = { border: 0, padding: 0, margin: '16px 0 0' } as const;

/** The line a website adds to show the chat button. */
const websiteCode = (inboxId: string) =>
  `<script src="${window.location.origin}/crm-chat.js" data-inbox="${inboxId}" async></script>`;

function ChannelFields({
  inbox,
  forms,
  value,
  onChange,
}: {
  inbox: SharedInbox;
  /** Null: I may not see the business's forms. */
  forms: WebsiteForm[] | null;
  value: InboxChannels;
  onChange: (next: InboxChannels) => void;
}) {
  const toast = useToast();
  const chat = value.chat;
  const setChat = (change: Partial<InboxChannels['chat']>) =>
    onChange({ ...value, chat: { ...chat, ...change } });
  const copy = () =>
    navigator.clipboard.writeText(websiteCode(inbox.id)).then(
      () => toast('Website code copied'),
      () => toast('Select the code and copy it', 'danger'),
    );

  return (
    <fieldset style={bare}>
      <legend className="field__label">Channels into this inbox</legend>

      <label style={check}>
        <input
          type="checkbox"
          checked={chat.enabled}
          onChange={(e) => setChat({ enabled: e.target.checked })}
        />
        Live chat on your website
      </label>
      {chat.enabled ? (
        <div style={{ margin: '8px 0 0 22px' }}>
          <label className="field__label" htmlFor={`chat-greeting-${inbox.id}`}>
            Greeting
          </label>
          <input
            id={`chat-greeting-${inbox.id}`}
            className="input crm-mb-2"
            maxLength={500}
            value={chat.greeting}
            onChange={(e) => setChat({ greeting: e.target.value })}
          />
          <label className="field__label" htmlFor={`chat-away-${inbox.id}`}>
            Automatic message while nobody here is available
          </label>
          <textarea
            id={`chat-away-${inbox.id}`}
            className="input"
            rows={2}
            maxLength={500}
            value={chat.awayMessage}
            onChange={(e) => setChat({ awayMessage: e.target.value })}
          />
          <label className="field__label crm-mt-2" htmlFor={`chat-fallback-${inbox.id}`}>
            Fallback support email (optional)
          </label>
          <input
            id={`chat-fallback-${inbox.id}`}
            type="email"
            className="input"
            placeholder={inbox.emailAddress ?? 'support@yourcompany.com'}
            maxLength={191}
            value={chat.fallbackEmail ?? ''}
            onChange={(e) => setChat({ fallbackEmail: e.target.value })}
          />
          <p className="crm-text-muted crm-fs-8 crm-mt-2">
            {fallbackEmailHelp(chat.fallbackEmail, inbox.emailAddress)}
          </p>
          {inbox.channels.chat.enabled ? (
            <div className="crm-mt-3">
              <label className="field__label" htmlFor={`chat-code-${inbox.id}`}>
                Add this line to your website to show the chat button
              </label>
              <textarea
                id={`chat-code-${inbox.id}`}
                className="input"
                rows={2}
                readOnly
                value={websiteCode(inbox.id)}
                onFocus={(e) => e.currentTarget.select()}
              />
              <p className="crm-mt-2">
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  onClick={() => void copy()}
                >
                  Copy code
                </button>{' '}
                <a
                  className="link"
                  href={`/chat-widget/${inbox.id}`}
                  target="_blank"
                  rel="noreferrer"
                >
                  Open the chat window
                </a>
              </p>
            </div>
          ) : (
            <p className="crm-text-muted crm-fs-8 crm-mt-2">Save to get the website code.</p>
          )}
        </div>
      ) : null}

      <p className="field__label crm-mt-3">Website forms that start a conversation here</p>
      {forms === null ? (
        <p className="crm-text-muted crm-fs-8">
          You need access to account settings to choose forms. {value.forms.formIds.length} chosen.
        </p>
      ) : forms.length ? (
        forms.map((form) => (
          <label key={form.id} style={check}>
            <input
              type="checkbox"
              checked={value.forms.formIds.includes(form.id)}
              onChange={(e) =>
                onChange({
                  ...value,
                  forms: {
                    formIds: e.target.checked
                      ? [...value.forms.formIds, form.id]
                      : value.forms.formIds.filter((id) => id !== form.id),
                  },
                })
              }
            />
            {form.name}
          </label>
        ))
      ) : (
        <p className="crm-text-muted crm-fs-8">There are no website forms yet.</p>
      )}

      <label style={{ ...check, marginTop: 14 }}>
        <input
          type="checkbox"
          checked={value.calls.enabled}
          onChange={(e) => onChange({ ...value, calls: { enabled: e.target.checked } })}
        />
        Log calls into this inbox
      </label>
      <p className="crm-text-muted crm-fs-8" style={{ marginLeft: 22 }}>
        No phone system is connected: members write calls down with “Log a call” in the Inbox.
      </p>
    </fieldset>
  );
}

function MemberPicker({
  people,
  chosen,
  onChange,
  disabled,
}: {
  people: Person[];
  chosen: string[];
  onChange: (next: string[]) => void;
  disabled: boolean;
}) {
  return (
    <fieldset disabled={disabled} style={{ border: 0, padding: 0, margin: 0 }}>
      <legend className="field__label">Who can read and answer</legend>
      <div
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: '6px 18px',
          maxHeight: 160,
          overflowY: 'auto',
        }}
      >
        {people.map((person) => (
          <label key={person.id} style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
            <input
              type="checkbox"
              checked={chosen.includes(person.id)}
              onChange={(e) =>
                onChange(
                  e.target.checked
                    ? [...chosen, person.id]
                    : chosen.filter((id) => id !== person.id),
                )
              }
            />
            {person.name}
          </label>
        ))}
      </div>
    </fieldset>
  );
}

function InboxCard({
  inbox,
  forms,
  people,
  canManage,
  canConnect,
  onChanged,
}: {
  inbox: SharedInbox;
  forms: WebsiteForm[] | null;
  people: Person[];
  canManage: boolean;
  canConnect: boolean;
  onChanged: () => void;
}) {
  const toast = useToast();
  const [name, setName] = useState(inbox.name);
  const [members, setMembers] = useState(inbox.members.map((m) => m.id));
  const [autoTicket, setAutoTicket] = useState(!!inbox.autoTicket?.enabled);
  const [channels, setChannels] = useState(inbox.channels);
  const [routing, setRouting] = useState<InboxRouting>(() => routingOf(inbox.routing));
  const [busy, setBusy] = useState(false);
  const connected = inbox.status === 'connected' || inbox.status === 'syncing';

  const save = async () => {
    if (!name.trim()) {
      toast('Give the inbox a name', 'danger');
      return;
    }
    const problem =
      routingProblem(routing) ??
      (canConnect ? fallbackEmailProblem(channels.chat.fallbackEmail) : null);
    if (problem) {
      toast(problem, 'danger');
      return;
    }
    setBusy(true);
    try {
      await updateSharedInbox(inbox.id, {
        name: name.trim(),
        memberIds: members,
        autoTicket: { ...inbox.autoTicket, enabled: autoTicket },
        routing,
        ...(canConnect && {
          channels: {
            ...channels,
            chat: { ...channels.chat, fallbackEmail: (channels.chat.fallbackEmail ?? '').trim() },
          },
        }),
      });
      toast('Team inbox saved');
      onChanged();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  const connect = async () => {
    try {
      const { authUrl } = await connectSharedInbox(inbox.id);
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  return (
    <article className="sales-card crm-mb-3" style={{ padding: 16 }} aria-label={inbox.name}>
      <p className="crm-mb-2">
        <strong>{inbox.name}</strong>{' '}
        <span className="crm-text-muted">
          {inbox.emailAddress
            ? `${inbox.emailAddress} · ${connected ? 'connected' : inbox.status.replace('_', ' ')}`
            : 'No Gmail address connected yet'}
        </span>
      </p>
      {canConnect && !connected ? (
        <p className="crm-mb-3">
          <button type="button" className="btn-crm btn-crm--outline btn-crm--sm" onClick={connect}>
            {inbox.emailAddress ? 'Reconnect Gmail' : 'Connect Gmail'}
          </button>{' '}
          <span className="crm-text-muted crm-fs-8">
            Sign in to Google with the team address, not your own.
          </span>
        </p>
      ) : null}
      {canManage ? (
        <>
          <label className="field__label" htmlFor={`team-name-${inbox.id}`}>
            Name
          </label>
          <input
            id={`team-name-${inbox.id}`}
            className="input crm-mb-3"
            maxLength={100}
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
          <MemberPicker people={people} chosen={members} onChange={setMembers} disabled={busy} />
          <label style={{ display: 'flex', gap: 6, alignItems: 'center', marginTop: 12 }}>
            <input
              type="checkbox"
              checked={autoTicket}
              onChange={(e) => setAutoTicket(e.target.checked)}
            />
            Create a ticket automatically for each new conversation
          </label>
          <RoutingFields value={routing} teams={inbox.teams ?? []} onChange={setRouting} />
          {canConnect ? (
            <ChannelFields inbox={inbox} forms={forms} value={channels} onChange={setChannels} />
          ) : null}
          <p className="crm-mt-3">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={busy}
              onClick={() => void save()}
            >
              Save
            </button>
          </p>
        </>
      ) : (
        <p className="crm-text-muted">
          Members: {inbox.members.map((m) => m.name).join(', ') || 'nobody yet'}
        </p>
      )}
    </article>
  );
}

export function TeamInboxesPanel() {
  const toast = useToast();
  const { owners } = useOwners(true, false);
  const [list, setList] = useState<SharedInboxList | null>(null);
  const [forms, setForms] = useState<WebsiteForm[] | null>(null);
  const [name, setName] = useState('');
  const [members, setMembers] = useState<string[]>([]);
  const [busy, setBusy] = useState(false);

  const load = useCallback(() => {
    listSharedInboxes().then(setList, (err) => toast(errorText(err), 'danger'));
  }, [toast]);
  useEffect(load, [load]);
  useEffect(() => {
    listWebsiteForms().then(
      (res) => setForms(res.data),
      () => setForms(null), // without the settings permission the list is not shown
    );
  }, []);

  if (!list || (!list.canManage && !list.canConnect)) return null;
  const people = owners.filter((o) => o.active).map((o) => ({ id: o.userId, name: o.name }));

  const create = async () => {
    if (!name.trim()) {
      toast('Give the inbox a name, for example Support', 'danger');
      return;
    }
    setBusy(true);
    try {
      await createSharedInbox({ name: name.trim(), memberIds: members });
      setName('');
      setMembers([]);
      toast('Team inbox created. Connect its Gmail address next.');
      load();
    } catch (err) {
      toast(errorText(err), 'danger');
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="crm-mb-4" aria-labelledby="team-inboxes-title">
      <h2 className="sales-card__title" id="team-inboxes-title">
        Team inboxes
      </h2>
      <p className="crm-text-muted crm-mb-3">
        Shared addresses such as support@. Only their members and people who manage inboxes can read
        them. Everyone’s own Gmail stays private.
      </p>
      {list.data.map((inbox) => (
        <InboxCard
          key={`${inbox.id}:${inbox.members.length}:${inbox.name}`}
          inbox={inbox}
          forms={forms}
          people={people}
          canManage={list.canManage}
          canConnect={list.canConnect}
          onChanged={load}
        />
      ))}
      {list.canConnect ? (
        <div className="sales-card" style={{ padding: 16 }}>
          <label className="field__label" htmlFor="team-new-name">
            New team inbox
          </label>
          <input
            id="team-new-name"
            className="input crm-mb-3"
            placeholder="Support"
            maxLength={100}
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
          <MemberPicker people={people} chosen={members} onChange={setMembers} disabled={busy} />
          <p className="crm-mt-3">
            <button
              type="button"
              className="btn-crm btn-crm--primary btn-crm--sm"
              disabled={busy}
              onClick={() => void create()}
            >
              Create team inbox
            </button>
          </p>
        </div>
      ) : null}
    </section>
  );
}
