'use client';

import { RotateCcw } from 'lucide-react';

import { useChatReset } from '../../hooks/useChatReset';
import { ChatHeaderActionButton } from './ChatHeaderActionButton';

export interface ChatHeaderResetButtonProps {
  /**
   * Backend reset call. Should resolve to `true` on success.
   * Plugged into `useChatReset` for in-flight state.
   */
  onReset: () => Promise<boolean>;
  /** Called after a successful reset (e.g. clear local messages, refetch). */
  onSuccess?: () => void;
  /** Called when reset fails (returned `false` or threw). */
  onError?: (error?: unknown) => void;
  /**
   * Show a `window.dialog.confirm` before calling `onReset`. @default true
   *
   * Requires the host to mount `<DialogProvider>` from `@djangocfg/ui-core`
   * — it installs the `window.dialog` API used here.
   */
  confirm?: boolean;
  /** Confirm dialog title. */
  confirmTitle?: string;
  /** Confirm dialog message. */
  confirmMessage?: string;
  /** Override tooltip / aria label. */
  ariaLabel?: string;
}

const DEFAULT_TITLE = 'Clear conversation?';
const DEFAULT_MESSAGE =
  'The assistant will forget this session and start a new one. This cannot be undone.';
const DEFAULT_LABEL = 'Clear conversation';

/**
 * Standard chat-reset action: prompts the user via `window.dialog.confirm`,
 * then runs the backend reset call through `useChatReset` so the button
 * spins while it's in flight.
 *
 * @example
 * ```tsx
 * <ChatHeaderResetButton
 *   onReset={api.clearChat}
 *   onSuccess={() => chat.clearMessages()}
 * />
 * ```
 */
export function ChatHeaderResetButton({
  onReset,
  onSuccess,
  onError,
  confirm = true,
  confirmTitle = DEFAULT_TITLE,
  confirmMessage = DEFAULT_MESSAGE,
  ariaLabel = DEFAULT_LABEL,
}: ChatHeaderResetButtonProps) {
  const { reset, isResetting } = useChatReset({ onReset, onSuccess, onError });

  const handleClick = async () => {
    if (confirm) {
      const api = typeof window !== 'undefined' ? window.dialog : undefined;
      if (api?.confirm) {
        const ok = await api.confirm({
          title: confirmTitle,
          message: confirmMessage,
          variant: 'destructive',
          confirmText: 'Clear',
          cancelText: 'Cancel',
        });
        if (!ok) return;
      } else if (typeof window !== 'undefined' && typeof window.confirm === 'function') {
        // Fallback to the native browser confirm when the dialog service
        // isn't wired (e.g. host forgot to mount DialogProvider).
        const ok = window.confirm(`${confirmTitle}\n\n${confirmMessage}`);
        if (!ok) return;
      }
    }
    await reset();
  };

  return (
    <ChatHeaderActionButton
      icon={<RotateCcw className="h-3.5 w-3.5" />}
      ariaLabel={ariaLabel}
      tooltip="Reset conversation"
      onClick={handleClick}
      loading={isResetting}
      destructive
    />
  );
}
