'use client';

import { useState } from 'react';
import Link from 'next/link';
import { CheckCircle, XCircle, AlertCircle, Loader2, Users, ArrowRight, Info, ChevronRight } from 'lucide-react';
import AppLogo from '@client/components/ui/AppLogo';
import { usePublicBranding } from '@client/hooks/usePublicBranding';

interface UserResult {
  email: string;
  status: 'created' | 'already_exists' | 'error' | 'pending' | 'loading';
  error?: string;
  needs_confirmation?: boolean;
  loginVerified?: boolean;
}

const DEMO_ACCOUNTS = [
  {
    label: 'Restaurant Owner',
    email: 'demo@restroagent.com',
    password: 'demo123456',
    description: 'Access restaurant dashboard, orders, bookings, and AI agent config',
    color: 'hsl(22, 89%, 48%)',
    bg: 'hsl(22, 89%, 97%)',
    border: 'hsl(22, 89%, 85%)',
  },
  {
    label: 'Admin Panel',
    email: 'admin@restroagent.com',
    password: 'admin123456',
    description: 'Access platform-wide admin dashboard, billing, and restaurant management',
    color: 'hsl(231, 60%, 48%)',
    bg: 'hsl(231, 60%, 97%)',
    border: 'hsl(231, 60%, 85%)',
  },
];

function StatusIcon({ status }: { status: UserResult['status'] }) {
  if (status === 'loading') return <Loader2 size={18} className="animate-spin text-blue-500" />;
  if (status === 'created') return <CheckCircle size={18} className="text-green-500" />;
  if (status === 'already_exists') return <CheckCircle size={18} className="text-blue-500" />;
  if (status === 'error') return <XCircle size={18} className="text-red-500" />;
  return null;
}

function StatusLabel({ status, error, loginVerified, needs_confirmation }: {
  status: UserResult['status'];
  error?: string;
  loginVerified?: boolean;
  needs_confirmation?: boolean;
}) {
  if (status === 'loading') return <span className="text-sm text-blue-600">Creating…</span>;
  if (status === 'created') {
    if (needs_confirmation) return <span className="text-sm font-medium text-amber-600">Created — email confirmation required</span>;
    return <span className="text-sm font-medium text-green-600">Created & verified {loginVerified ? '✓ Login works' : ''}</span>;
  }
  if (status === 'already_exists') {
    if (needs_confirmation) return <span className="text-sm font-medium text-amber-600">Exists — email confirmation required</span>;
    return <span className="text-sm font-medium text-blue-600">Already exists — ready {loginVerified ? '✓ Login works' : ''}</span>;
  }
  if (status === 'error') return <span className="text-sm font-medium text-red-600">Error: {error || 'Unknown error'}</span>;
  return null;
}

