import React, { useState } from 'react';
import { api } from '../api';

export default function SetupWizard({ status, onStatusChange }) {
  const [step, setStep] = useState(status?.hasEmail ? 2 : 1);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  // Step 1: Email
  const [email, setEmail] = useState('');
  const [appPassword, setAppPassword] = useState('');
  const [smtpHost, setSmtpHost] = useState('smtp.gmail.com');
  const [smtpPort, setSmtpPort] = useState('587');
  const [emailVerified, setEmailVerified] = useState(false);

  // Step 2: Admin
  const [adminName, setAdminName] = useState('');
  const [adminEmail, setAdminEmail] = useState('');
  const [adminPassword, setAdminPassword] = useState('');

  const handleEmailSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      await api.setup.configureEmail({ smtp_host: smtpHost, smtp_port: parseInt(smtpPort), email, app_password });
      setEmailVerified(true);
      onStatusChange({ ...status, hasEmail: true });
      setTimeout(() => setStep(2), 600);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleAdminSubmit = async (e) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const data = await api.setup.createAdmin({ email: adminEmail, name: adminName, password: adminPassword });
      localStorage.setItem('teamflow_token', data.token);
      localStorage.setItem('teamflow_user', JSON.stringify(data.user));
      window.location.href = '/';
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-brand-600 via-brand-700 to-indigo-800 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="text-5xl mb-4">🌊</div>
          <h1 className="text-3xl font-bold text-white">Welcome to TeamFlow</h1>
          <p className="text-brand-200 mt-2">Set up your workspace in two quick steps</p>
        </div>

        {/* Progress */}
        <div className="flex items-center justify-center gap-4 mb-8">
          <StepDot num={1} active={step === 1} done={step > 1} label="Email" />
          <div className={`h-0.5 w-16 ${step > 1 ? 'bg-white' : 'bg-brand-500'}`} />
          <StepDot num={2} active={step === 2} done={false} label="Admin" />
        </div>

        <div className="bg-white rounded-2xl shadow-2xl p-8">
          {step === 1 && (
            <form onSubmit={handleEmailSubmit}>
              <h2 className="text-xl font-bold text-gray-900 mb-1">Configure Email</h2>
              <p className="text-sm text-gray-500 mb-6">Connect your email for notifications and inbound card creation</p>

              <div className="space-y-4">
                <div className="p-3 bg-blue-50 rounded-lg text-sm text-blue-700">
                  <strong> Gmail:</strong> Use an <a href="https://myaccount.google.com/apppasswords" target="_blank" className="underline font-medium">App Password</a> (not your regular password).
                  Enable 2FA first, then generate a 16-character app password.
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">SMTP Host</label>
                  <input type="text" value={smtpHost} onChange={e => setSmtpHost(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
                </div>
                <div className="flex gap-3">
                  <div className="flex-1">
                    <label className="block text-sm font-medium text-gray-700 mb-1">Port</label>
                    <select value={smtpPort} onChange={e => setSmtpPort(e.target.value)} className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent">
                      <option value="587">587 (TLS)</option>
                      <option value="465">465 (SSL)</option>
                    </select>
                  </div>
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Email Address</label>
                  <input type="email" value={email} onChange={e => setEmail(e.target.value)} required placeholder="you@gmail.com" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">App Password</label>
                  <input type="password" value={appPassword} onChange={e => setAppPassword(e.target.value)} required placeholder="xxxx xxxx xxxx xxxx" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent font-mono" />
                </div>
              </div>

              {error && <div className="mt-4 p-3 bg-red-50 rounded-lg text-sm text-red-700">{error}</div>}
              {emailVerified && <div className="mt-4 p-3 bg-green-50 rounded-lg text-sm text-green-700 font-medium">✅ Email verified! Moving to next step...</div>}

              <button type="submit" disabled={loading || emailVerified} className="mt-6 w-full bg-brand-600 text-white py-2.5 rounded-lg font-medium hover:bg-brand-700 disabled:opacity-50 transition-colors">
                {loading ? 'Verifying...' : 'Connect Email'}
              </button>
            </form>
          )}

          {step === 2 && (
            <form onSubmit={handleAdminSubmit}>
              <h2 className="text-xl font-bold text-gray-900 mb-1">Create Admin Account</h2>
              <p className="text-sm text-gray-500 mb-6">This is the first user with full administrative access</p>

              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Full Name</label>
                  <input type="text" value={adminName} onChange={e => setAdminName(e.target.value)} required placeholder="John Doe" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
                  <input type="email" value={adminEmail} onChange={e => setAdminEmail(e.target.value)} required placeholder="admin@company.com" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
                  <input type="password" value={adminPassword} onChange={e => setAdminPassword(e.target.value)} required minLength={6} placeholder="Min 6 characters" className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-brand-500 focus:border-transparent" />
                </div>
              </div>

              {error && <div className="mt-4 p-3 bg-red-50 rounded-lg text-sm text-red-700">{error}</div>}

              <button type="submit" disabled={loading} className="mt-6 w-full bg-brand-600 text-white py-2.5 rounded-lg font-medium hover:bg-brand-700 disabled:opacity-50 transition-colors">
                {loading ? 'Creating...' : 'Create Admin & Launch'}
              </button>
              <button type="button" onClick={() => setStep(1)} className="mt-2 w-full text-sm text-gray-500 hover:text-gray-700">← Back to email config</button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

function StepDot({ num, active, done, label }) {
  return (
    <div className="flex flex-col items-center gap-1">
      <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold transition-colors ${
        done ? 'bg-green-400 text-white' : active ? 'bg-white text-brand-600' : 'bg-brand-500 text-brand-200'
      }`}>
        {done ? '✓' : num}
      </div>
      <span className={`text-xs ${active ? 'text-white font-medium' : 'text-brand-300'}`}>{label}</span>
    </div>
  );
}
