// frontend/src/pages/Auth.jsx
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext.jsx';
import { Button, Input } from '../components/ui/index.jsx';
import { Zap } from 'lucide-react';
import toast from 'react-hot-toast';

function AuthLayout({ children, title, subtitle }) {
  return (
    <div className="min-h-screen bg-gray-950 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="flex items-center justify-center gap-2 mb-8">
          <div className="w-9 h-9 bg-brand-500 rounded-xl flex items-center justify-center">
            <Zap size={18} className="text-white" />
          </div>
          <span className="text-white font-semibold text-lg tracking-tight">Content Machine</span>
        </div>

        <div className="bg-white rounded-2xl shadow-2xl p-8">
          <h1 className="text-xl font-semibold text-gray-900 mb-1">{title}</h1>
          <p className="text-sm text-gray-500 mb-6">{subtitle}</p>
          {children}
        </div>
      </div>
    </div>
  );
}

export function LoginPage() {
  const { login } = useAuth();
  const navigate = useNavigate();
  const [form, setForm] = useState({ email: '', password: '' });
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});

  const handleSubmit = async (e) => {
    e.preventDefault();
    setErrors({});
    setLoading(true);
    try {
      const user = await login(form.email, form.password);
      if (user.role === 'superadmin') navigate('/admin');
      else navigate('/dashboard');
    } catch (err) {
      const msg = err.response?.data?.message || 'Invalid email or password';
      setErrors({ form: msg });
      toast.error(msg);
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthLayout title="Welcome back" subtitle="Sign in to your Content Machine account">
      <form onSubmit={handleSubmit} className="space-y-4">
        {errors.form && (
          <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 text-sm text-red-700">
            {errors.form}
          </div>
        )}
        <Input
          label="Email"
          type="email"
          value={form.email}
          onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
          placeholder="you@example.com"
          required
        />
        <Input
          label="Password"
          type="password"
          value={form.password}
          onChange={e => setForm(f => ({ ...f, password: e.target.value }))}
          placeholder="••••••••"
          required
        />
        <div className="flex justify-end">
          <Link to="/forgot-password" className="text-xs text-brand-600 hover:text-brand-700">Forgot password?</Link>
        </div>
        <Button type="submit" loading={loading} className="w-full">
          Sign in
        </Button>
        <p className="text-center text-sm text-gray-500">
          Don't have an account?{' '}
          <Link to="/register" className="text-brand-600 hover:text-brand-700 font-medium">Get started</Link>
        </p>
      </form>
    </AuthLayout>
  );
}

export function RegisterPage() {
  const { register } = useAuth();
  const navigate = useNavigate();
  const [form, setForm] = useState({ fullName: '', email: '', password: '', planId: 'starter', locale: 'en' });
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState({});

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (form.password.length < 8) { setErrors({ password: 'Min 8 characters' }); return; }
    setLoading(true);
    try {
      await register(form);
      navigate('/dashboard');
      toast.success('Welcome! Your 14-day trial has started 🎉');
    } catch (err) {
      const msg = err.response?.data?.message || 'Registration failed';
      setErrors({ form: msg });
    } finally {
      setLoading(false);
    }
  };

  return (
    <AuthLayout title="Start your free trial" subtitle="14 days free, no commitment">
      <form onSubmit={handleSubmit} className="space-y-4">
        {errors.form && (
          <div className="bg-red-50 border border-red-200 rounded-lg px-4 py-3 text-sm text-red-700">{errors.form}</div>
        )}
        <Input label="Full name" value={form.fullName} onChange={e => setForm(f => ({ ...f, fullName: e.target.value }))} placeholder="Jane Smith" required />
        <Input label="Email" type="email" value={form.email} onChange={e => setForm(f => ({ ...f, email: e.target.value }))} placeholder="you@example.com" required />
        <Input label="Password" type="password" value={form.password} onChange={e => setForm(f => ({ ...f, password: e.target.value }))} placeholder="Min 8 characters" error={errors.password} required />

        {/* Plan selector */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">Plan</label>
          <div className="grid grid-cols-3 gap-2">
            {[
              { id: 'starter', name: 'Starter', price: '$29' },
              { id: 'pro', name: 'Pro', price: '$79' },
              { id: 'agency', name: 'Agency', price: '$199' },
            ].map(p => (
              <button
                key={p.id}
                type="button"
                onClick={() => setForm(f => ({ ...f, planId: p.id }))}
                className={`p-3 rounded-xl border-2 text-left transition-all ${
                  form.planId === p.id
                    ? 'border-brand-500 bg-brand-50'
                    : 'border-gray-200 hover:border-gray-300'
                }`}
              >
                <p className="text-xs font-semibold text-gray-900">{p.name}</p>
                <p className="text-xs text-gray-400">{p.price}/mo</p>
              </button>
            ))}
          </div>
        </div>

        {/* Language */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Language</label>
          <div className="flex gap-2">
            {[{ val: 'en', label: '🇬🇧 English' }, { val: 'ro', label: '🇷🇴 Română' }].map(l => (
              <button
                key={l.val}
                type="button"
                onClick={() => setForm(f => ({ ...f, locale: l.val }))}
                className={`flex-1 py-2 rounded-lg border text-sm transition-all ${
                  form.locale === l.val ? 'border-brand-500 bg-brand-50 text-brand-700' : 'border-gray-200 text-gray-600'
                }`}
              >
                {l.label}
              </button>
            ))}
          </div>
        </div>

        <Button type="submit" loading={loading} className="w-full mt-2">
          Start free trial →
        </Button>
        <p className="text-center text-xs text-gray-400">
          14 days free. Cancel anytime. Card required to activate.
        </p>
        <p className="text-center text-sm text-gray-500">
          Already have an account?{' '}
          <Link to="/login" className="text-brand-600 hover:text-brand-700 font-medium">Sign in</Link>
        </p>
      </form>
    </AuthLayout>
  );
}