export default function DemoSetupPage() {
  const { logoUrl, siteTitle } = usePublicBranding();
  const [userResults, setUserResults] = useState<Record<string, UserResult>>({});
  const [globalError, setGlobalError] = useState<string | null>(null);
  const [globalNote, setGlobalNote] = useState<string | null>(null);
  const [isRunning, setIsRunning] = useState(false);
  const [isDone, setIsDone] = useState(false);
  const [needsConfirmation, setNeedsConfirmation] = useState(false);

  const handleCreateDemoUsers = async () => {
    setIsRunning(true);
    setGlobalError(null);
    setGlobalNote(null);
    setIsDone(false);
    setNeedsConfirmation(false);

    const loadingState: Record<string, UserResult> = {};
    DEMO_ACCOUNTS.forEach(a => {
      loadingState[a.email] = { email: a.email, status: 'loading' };
    });
    setUserResults(loadingState);

    try {
      const res = await fetch('/api/auth/seed-demo-users', { method: 'POST' });

      let data: any;
      try {
        data = await res.json();
      } catch {
        setGlobalError('Server returned an unexpected response. Please check your configuration.');
        const errorState: Record<string, UserResult> = {};
        DEMO_ACCOUNTS.forEach(a => {
          errorState[a.email] = { email: a.email, status: 'error', error: 'Invalid server response' };
        });
        setUserResults(errorState);
        setIsRunning(false);
        return;
      }

      if (data.error && !data.results) {
        setGlobalError(data.error);
        const errorState: Record<string, UserResult> = {};
        DEMO_ACCOUNTS.forEach(a => {
          errorState[a.email] = { email: a.email, status: 'error', error: data.error };
        });
        setUserResults(errorState);
        setIsRunning(false);
        return;
      }

      const newResults: Record<string, UserResult> = {};
      (data.results ?? []).forEach((r: any) => {
        newResults[r.email] = {
          email: r.email,
          status: r.status as UserResult['status'],
          error: r.error,
          loginVerified: r.loginVerified,
          needs_confirmation: r.needs_confirmation,
        };
      });
      setUserResults(newResults);

      if (data.needs_confirmation) {
        setNeedsConfirmation(true);
        setGlobalNote(data.note ?? null);
      } else if (data.note && !data.usedServiceRole) {
        setGlobalNote(data.note);
      }

      const allReady = Object.values(newResults).every(
        r => (r.status === 'created' || r.status === 'already_exists') && !r.needs_confirmation
      );
      setIsDone(allReady);
    } catch (err: any) {
      setGlobalError(err?.message || 'Network error. Please try again.');
      const errorState: Record<string, UserResult> = {};
      DEMO_ACCOUNTS.forEach(a => {
        errorState[a.email] = { email: a.email, status: 'error', error: 'Network error' };
      });
      setUserResults(errorState);
    } finally {
      setIsRunning(false);
    }
  };

  const hasAnyResult = Object.keys(userResults).length > 0;

  return (
    <div className="min-h-screen flex items-center justify-center p-6" style={{ backgroundColor: 'hsl(var(--background))' }}>
      <div className="w-full max-w-lg">
        {/* Header */}
        <div className="flex items-center gap-3 mb-8">
          <AppLogo src={logoUrl || undefined} size={32} />
          <span className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{siteTitle}</span>
        </div>

        <div className="rounded-2xl border p-6 shadow-sm" style={{ backgroundColor: 'hsl(var(--card))', borderColor: 'hsl(var(--border))' }}>
          <div className="flex items-center gap-3 mb-2">
            <div className="w-9 h-9 rounded-xl flex items-center justify-center" style={{ backgroundColor: 'hsl(231, 60%, 97%)' }}>
              <Users size={18} style={{ color: 'hsl(231, 60%, 48%)' }} />
            </div>
            <h1 className="text-xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>Demo Setup</h1>
          </div>
          <p className="text-sm mb-6" style={{ color: 'hsl(var(--muted-foreground))' }}>
            Initialize demo accounts to explore RestroAgent without signing up.
          </p>

          {/* Info banner */}
          <div className="flex gap-2 p-3 rounded-xl mb-6 text-sm" style={{ backgroundColor: 'hsl(210, 100%, 97%)', border: '1px solid hsl(210, 100%, 88%)', color: 'hsl(210, 100%, 35%)' }}>
            <Info size={15} className="mt-0.5 shrink-0" />
            <span>This creates two demo accounts in the database. Safe to run multiple times — existing accounts are skipped.</span>
          </div>

          {/* Demo accounts */}
          <div className="space-y-3 mb-6">
            {DEMO_ACCOUNTS.map(account => {
              const result = userResults[account.email];
              return (
                <div
                  key={account.email}
                  className="rounded-xl p-4 border"
                  style={{ backgroundColor: account.bg, borderColor: account.border }}
                >
                  <div className="flex items-start justify-between gap-2">
                    <div className="flex-1 min-w-0">
                      <p className="font-semibold text-sm mb-1" style={{ color: account.color }}>{account.label}</p>
                      <p className="text-xs mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{account.description}</p>
                      <div className="space-y-0.5">
                        <p className="text-xs" style={{ color: 'hsl(var(--foreground))' }}>
                          <span className="font-medium">Email:</span>{' '}
                          <span style={{ color: 'hsl(var(--muted-foreground))' }}>{account.email}</span>
                        </p>
                        <p className="text-xs" style={{ color: 'hsl(var(--foreground))' }}>
                          <span className="font-medium">Password:</span>{' '}
                          <span style={{ color: 'hsl(var(--muted-foreground))' }}>{account.password}</span>
                        </p>
                      </div>
                    </div>
                    {result && result.status !== 'pending' && (
                      <div className="flex items-center gap-1.5 shrink-0 mt-1">
                        <StatusIcon status={result.status} />
                      </div>
                    )}
                  </div>
                  {result && result.status !== 'pending' && (
                    <div className="mt-2 pt-2 border-t" style={{ borderColor: account.border }}>
                      <StatusLabel
                        status={result.status}
                        error={result.error}
                        loginVerified={result.loginVerified}
                        needs_confirmation={result.needs_confirmation}
                      />
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          

          {/* Global error */}
          {globalError && (
            <div className="flex items-start gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(0, 84%, 97%)', color: 'hsl(0, 84%, 44%)', border: '1px solid hsl(0, 84%, 90%)' }}>
              <AlertCircle size={15} className="mt-0.5 shrink-0" />
              <div>
                <p className="font-medium mb-0.5">Setup failed</p>
                <p>{globalError}</p>
              </div>
            </div>
          )}

          {/* Global note (anon fallback info) */}
          {globalNote && !needsConfirmation && (
            <div className="flex items-start gap-2 p-3 rounded-xl mb-4 text-sm" style={{ backgroundColor: 'hsl(210, 100%, 97%)', color: 'hsl(210, 100%, 35%)', border: '1px solid hsl(210, 100%, 88%)' }}>
              <Info size={15} className="mt-0.5 shrink-0" />
              <p>{globalNote}</p>
            </div>
          )}

          {/* Action buttons */}
          <div className="space-y-3">
            {!isDone ? (
              <button
                onClick={handleCreateDemoUsers}
                disabled={isRunning}
                className="w-full flex items-center justify-center gap-2 py-2.5 px-4 rounded-xl font-semibold text-sm transition-opacity disabled:opacity-60"
                style={{ backgroundColor: 'hsl(231, 60%, 48%)', color: '#fff' }}
              >
                {isRunning ? (
                  <>
                    <Loader2 size={16} className="animate-spin" />
                    Creating demo users…
                  </>
                ) : (
                  <>
                    <Users size={16} />
                    {hasAnyResult ? 'Retry Create Demo Users' : 'Create Demo Users'}
                  </>
                )}
              </button>
            ) : (
              <div className="flex items-center gap-2 p-3 rounded-xl text-sm font-medium" style={{ backgroundColor: 'hsl(142, 71%, 95%)', color: 'hsl(142, 71%, 30%)', border: '1px solid hsl(142, 71%, 80%)' }}>
                <CheckCircle size={16} />
                All demo accounts are ready! Login is verified ✓
              </div>
            )}

            {isDone && (
              <Link
                href="/login"
                className="w-full flex items-center justify-center gap-2 py-2.5 px-4 rounded-xl font-semibold text-sm transition-opacity"
                style={{ backgroundColor: 'hsl(22, 89%, 48%)', color: '#fff' }}
              >
                Go to Login
                <ArrowRight size={16} />
              </Link>
            )}

            <Link
              href="/login"
              className="w-full flex items-center justify-center gap-2 py-2 px-4 rounded-xl text-sm font-medium transition-opacity"
              style={{ color: 'hsl(var(--muted-foreground))', border: '1px solid hsl(var(--border))' }}
            >
              Back to Login
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
