'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { Loader2, ArrowRight, AlertCircle } from 'lucide-react';
import {
  DEMO_OWNER_EMAIL, DEMO_OWNER_PASSWORD,
  DEMO_ADMIN_EMAIL, DEMO_ADMIN_PASSWORD,
} from '@/lib/demoMode';

export type LaunchTarget = 'owner' | 'admin';

interface Account {
  email: string;
  password: string;
  redirect: string;
}

const ACCOUNTS: Record<LaunchTarget, Account> = {
  owner: { email: DEMO_OWNER_EMAIL, password: DEMO_OWNER_PASSWORD, redirect: '/restaurant-dashboard' },
  admin: { email: DEMO_ADMIN_EMAIL, password: DEMO_ADMIN_PASSWORD, redirect: '/admin/dashboard' },
};

export type LaunchStatus = 'idle' | 'seeding' | 'signing' | 'redirecting' | 'error';

export function useDemoLaunch(target: LaunchTarget, redirectOverride?: string) {
  const router = useRouter();
  const [status, setStatus] = useState<LaunchStatus>('idle');
  const [error, setError] = useState<string | null>(null);
  const account = ACCOUNTS[target];
  const targetRoute = redirectOverride ?? account.redirect;

  const launch = async () => {
    setStatus('seeding');
    setError(null);
    try {
      // Seed demo users (idempotent). Network/seed errors are non-fatal —
      // sign-in surfaces the real failure below.
      try {
        await fetch('/api/auth/seed-demo-users', { method: 'POST' });
      } catch {
        /* ignore */
      }

      setStatus('signing');
      const res = await fetch('/api/auth/sign-in', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: account.email, password: account.password }),
      });

      if (!res.ok) {
        const data = await res.json().catch(() => ({} as { error?: string }));
        const msg = data?.error || `Sign-in failed (HTTP ${res.status})`;
        setError(msg);
        setStatus('error');
        toast.error(`Auto sign-in failed: ${msg}. Sending you to login…`);
        setTimeout(() => router.push(`/login?email=${encodeURIComponent(account.email)}`), 1500);
        return;
      }

      setStatus('redirecting');
      router.push(targetRoute);
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Network error';
      setError(msg);
      setStatus('error');
      toast.error(`Demo launch failed: ${msg}. Sending you to login…`);
      setTimeout(() => router.push(`/login?email=${encodeURIComponent(account.email)}`), 1500);
    }
  };

  const busy = status === 'seeding' || status === 'signing' || status === 'redirecting';
  return { status, error, busy, launch, account };
}

interface DemoLaunchButtonProps {
  target: LaunchTarget;
  label: string;
  description: string;
  primary?: boolean;
  icon: React.ReactNode;
  redirectOverride?: string;
}

export default function DemoLaunchButton({
  target, label, description, primary, icon, redirectOverride,
}: DemoLaunchButtonProps) {
  const { status, error, busy, launch } = useDemoLaunch(target, redirectOverride);

  return (
    <button
      type="button"
      onClick={launch}
      disabled={busy}
      aria-label={label}
      className={`group relative w-full flex items-center justify-center gap-2 px-6 py-3.5 rounded-xl font-semibold text-sm transition-all duration-200 active:scale-[0.98] disabled:opacity-80 disabled:cursor-wait ${
        primary
          ? 'bg-orange-500 hover:bg-orange-600 text-white shadow-lg shadow-orange-500/30 hover:-translate-y-0.5 hover:shadow-orange-500/40'
          : 'bg-slate-900 dark:bg-white text-white dark:text-slate-900 hover:bg-slate-800 dark:hover:bg-slate-100 shadow-md hover:-translate-y-0.5'
      }`}
    >
      {busy ? (
        <>
          <Loader2 size={16} className="animate-spin" />
          {status === 'seeding' && 'Preparing demo data…'}
          {status === 'signing' && 'Signing you in…'}
          {status === 'redirecting' && 'Loading dashboard…'}
        </>
      ) : status === 'error' ? (
        <>
          <AlertCircle size={16} />
          {error || 'Sign-in failed'} — sending you to login…
        </>
      ) : (
        <>
          <span className="shrink-0">{icon}</span>
          <span className="flex flex-col items-start text-left">
            <span>{label}</span>
            <span className={`text-[11px] font-normal opacity-80 ${primary ? 'text-white/85' : 'text-white/85 dark:text-slate-700'}`}>{description}</span>
          </span>
          <ArrowRight size={16} className="ml-1 transition-transform group-hover:translate-x-0.5" />
        </>
      )}
    </button>
  );
}

interface DemoLaunchCardProps {
  target: LaunchTarget;
  redirect: string;
  icon: React.ReactNode;
  title: string;
  description: string;
  ringClass: string;
}

export function DemoLaunchCard({ target, redirect, icon, title, description, ringClass }: DemoLaunchCardProps) {
  const { status, busy, launch } = useDemoLaunch(target, redirect);

  return (
    <button
      type="button"
      onClick={launch}
      disabled={busy}
      aria-label={`Open ${title} in demo`}
      className={`group text-left rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-5 transition-all duration-200 hover:-translate-y-0.5 hover:shadow-lg hover:ring-2 ${ringClass} disabled:opacity-70 disabled:cursor-wait`}
    >
      <div className="flex items-start gap-3 mb-3">
        {icon}
        <div className="flex-1 min-w-0">
          <h3 className="font-bold text-sm text-slate-900 dark:text-white">{title}</h3>
          <p className="text-xs text-slate-500 dark:text-slate-400 mt-0.5 leading-relaxed">{description}</p>
        </div>
      </div>
      <div className="flex items-center gap-1.5 text-xs font-semibold text-orange-600 dark:text-orange-400">
        {busy ? (
          <>
            <Loader2 size={13} className="animate-spin" /> Launching…
          </>
        ) : status === 'error' ? (
          <>
            <AlertCircle size={13} /> Redirecting to login…
          </>
        ) : (
          <>
            Open in demo
            <ArrowRight size={13} className="transition-transform group-hover:translate-x-0.5" />
          </>
        )}
      </div>
    </button>
  );
}
