import { useEffect } from 'react';
import { Loader2, AlertCircle, Inbox, CheckCircle2, XCircle, Info, X } from 'lucide-react';
import { Card, CardBody } from './Card';
import { cn } from '@/lib/cn';

export function Loading({ label = 'Loading…' }: { label?: string }) {
  return (
    <Card>
      <CardBody className="flex items-center gap-3 text-sm text-ink-500">
        <Loader2 className="h-4 w-4 animate-spin" />
        {label}
      </CardBody>
    </Card>
  );
}

export function ErrorState({ error, onRetry }: { error: Error; onRetry?: () => void }) {
  return (
    <Card>
      <CardBody>
        <div className="flex items-start gap-3">
          <AlertCircle className="h-5 w-5 text-danger shrink-0 mt-0.5" />
          <div className="flex-1">
            <p className="text-sm font-medium text-ink-900">Something went wrong</p>
            <p className="text-xs text-ink-500 mt-1">{error.message}</p>
            {onRetry && (
              <button onClick={onRetry} className="mt-3 text-xs font-medium text-brand-700 hover:underline">
                Try again
              </button>
            )}
          </div>
        </div>
      </CardBody>
    </Card>
  );
}

export function Empty({ icon, title, hint, action }: { icon?: React.ReactNode; title: string; hint?: string; action?: React.ReactNode }) {
  return (
    <Card>
      <CardBody className="text-center py-12">
        <div className="mx-auto h-10 w-10 grid place-items-center rounded-xl bg-ink-100 text-ink-600 mb-3">
          {icon ?? <Inbox className="h-5 w-5" />}
        </div>
        <p className="text-sm font-medium text-ink-900">{title}</p>
        {hint && <p className="text-xs text-ink-500 mt-1">{hint}</p>}
        {action && <div className="mt-4 inline-flex justify-center">{action}</div>}
      </CardBody>
    </Card>
  );
}

/**
 * Toast notification. Auto-dismisses after `duration` ms (default depends on
 * tone — see below). Slides in from the right with a subtle entrance animation.
 *
 * Tone-aware defaults: danger toasts STAY until the user dismisses them. Error
 * messages can be 200+ characters of actionable detail (e.g. "open ports
 * 49152-65534 on the WP host's outbound firewall, or switch to SFTP") and a
 * 4-second dismiss makes those impossible to read.
 */
export function Toast({
  message,
  tone = 'success',
  onClose,
  duration,
}: {
  message: string;
  tone?: 'success' | 'danger' | 'neutral';
  onClose: () => void;
  /** Override the tone default. `0` = sticky (no auto-dismiss). */
  duration?: number;
}) {
  // Resolve the effective duration. Sticky for errors (so the user can read
  // the actionable hint) — short for success/neutral so they stop blocking the
  // UI quickly. Caller can pass `duration` explicitly to override.
  const effective = duration ?? (tone === 'danger' ? 0 : 4000);
  useEffect(() => {
    if (effective <= 0) return;
    const t = window.setTimeout(onClose, effective);
    return () => window.clearTimeout(t);
  }, [effective, onClose]);

  const config = {
    success: {
      icon: <CheckCircle2 className="h-5 w-5 text-emerald-500" />,
      ring: 'ring-emerald-100',
      iconBg: 'bg-emerald-50',
    },
    danger: {
      icon: <XCircle className="h-5 w-5 text-red-500" />,
      ring: 'ring-red-100',
      iconBg: 'bg-red-50',
    },
    neutral: {
      icon: <Info className="h-5 w-5 text-ink-600" />,
      ring: 'ring-ink-100',
      iconBg: 'bg-ink-50',
    },
  }[tone];

  return (
    <div
      role="status"
      aria-live="polite"
      className={cn(
        'fixed bottom-6 right-6 z-[100001] min-w-[280px] max-w-sm',
        'rounded-xl bg-white shadow-pop ring-1',
        'flex items-center gap-3 pl-3 pr-2 py-2.5',
        'animate-[backreload-slide-in_180ms_ease-out]',
        config.ring,
      )}
    >
      <span className={cn('h-8 w-8 rounded-lg grid place-items-center shrink-0', config.iconBg)}>
        {config.icon}
      </span>
      <p className="flex-1 text-sm text-ink-900">{message}</p>
      <button
        onClick={onClose}
        className="h-7 w-7 grid place-items-center rounded-md text-ink-400 hover:text-ink-900 hover:bg-ink-50"
        aria-label="Dismiss"
      >
        <X className="h-4 w-4" />
      </button>
    </div>
  );
}
