'use client';

import { useEffect, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

export type ViewDialogMode = 'save' | 'clone' | 'share';

const TITLES: Record<ViewDialogMode, string> = {
  save: 'Save view',
  clone: 'Clone to new view',
  share: 'Manage sharing',
};

/**
 * Name and access of a view: "Save view" / "Clone to new view" (a new view), or "Manage
 * sharing" (access only). Views are private or shared with everyone; the API has no team
 * sharing yet, so "My team" is shown but can't be picked.
 */
export function SaveViewDialog({
  mode,
  open,
  onClose,
  initialName,
  initialShared,
  onSubmit,
}: {
  mode: ViewDialogMode;
  open: boolean;
  onClose: () => void;
  initialName: string;
  initialShared: boolean;
  /** Rejects with the API error to show it. */
  onSubmit: (input: { name: string; isShared: boolean }) => Promise<void>;
}) {
  const [name, setName] = useState(initialName);
  const [shared, setShared] = useState(initialShared);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [nameMissing, setNameMissing] = useState(false);

  useEffect(() => {
    if (!open) return;
    setName(initialName);
    setShared(initialShared);
    setError(null);
    setNameMissing(false);
    setBusy(false);
  }, [open, initialName, initialShared]);

  const submit = async () => {
    if (mode !== 'share' && !name.trim()) {
      setNameMissing(true);
      return;
    }
    setBusy(true);
    setError(null);
    try {
      await onSubmit({ name: name.trim(), isShared: shared });
      onClose();
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(false);
    }
  };

  return (
    <CrmModal id="evViewModal" open={open} onClose={onClose}>
      <form
        noValidate
        className="ev-dialog"
        onSubmit={(e) => {
          e.preventDefault();
          void submit();
        }}
      >
        <ModalHeader id="evViewModal" title={TITLES[mode]} onClose={onClose} />
        <div className="modal__body">
          {error ? <Alert tone="danger">{error}</Alert> : null}
          {mode !== 'share' ? (
            <div className={cn('field', nameMissing && 'is-invalid')}>
              <label className="field__label" htmlFor="evViewName">
                View name
              </label>
              <input
                className="input"
                id="evViewName"
                maxLength={100}
                autoComplete="off"
                value={name}
                onChange={(e) => {
                  setName(e.target.value);
                  if (e.target.value.trim()) setNameMissing(false);
                }}
              />
              <span className="field__error">Enter a view name.</span>
            </div>
          ) : null}
          <fieldset className="ev-fieldset">
            <legend className="field__label">
              {mode === 'share' ? 'Who can access this view' : 'Who can access it'}
            </legend>
            <label className="ev-radio">
              <input
                type="radio"
                name="access"
                checked={!shared}
                onChange={() => setShared(false)}
              />{' '}
              Private {mode === 'share' ? <span className="ev-help-inline">Only you</span> : null}
            </label>
            <label className="ev-radio is-disabled" title="Team sharing is not available yet">
              <input type="radio" name="access" disabled /> My team{' '}
              <span className="ev-help-inline">Not available yet</span>
            </label>
            <label className="ev-radio">
              <input type="radio" name="access" checked={shared} onChange={() => setShared(true)} />{' '}
              Everyone{' '}
              {mode === 'share' ? (
                <span className="ev-help-inline">Everyone in this CRM</span>
              ) : null}
            </label>
          </fieldset>
        </div>
        <div className="modal__footer">
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Cancel
          </button>
          <button
            type="submit"
            className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
            disabled={busy}
          >
            Save
          </button>
        </div>
      </form>
    </CrmModal>
  );
}
