'use client';

import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { listDashboards } from '@/features/reports/api.client';
import { createReport, listReportTags } from '@/features/saved-reports/api.client';
import type { ReportShare } from '@/features/saved-reports/types';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { presetLabel, type CallAnalyticsFilters } from '../analytics';

type Option = { value: string; label: string };

/**
 * CL8b (Calls parity): a Call Analytics card's ⋮ › Save report, the live design's side panel
 * (call-analytics.php `ca-pan`, call-analytics.js openSave / finish): step 1 name, tags,
 * description (Generate), dashboard; step 2 a new dashboard's name and who can access the report.
 * It saves a report of the card (POST /saved-reports with `definition.callAnalytics`), which the
 * reports library lists and opens back here with the card's filters.
 */
export function CallReportSavePanel({
  card,
  filters,
  lists,
  onClose,
}: {
  /** The card saved: its key and title; null closes the panel. */
  card: { id: string; title: string } | null;
  filters: CallAnalyticsFilters;
  /** The page's filter lists, for Generate's words. */
  lists: Array<{ key: keyof CallAnalyticsFilters; label: string; options: Option[] }>;
  onClose: () => void;
}) {
  const toast = useToast();
  const [step, setStep] = useState<1 | 2>(1);
  const [name, setName] = useState('');
  const [desc, setDesc] = useState('');
  const [tags, setTags] = useState<Option[]>([]);
  const [tagIds, setTagIds] = useState<string[]>([]);
  const [tagsOpen, setTagsOpen] = useState(false);
  const [dash, setDash] = useState<'none' | 'existing' | 'new'>('none');
  const [dashboards, setDashboards] = useState<Option[]>([]);
  const [dashId, setDashId] = useState('');
  const [dashName, setDashName] = useState('');
  const [access, setAccess] = useState<'private' | 'everyone' | 'specific'>('everyone');
  const [shares, setShares] = useState<string[]>([]);
  const [errors, setErrors] = useState<Record<string, boolean>>({});
  const [busy, setBusy] = useState(false);
  const nameRef = useRef<HTMLInputElement>(null);
  const people = lists.find((l) => l.key === 'ownerIds')?.options ?? [];
  const teams = lists.find((l) => l.key === 'teamIds')?.options ?? [];

  useEffect(() => {
    if (!card) return;
    setStep(1);
    setName('');
    setDesc('');
    setTagIds([]);
    setTagsOpen(false);
    setDash('none');
    setDashId('');
    setDashName('');
    setAccess('everyone');
    setShares([]);
    setErrors({});
    listReportTags().then(
      (rows) => setTags(rows.map((t) => ({ value: t.id, label: t.name }))),
      () => setTags([]),
    );
    listDashboards().then(
      (rows) => setDashboards(rows.map((d) => ({ value: d.id, label: d.name }))),
      () => setDashboards([]),
    );
    window.setTimeout(() => nameRef.current?.focus(), 0);
  }, [card]);

  useEffect(() => {
    if (!card) return;
    const key = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !busy) onClose();
    };
    document.addEventListener('keydown', key);
    return () => document.removeEventListener('keydown', key);
  }, [card, busy, onClose]);

  if (!card) return null;

  /** The design's Generate (call-analytics.js describe). */
  const generate = () => {
    const used = lists.filter((l) => filters[l.key].length);
    const words = (l: (typeof lists)[number]) =>
      (filters[l.key] as string[])
        .map((v) =>
          v === 'unassigned' ? 'Unassigned' : (l.options.find((o) => o.value === v)?.label ?? v),
        )
        .join(', ');
    const text =
      `This report shows ${card.title.charAt(0).toLowerCase()}${card.title.slice(1)} from the Call Analytics dashboard` +
      (filters.date ? ` for ${presetLabel(filters.date).toLowerCase()}` : '') +
      '.' +
      (used.length
        ? ` Filtered by ${used.map((l) => `${l.label.toLowerCase()} (${words(l)})`).join(', ')}.`
        : '') +
      ' Use it to track call volume and activity across your sales team.';
    setDesc(text.slice(0, 1000));
  };

  const last = step === 2 || dash === 'existing';
  const goLabel = !last ? 'Next' : dash === 'none' ? 'Save' : 'Save & add';

  const save = async () => {
    setBusy(true);
    try {
      const reportShares: ReportShare[] = shares.map((s) =>
        s.startsWith('team:') ? { type: 'team', id: s.slice(5) } : { type: 'user', id: s },
      );
      await createReport({
        name: name.trim(),
        description: desc.trim() || null,
        tagIds,
        // The design saves to an existing dashboard straight away, for everyone.
        access: dash === 'existing' ? 'everyone' : access === 'private' ? 'owner_only' : access,
        ...(access === 'specific' && dash !== 'existing' && { shares: reportShares }),
        addToDashboard:
          dash === 'existing'
            ? { mode: 'existing', dashboardId: dashId }
            : dash === 'new'
              ? { mode: 'new', name: dashName.trim() }
              : { mode: 'none' },
        definition: {
          // What the report is about, for the library; it runs through Call Analytics.
          objectType: 'contact',
          chartType:
            card.id === 'goal'
              ? 'line'
              : card.id === 'byday' || card.id === 'minutes' || card.id === 'types'
                ? 'column'
                : 'bar',
          measure: { op: 'count' },
          groupBy: null,
          breakdown: null,
          filter: null,
          dateRange: null,
          columns: [],
          display: { showTotal: true, showDateBadge: true },
          callAnalytics: {
            card: card.id,
            ...(filters.date && { date: filters.date }),
            ...(filters.ownerIds.length && { ownerIds: filters.ownerIds }),
            ...(filters.outcomes.length && { outcomes: filters.outcomes }),
            ...(filters.teamIds.length && { teamIds: filters.teamIds }),
            ...(filters.directions.length && { directions: filters.directions }),
          },
        },
      });
      const dashLabel =
        dash === 'existing'
          ? dashboards.find((d) => d.value === dashId)?.label
          : dash === 'new'
            ? dashName.trim()
            : '';
      toast(
        `"${name.trim()}" saved to your reports${dashLabel ? ` and added to ${dashLabel}` : ''}`,
      );
      onClose();
    } catch (err) {
      toast(errorText(err), 'danger', { durationMs: 8000 });
    } finally {
      setBusy(false);
    }
  };

  const submit = () => {
    if (step === 1) {
      if (!name.trim()) {
        setErrors({ name: true });
        nameRef.current?.focus();
        return;
      }
      if (dash === 'existing') {
        if (!dashId) {
          setErrors({ dashId: true });
          return;
        }
        void save();
        return;
      }
      setErrors({});
      setStep(2);
      return;
    }
    if (dash === 'new' && !dashName.trim()) {
      setErrors({ dashName: true });
      return;
    }
    if (access === 'specific' && !shares.length) {
      setErrors({ users: true });
      return;
    }
    void save();
  };

  const tagText = tagIds.length
    ? tagIds
        .map((id) => tags.find((t) => t.value === id)?.label ?? '')
        .filter(Boolean)
        .join(', ')
    : 'Select tags';

  return (
    <div
      className="ca-pan-ov is-open"
      onClick={(e) => e.target === e.currentTarget && !busy && onClose()}
    >
      <aside className="ca-pan" role="dialog" aria-modal="true" aria-labelledby="caSaveT">
        <header className="ca-pan__head">
          <h2 id="caSaveT">Save report</h2>
          <button
            type="button"
            className="ca-icon"
            aria-label="Close"
            onClick={onClose}
            disabled={busy}
          >
            <CrmIcon name="x" className="iconSize-18" />
          </button>
        </header>
        <form
          className="ca-pan__form"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            submit();
          }}
        >
          <div className="ca-pan__body">
            {step === 1 ? (
              <section className="ca-step">
                <p className="ca-pan__intro">
                  This report will be saved to your reports. You can also add it to a dashboard.
                </p>
                <label className="ca-f">
                  <span>
                    Report name <b aria-hidden="true">*</b>
                  </span>
                  <input
                    ref={nameRef}
                    type="text"
                    maxLength={120}
                    required
                    autoComplete="off"
                    value={name}
                    onChange={(e) => {
                      setName(e.target.value);
                      if (e.target.value.trim()) setErrors((x) => ({ ...x, name: false }));
                    }}
                  />
                  {errors.name ? <small>Enter a report name.</small> : null}
                </label>
                <div className="ca-f">
                  <span id="caTagsL">Tags</span>
                  <div className="ca-tags">
                    <button
                      type="button"
                      className={cn('ca-sel', tagIds.length > 0 && 'is-set')}
                      aria-haspopup="listbox"
                      aria-expanded={tagsOpen}
                      aria-labelledby="caTagsL caTagsV"
                      onClick={() => setTagsOpen((o) => !o)}
                    >
                      <span id="caTagsV">{tagText}</span>
                      <CrmIcon name="chevron-down" className="iconSize-14" />
                    </button>
                    {tagsOpen ? (
                      <div className="ca-dd">
                        <div role="listbox" aria-multiselectable="true" aria-labelledby="caTagsL">
                          {tags.map((t, i) => {
                            const on = tagIds.includes(t.value);
                            return (
                              <button
                                key={t.value}
                                type="button"
                                className="ca-dd__opt"
                                role="option"
                                aria-selected={on}
                                onClick={() =>
                                  setTagIds((ids) =>
                                    on ? ids.filter((x) => x !== t.value) : [...ids, t.value],
                                  )
                                }
                              >
                                <span className={cn('ca-cb', on && 'is-on')} />
                                <span className={`ca-dot ca-dot--${i % 4}`} />
                                {t.label}
                              </button>
                            );
                          })}
                        </div>
                        <Link
                          className="ca-dd__foot"
                          href="/reports/library"
                          target="_blank"
                          rel="noopener"
                        >
                          Manage tags <CrmIcon name="external" className="iconSize-14" />
                        </Link>
                      </div>
                    ) : null}
                  </div>
                </div>
                <div className="ca-f">
                  <label htmlFor="caDesc">Description</label>
                  <textarea
                    id="caDesc"
                    rows={4}
                    maxLength={1000}
                    value={desc}
                    onChange={(e) => setDesc(e.target.value)}
                  />
                  <div className="ca-f__meta">
                    <small className="ca-count" aria-live="polite">
                      {1000 - desc.length}
                    </small>
                    <button type="button" className="ca-gen" onClick={generate}>
                      Generate
                    </button>
                  </div>
                </div>
                <fieldset className="ca-rad">
                  <legend>Add this report to a dashboard?</legend>
                  {(
                    [
                      ['none', "Don't add to a dashboard"],
                      ['existing', 'Add to existing dashboard'],
                    ] as const
                  ).map(([v, l]) => (
                    <label key={v}>
                      <input
                        type="radio"
                        name="dash"
                        checked={dash === v}
                        onChange={() => setDash(v)}
                      />
                      <span>{l}</span>
                    </label>
                  ))}
                  {dash === 'existing' ? (
                    <div className="ca-rad__sub">
                      <select
                        aria-label="Dashboard"
                        value={dashId}
                        onChange={(e) => {
                          setDashId(e.target.value);
                          if (e.target.value) setErrors((x) => ({ ...x, dashId: false }));
                        }}
                      >
                        <option value="">Search</option>
                        {dashboards.map((d) => (
                          <option key={d.value} value={d.value}>
                            {d.label}
                          </option>
                        ))}
                      </select>
                      {errors.dashId ? <small>Choose a dashboard.</small> : null}
                    </div>
                  ) : null}
                  <label>
                    <input
                      type="radio"
                      name="dash"
                      checked={dash === 'new'}
                      onChange={() => setDash('new')}
                    />
                    <span>Add to new dashboard</span>
                  </label>
                </fieldset>
              </section>
            ) : (
              <section className="ca-step">
                {dash === 'new' ? (
                  <label className="ca-f">
                    <span>
                      Dashboard name <b aria-hidden="true">*</b>
                    </span>
                    <input
                      type="text"
                      maxLength={120}
                      autoComplete="off"
                      value={dashName}
                      onChange={(e) => setDashName(e.target.value)}
                    />
                    {errors.dashName ? <small>Enter a dashboard name.</small> : null}
                  </label>
                ) : null}
                <fieldset className="ca-rad">
                  <legend>Who can access this report?</legend>
                  {(
                    [
                      ['private', 'Private to owner (me)'],
                      ['everyone', 'Everyone'],
                      ['specific', 'Only specific users and teams'],
                    ] as const
                  ).map(([v, l]) => (
                    <label key={v}>
                      <input
                        type="radio"
                        name="access"
                        checked={access === v}
                        onChange={() => setAccess(v)}
                      />
                      <span>{l}</span>
                    </label>
                  ))}
                  {access === 'specific' ? (
                    <div className="ca-rad__sub ca-users">
                      {people.map((p) => (
                        <label key={p.value}>
                          <input
                            type="checkbox"
                            checked={shares.includes(p.value)}
                            onChange={(e) =>
                              setShares((s) =>
                                e.target.checked ? [...s, p.value] : s.filter((x) => x !== p.value),
                              )
                            }
                          />
                          <span>{p.label}</span>
                        </label>
                      ))}
                      {teams.map((t) => {
                        const v = `team:${t.value}`;
                        return (
                          <label key={v}>
                            <input
                              type="checkbox"
                              checked={shares.includes(v)}
                              onChange={(e) =>
                                setShares((s) =>
                                  e.target.checked ? [...s, v] : s.filter((x) => x !== v),
                                )
                              }
                            />
                            <span>
                              {t.label} <em>(team)</em>
                            </span>
                          </label>
                        );
                      })}
                      {errors.users ? <small>Choose at least one user or team.</small> : null}
                    </div>
                  ) : null}
                </fieldset>
              </section>
            )}
          </div>
          <footer className="ca-pan__foot">
            {step === 2 ? (
              <button
                type="button"
                className="btn-crm btn-crm--outline btn-crm--sm"
                disabled={busy}
                onClick={() => setStep(1)}
              >
                <CrmIcon name="chevron-left" className="iconSize-14" />
                Back
              </button>
            ) : null}
            <button
              type="submit"
              className={cn(
                'btn-crm btn-crm--primary btn-crm--sm ca-pan__go',
                busy && 'is-loading',
              )}
              disabled={busy || !name.trim()}
            >
              <span>{goLabel}</span>
              {!last ? <CrmIcon name="chevron-right" className="iconSize-14" /> : null}
            </button>
          </footer>
        </form>
      </aside>
    </div>
  );
}
