import { useState, type FormEvent } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Mail, Lock, User, ArrowRight, Building2, Camera } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
import { handleApiError } from '../../services/api';
import { Button } from '../../components/ui/Button';
import { Input } from '../../components/ui/Input';
import type { UserRole } from '../../types/user';
import logo from '../../assets/logo.png';

export default function Register() {
  const navigate = useNavigate();
  const { register } = useAuth();
  const [role, setRole] = useState<UserRole | null>(null);
  const [form, setForm] = useState({
    username: '',
    email: '',
    first_name: '',
    last_name: '',
    password: '',
    password_confirm: '',
  });
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!role) return;
    if (form.password !== form.password_confirm) {
      setError('Passwords do not match');
      return;
    }
    setError('');
    setLoading(true);
    try {
      await register({ ...form, role });
      navigate('/');
    } catch (err) {
      setError(handleApiError(err));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-white flex">
      {/* Left branding */}
      <div className="hidden lg:flex lg:w-1/2 items-center justify-center p-12 bg-gray-50 border-r border-gray-100">
        <div className="max-w-sm">
          <div className="mb-10">
            <img src={logo} alt="SYNC" className="h-9 w-auto" />
          </div>
          <h1 className="text-3xl font-bold text-gray-900 mb-4 leading-tight">
            Start your journey with Sync
          </h1>
          <p className="text-gray-500 leading-relaxed">
            Whether you're a creator looking to monetise your audience or a
            brand searching for the perfect partnership — we've got you covered.
          </p>
        </div>
      </div>

      {/* Right form */}
      <div className="flex-1 flex items-center justify-center p-6 lg:p-12">
        <div className="w-full max-w-sm">
          <div className="lg:hidden mb-10">
            <img src={logo} alt="SYNC" className="h-8 w-auto" />
          </div>

          <h2 className="text-xl font-bold text-gray-900 mb-1">
            Create account
          </h2>
          <p className="text-sm text-gray-500 mb-8">
            Already have an account?{' '}
            <Link
              to="/login"
              className="text-brand-600 hover:text-brand-700 font-medium"
            >
              Sign in
            </Link>
          </p>

          {error && (
            <div className="mb-6 p-3 rounded-lg bg-red-50 border border-red-100 text-red-700 text-sm">
              {error}
            </div>
          )}

          {/* Role selection */}
          {!role ? (
            <div className="space-y-3">
              <p className="text-sm text-gray-500 font-medium mb-1">
                I am a...
              </p>
              <button
                onClick={() => setRole('INFLUENCER')}
                className="w-full flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-brand-200 hover:bg-brand-50/50 transition-all cursor-pointer group card-surface card-hover"
              >
                <div className="h-10 w-10 rounded-lg bg-brand-600 flex items-center justify-center">
                  <Camera className="h-5 w-5 text-white" />
                </div>
                <div className="text-left flex-1">
                  <p className="text-sm font-semibold text-gray-900">
                    Creator / Influencer
                  </p>
                  <p className="text-xs text-gray-500">
                    Connect your Instagram and get discovered by brands
                  </p>
                </div>
                <ArrowRight className="h-4 w-4 text-gray-300 group-hover:text-brand-600" />
              </button>
              <button
                onClick={() => setRole('BUSINESS')}
                className="w-full flex items-center gap-4 p-4 rounded-xl border border-gray-200 bg-white hover:border-brand-200 hover:bg-brand-50/50 transition-all cursor-pointer group card-surface card-hover"
              >
                <div className="h-10 w-10 rounded-lg bg-gray-800 flex items-center justify-center">
                  <Building2 className="h-5 w-5 text-white" />
                </div>
                <div className="text-left flex-1">
                  <p className="text-sm font-semibold text-gray-900">
                    Business / Brand
                  </p>
                  <p className="text-xs text-gray-500">
                    Find and collaborate with the right creators
                  </p>
                </div>
                <ArrowRight className="h-4 w-4 text-gray-300 group-hover:text-brand-600" />
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-4">
              <button
                type="button"
                onClick={() => setRole(null)}
                className="text-sm text-brand-600 hover:text-brand-700 mb-1 cursor-pointer"
              >
                &larr; Change role
              </button>

              <div className="grid grid-cols-2 gap-3">
                <Input
                  label="First Name"
                  placeholder="John"
                  icon={<User className="h-4 w-4" />}
                  value={form.first_name}
                  onChange={(e) =>
                    setForm({ ...form, first_name: e.target.value })
                  }
                  required
                  autoFocus
                />
                <Input
                  label="Last Name"
                  placeholder="Doe"
                  value={form.last_name}
                  onChange={(e) =>
                    setForm({ ...form, last_name: e.target.value })
                  }
                  required
                />
              </div>

              <Input
                label="Username"
                placeholder="johndoe"
                value={form.username}
                onChange={(e) => setForm({ ...form, username: e.target.value })}
                required
              />
              <Input
                label="Email"
                type="email"
                placeholder="john@example.com"
                icon={<Mail className="h-4 w-4" />}
                value={form.email}
                onChange={(e) => setForm({ ...form, email: e.target.value })}
                required
              />
              <Input
                label="Password"
                type="password"
                placeholder="Min 8 characters"
                icon={<Lock className="h-4 w-4" />}
                value={form.password}
                onChange={(e) => setForm({ ...form, password: e.target.value })}
                required
                minLength={8}
              />
              <Input
                label="Confirm Password"
                type="password"
                placeholder="Repeat password"
                icon={<Lock className="h-4 w-4" />}
                value={form.password_confirm}
                onChange={(e) =>
                  setForm({ ...form, password_confirm: e.target.value })
                }
                required
              />

              <Button
                type="submit"
                loading={loading}
                className="w-full"
                size="lg"
                icon={<ArrowRight className="h-4 w-4" />}
              >
                Create Account
              </Button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
