'use client';

import { FormEvent, useState } from 'react';
import { fetchWithAuth } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? '';

export default function AdminUserPage() {
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<{ id: string; email: string; created_at: string } | null>(null);
  const [error, setError] = useState<string | null>(null);

  // Auth guard is handled by the parent admin layout

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setResult(null);
    setError(null);

    const trimmedEmail = email.trim().toLowerCase();
    if (!trimmedEmail || !trimmedEmail.includes('@')) {
      setError(t('admin.user.errorEmail'));
      return;
    }
    if (password.length < 8) {
      setError(t('admin.user.errorPasswordLength'));
      return;
    }

    setLoading(true);
    try {
      const res = await fetchWithAuth(`${API_BASE}/api/admin/users`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: trimmedEmail, password }),
      });
      const body = await res.json().catch(() => ({}));
      if (!res.ok) {
        throw new Error(body?.detail ?? `HTTP ${res.status}`);
      }
      setResult(body);
      setEmail('');
      setPassword('');
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : t('admin.user.errorCreate'));
    } finally {
      setLoading(false);
    }
  }

  const card: React.CSSProperties = {
    background: '#fff',
    borderRadius: 12,
    boxShadow: '0 2px 16px rgba(92,95,188,0.09)',
    padding: '28px 32px',
    marginBottom: 24,
  };

  const inputStyle: React.CSSProperties = {
    width: '100%',
    padding: '10px 12px',
    fontSize: 14,
    border: '1px solid #e5e7eb',
    borderRadius: 8,
    outline: 'none',
    boxSizing: 'border-box',
    marginTop: 6,
  };

  const labelStyle: React.CSSProperties = {
    fontSize: 13,
    fontWeight: 500,
    color: '#374151',
    display: 'block',
    marginBottom: 2,
  };

  return (
    <div style={{ maxWidth: 520, paddingTop: '8px' }}>
      {/* Page title */}
      <div style={{ marginBottom: 28 }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#1a1a2e' }}>
          {t('admin.user.title')}
        </h1>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: '#6b7280' }}>
          {t('admin.user.description')}
        </p>
      </div>

        {/* Form */}
        <div style={card}>
          <form onSubmit={handleSubmit} noValidate>
            <div style={{ marginBottom: 18 }}>
              <label style={labelStyle}>{t('admin.user.email')}</label>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="user@example.com"
                autoComplete="off"
                style={inputStyle}
              />
            </div>

            <div style={{ marginBottom: 24 }}>
              <label style={labelStyle}>{t('admin.user.password')}</label>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder={t('admin.user.passwordPlaceholder')}
                autoComplete="new-password"
                style={inputStyle}
              />
            </div>

            {error && (
              <div
                style={{
                  background: '#fef2f2',
                  border: '1px solid #fecaca',
                  color: '#b91c1c',
                  borderRadius: 8,
                  padding: '10px 14px',
                  fontSize: 13,
                  marginBottom: 16,
                }}
              >
                {error}
              </div>
            )}

            {result && (
              <div
                style={{
                  background: '#f0fdf4',
                  border: '1px solid #bbf7d0',
                  color: '#166534',
                  borderRadius: 8,
                  padding: '10px 14px',
                  fontSize: 13,
                  marginBottom: 16,
                }}
              >
                <strong>{t('admin.user.success')}</strong>
                <br />
                ID: <code style={{ fontSize: 12 }}>{result.id}</code>
                <br />
                Email: {result.email}
                <br />
                Created: {new Date(result.created_at).toLocaleString()}
              </div>
            )}

            <button
              type="submit"
              disabled={loading}
              style={{
                width: '100%',
                padding: '11px',
                background: loading ? '#a5b4fc' : '#5c5fbc',
                color: '#fff',
                border: 'none',
                borderRadius: 8,
                fontSize: 15,
                fontWeight: 600,
                cursor: loading ? 'not-allowed' : 'pointer',
                transition: 'background 0.15s',
              }}
            >
              {loading ? t('admin.user.creating') : t('admin.user.create')}
            </button>
          </form>
        </div>
    </div>
  );
}
