import React from 'react';
import type { FallbackProps } from './error-boundary';

// ─────────────────────────────────────────────────────────────────────────────
// error-fallbacks.tsx
//
// Three UI fallbacks for the three ErrorBoundary variants.
// All are intentionally kept dependency-light (no xertica-ui imports) so they
// work even if the library itself fails to load.
// ─────────────────────────────────────────────────────────────────────────────

// ── Shared helpers ────────────────────────────────────────────────────────────

function isDev() {
  return import.meta.env.DEV;
}

// ── AppErrorFallback — root crash ─────────────────────────────────────────────

/**
 * Full-screen fallback for root-level crashes.
 * Shown when a provider or the app shell itself throws.
 */
export function AppErrorFallback({ error, reset }: FallbackProps) {
  return (
    <div
      role="alert"
      style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        minHeight: '100vh',
        padding: '2rem',
        background: 'var(--background, #f8f9fa)',
        color: 'var(--foreground, #1a1a1a)',
        fontFamily: 'system-ui, sans-serif',
        textAlign: 'center',
        gap: '1rem',
      }}
    >
      {/* Icon */}
      <svg
        width="48"
        height="48"
        viewBox="0 0 24 24"
        fill="none"
        stroke="var(--destructive, #ef4444)"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        aria-hidden="true"
      >
        <circle cx="12" cy="12" r="10" />
        <line x1="12" y1="8" x2="12" y2="12" />
        <line x1="12" y1="16" x2="12.01" y2="16" />
      </svg>

      <h1 style={{ fontSize: '1.5rem', fontWeight: 700, margin: 0 }}>Algo deu errado</h1>
      <p style={{ color: 'var(--muted-foreground, #6b7280)', maxWidth: 420, margin: 0 }}>
        Ocorreu um erro inesperado na aplicação. Tente recarregar a página ou entre em contato com o
        suporte se o problema persistir.
      </p>

      {isDev() && (
        <pre
          style={{
            background: 'var(--muted, #f3f4f6)',
            border: '1px solid var(--border, #e5e7eb)',
            borderRadius: 8,
            padding: '0.75rem 1rem',
            fontSize: '0.75rem',
            textAlign: 'left',
            maxWidth: 600,
            overflowX: 'auto',
            whiteSpace: 'pre-wrap',
            wordBreak: 'break-word',
          }}
        >
          {error.message}
          {error.stack ? `\n\n${error.stack}` : ''}
        </pre>
      )}

      <div style={{ display: 'flex', gap: '0.75rem', flexWrap: 'wrap', justifyContent: 'center' }}>
        <button
          onClick={reset}
          style={{
            padding: '0.5rem 1.25rem',
            borderRadius: 6,
            border: '1px solid var(--border, #e5e7eb)',
            background: 'transparent',
            cursor: 'pointer',
            fontSize: '0.875rem',
            color: 'var(--foreground, #1a1a1a)',
          }}
        >
          Tentar novamente
        </button>
        <button
          onClick={() => window.location.assign('/')}
          style={{
            padding: '0.5rem 1.25rem',
            borderRadius: 6,
            border: 'none',
            background: 'var(--primary, #2563eb)',
            color: 'var(--primary-foreground, #fff)',
            cursor: 'pointer',
            fontSize: '0.875rem',
          }}
        >
          Ir para o início
        </button>
      </div>
    </div>
  );
}

// ── PageErrorFallback — route-level crash ─────────────────────────────────────

/**
 * Page-area fallback. Shown when a lazy chunk fails to load or a page
 * component throws. The app shell (header, sidebar) remains intact.
 */
export function PageErrorFallback({ error, reset }: FallbackProps) {
  return (
    <div
      role="alert"
      className="flex flex-col items-center justify-center flex-1 min-h-[400px] p-8 gap-4 text-center"
    >
      <svg
        width="40"
        height="40"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        className="text-destructive"
        aria-hidden="true"
      >
        <path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
        <line x1="12" y1="9" x2="12" y2="13" />
        <line x1="12" y1="17" x2="12.01" y2="17" />
      </svg>

      <div className="space-y-1">
        <h2 className="text-lg font-semibold">Erro ao carregar página</h2>
        <p className="text-sm text-muted-foreground max-w-sm">
          Esta página encontrou um problema. Clique em "Tentar novamente" ou navegue para outra
          seção.
        </p>
      </div>

      {isDev() && (
        <pre className="text-left text-xs bg-muted border border-border rounded-lg p-3 max-w-lg w-full overflow-x-auto whitespace-pre-wrap break-words">
          {error.message}
        </pre>
      )}

      <div className="flex gap-3 flex-wrap justify-center">
        <button
          onClick={reset}
          className="inline-flex items-center px-4 py-2 text-sm rounded-[var(--radius-button)] border border-border bg-transparent hover:bg-accent hover:text-accent-foreground transition-colors"
        >
          Tentar novamente
        </button>
        <button
          onClick={() => window.location.assign('/')}
          className="inline-flex items-center px-4 py-2 text-sm rounded-[var(--radius-button)] bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"
        >
          Ir para o início
        </button>
      </div>
    </div>
  );
}

// ── SectionErrorFallback — feature/section-level crash ────────────────────────

/**
 * Compact inline fallback for section-level errors (data tables, charts,
 * the assistant panel, etc.). Prevents one broken section from crashing the page.
 */
export function SectionErrorFallback({ error, reset }: FallbackProps) {
  return (
    <div
      role="alert"
      className="flex flex-col items-center justify-center gap-3 p-6 rounded-[var(--radius-lg)] border border-destructive/30 bg-destructive/5 text-center"
    >
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
        className="text-destructive shrink-0"
        aria-hidden="true"
      >
        <circle cx="12" cy="12" r="10" />
        <line x1="12" y1="8" x2="12" y2="12" />
        <line x1="12" y1="16" x2="12.01" y2="16" />
      </svg>

      <div className="space-y-1">
        <p className="text-sm font-medium">Não foi possível carregar este conteúdo</p>
        {isDev() && <p className="text-xs text-muted-foreground font-mono">{error.message}</p>}
      </div>

      <button
        onClick={reset}
        className="inline-flex items-center px-3 py-1.5 text-xs rounded-[var(--radius-button)] border border-border bg-background hover:bg-accent hover:text-accent-foreground transition-colors"
      >
        Tentar novamente
      </button>
    </div>
  );
}
