/**
 * Register Page - Xpeditis
 *
 * Modern registration page with split-screen design
 */

'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { register } from '@/lib/api';
import { verifyInvitation, type InvitationResponse } from '@/lib/api/invitations';
import type { OrganizationType } from '@/types/api';

export default function RegisterPage() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');

  // Organization fields
  const [organizationName, setOrganizationName] = useState('');
  const [organizationType, setOrganizationType] = useState<OrganizationType>('FREIGHT_FORWARDER');
  const [street, setStreet] = useState('');
  const [city, setCity] = useState('');
  const [state, setState] = useState('');
  const [postalCode, setPostalCode] = useState('');
  const [country, setCountry] = useState('FR');

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');

  // Invitation-related state
  const [invitationToken, setInvitationToken] = useState<string | null>(null);
  const [invitation, setInvitation] = useState<InvitationResponse | null>(null);
  const [isVerifyingInvitation, setIsVerifyingInvitation] = useState(false);

  // Verify invitation token on mount
  useEffect(() => {
    const token = searchParams.get('token');
    if (token) {
      setIsVerifyingInvitation(true);
      verifyInvitation(token)
        .then(invitationData => {
          setInvitation(invitationData);
          setInvitationToken(token);
          // Pre-fill user information from invitation
          setEmail(invitationData.email);
          setFirstName(invitationData.firstName);
          setLastName(invitationData.lastName);
        })
        .catch(err => {
          setError('Le lien d\'invitation est invalide ou expiré.');
        })
        .finally(() => {
          setIsVerifyingInvitation(false);
        });
    }
  }, [searchParams]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    // Validate passwords match
    if (password !== confirmPassword) {
      setError('Les mots de passe ne correspondent pas');
      return;
    }

    // Validate password length
    if (password.length < 12) {
      setError('Le mot de passe doit contenir au moins 12 caractères');
      return;
    }

    // Validate organization fields only if NOT using invitation
    if (!invitationToken) {
      if (!organizationName.trim()) {
        setError('Le nom de l\'organisation est requis');
        return;
      }

      if (!street.trim() || !city.trim() || !postalCode.trim() || !country.trim()) {
        setError('Tous les champs d\'adresse sont requis');
        return;
      }
    }

    setIsLoading(true);

    try {
      await register({
        email,
        password,
        firstName,
        lastName,
        // If invitation token exists, use it; otherwise provide organization data
        ...(invitationToken
          ? { invitationToken }
          : {
              organization: {
                name: organizationName,
                type: organizationType,
                street,
                city,
                state: state || undefined,
                postalCode,
                country: country.toUpperCase(),
              },
            }),
      });
      router.push('/dashboard');
    } catch (err: any) {
      setError(err.message || 'Erreur lors de la création du compte');
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex">
      {/* Left Side - Form */}
      <div className="w-full lg:w-1/2 flex flex-col justify-center px-8 sm:px-12 lg:px-16 xl:px-24 bg-white">
        <div className="max-w-md w-full mx-auto">
          {/* Logo */}
          <div className="mb-10">
            <Link href="/">
              <Image
                src="/assets/logos/logo-black.svg"
                alt="Xpeditis"
                width={50}
                height={60}
                priority
                className="h-auto"
              />
            </Link>
          </div>

          {/* Header */}
          <div className="mb-8">
            <h1 className="text-h1 text-brand-navy mb-2">
              {invitation ? 'Accepter l\'invitation' : 'Créer un compte'}
            </h1>
            <p className="text-body text-neutral-600">
              {invitation
                ? `Vous avez été invité à rejoindre une organisation`
                : 'Commencez votre essai gratuit dès aujourd\'hui'}
            </p>
          </div>

          {/* Verifying Invitation Loading */}
          {isVerifyingInvitation && (
            <div className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
              <p className="text-body-sm text-blue-800">Vérification de l'invitation...</p>
            </div>
          )}

          {/* Success Message for Invitation */}
          {invitation && !error && (
            <div className="mb-6 p-4 bg-green-50 border border-green-200 rounded-lg">
              <p className="text-body-sm text-green-800">
                Invitation valide ! Créez votre mot de passe pour rejoindre l'organisation.
              </p>
            </div>
          )}

          {/* Error Message */}
          {error && (
            <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
              <p className="text-body-sm text-red-800">{error}</p>
            </div>
          )}

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-5">
            {/* First Name & Last Name */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="firstName" className="label">
                  Prénom
                </label>
                <input
                  id="firstName"
                  type="text"
                  required
                  value={firstName}
                  onChange={e => setFirstName(e.target.value)}
                  className="input w-full"
                  placeholder="Jean"
                  disabled={isLoading || !!invitation}
                />
              </div>
              <div>
                <label htmlFor="lastName" className="label">
                  Nom
                </label>
                <input
                  id="lastName"
                  type="text"
                  required
                  value={lastName}
                  onChange={e => setLastName(e.target.value)}
                  className="input w-full"
                  placeholder="Dupont"
                  disabled={isLoading || !!invitation}
                />
              </div>
            </div>

            {/* Email */}
            <div>
              <label htmlFor="email" className="label">
                Adresse email
              </label>
              <input
                id="email"
                type="email"
                required
                value={email}
                onChange={e => setEmail(e.target.value)}
                className="input w-full"
                placeholder="jean.dupont@entreprise.com"
                autoComplete="email"
                disabled={isLoading || !!invitation}
              />
            </div>

            {/* Password */}
            <div>
              <label htmlFor="password" className="label">
                Mot de passe
              </label>
              <input
                id="password"
                type="password"
                required
                value={password}
                onChange={e => setPassword(e.target.value)}
                className="input w-full"
                placeholder="••••••••••••"
                autoComplete="new-password"
                disabled={isLoading}
              />
              <p className="mt-1.5 text-body-xs text-neutral-500">Au moins 12 caractères</p>
            </div>

            {/* Confirm Password */}
            <div>
              <label htmlFor="confirmPassword" className="label">
                Confirmer le mot de passe
              </label>
              <input
                id="confirmPassword"
                type="password"
                required
                value={confirmPassword}
                onChange={e => setConfirmPassword(e.target.value)}
                className="input w-full"
                placeholder="••••••••••••"
                autoComplete="new-password"
                disabled={isLoading}
              />
            </div>

            {/* Organization Section - Only show if NOT using invitation */}
            {!invitation && (
              <div className="pt-4 border-t border-neutral-200">
                <h3 className="text-h5 text-brand-navy mb-4">Informations de votre organisation</h3>

              {/* Organization Name */}
              <div className="mb-4">
                <label htmlFor="organizationName" className="label">
                  Nom de l'organisation
                </label>
                <input
                  id="organizationName"
                  type="text"
                  required
                  value={organizationName}
                  onChange={e => setOrganizationName(e.target.value)}
                  className="input w-full"
                  placeholder="Acme Logistics"
                  disabled={isLoading}
                />
              </div>

              {/* Organization Type */}
              <div className="mb-4">
                <label htmlFor="organizationType" className="label">
                  Type d'organisation
                </label>
                <select
                  id="organizationType"
                  value={organizationType}
                  onChange={e => setOrganizationType(e.target.value as OrganizationType)}
                  className="input w-full"
                  disabled={isLoading}
                >
                  <option value="FREIGHT_FORWARDER">Transitaire</option>
                  <option value="SHIPPER">Expéditeur</option>
                  <option value="CARRIER">Transporteur</option>
                </select>
              </div>

              {/* Street Address */}
              <div className="mb-4">
                <label htmlFor="street" className="label">
                  Adresse
                </label>
                <input
                  id="street"
                  type="text"
                  required
                  value={street}
                  onChange={e => setStreet(e.target.value)}
                  className="input w-full"
                  placeholder="123 Rue de la République"
                  disabled={isLoading}
                />
              </div>

              {/* City & Postal Code */}
              <div className="grid grid-cols-2 gap-4 mb-4">
                <div>
                  <label htmlFor="city" className="label">
                    Ville
                  </label>
                  <input
                    id="city"
                    type="text"
                    required
                    value={city}
                    onChange={e => setCity(e.target.value)}
                    className="input w-full"
                    placeholder="Paris"
                    disabled={isLoading}
                  />
                </div>
                <div>
                  <label htmlFor="postalCode" className="label">
                    Code postal
                  </label>
                  <input
                    id="postalCode"
                    type="text"
                    required
                    value={postalCode}
                    onChange={e => setPostalCode(e.target.value)}
                    className="input w-full"
                    placeholder="75001"
                    disabled={isLoading}
                  />
                </div>
              </div>

              {/* State & Country */}
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label htmlFor="state" className="label">
                    Région (optionnel)
                  </label>
                  <input
                    id="state"
                    type="text"
                    value={state}
                    onChange={e => setState(e.target.value)}
                    className="input w-full"
                    placeholder="Île-de-France"
                    disabled={isLoading}
                  />
                </div>
                <div>
                  <label htmlFor="country" className="label">
                    Pays (code ISO)
                  </label>
                  <input
                    id="country"
                    type="text"
                    required
                    value={country}
                    onChange={e => setCountry(e.target.value)}
                    className="input w-full"
                    placeholder="FR"
                    maxLength={2}
                    disabled={isLoading}
                  />
                </div>
              </div>
              </div>
            )}

            {/* Submit Button */}
            <button
              type="submit"
              disabled={isLoading}
              className="btn-primary w-full text-lg disabled:opacity-50 disabled:cursor-not-allowed mt-6"
            >
              {isLoading ? 'Création du compte...' : 'Créer mon compte'}
            </button>

            {/* Terms */}
            <p className="text-body-xs text-center text-neutral-500 mt-4">
              En créant un compte, vous acceptez nos{' '}
              <Link href="/terms" className="link">
                Conditions d'utilisation
              </Link>{' '}
              et notre{' '}
              <Link href="/privacy" className="link">
                Politique de confidentialité
              </Link>
            </p>
          </form>

          {/* Sign In Link */}
          <div className="mt-8 text-center">
            <p className="text-body text-neutral-600">
              Vous avez déjà un compte ?{' '}
              <Link href="/login" className="link font-semibold">
                Se connecter
              </Link>
            </p>
          </div>

          {/* Footer Links */}
          <div className="mt-8 pt-8 border-t border-neutral-200">
            <div className="flex flex-wrap justify-center gap-6 text-body-sm text-neutral-500">
              <Link href="/help" className="hover:text-accent transition-colors">
                Centre d'aide
              </Link>
              <Link href="/contact" className="hover:text-accent transition-colors">
                Contactez-nous
              </Link>
              <Link href="/privacy" className="hover:text-accent transition-colors">
                Confidentialité
              </Link>
              <Link href="/terms" className="hover:text-accent transition-colors">
                Conditions
              </Link>
            </div>
          </div>
        </div>
      </div>

      {/* Right Side - Brand Features (same as login) */}
      <div className="hidden lg:block lg:w-1/2 relative bg-brand-navy">
        <div className="absolute inset-0 bg-gradient-to-br from-brand-navy to-neutral-800 opacity-95"></div>
        <div className="absolute inset-0 flex flex-col justify-center px-16 xl:px-24 text-white">
          <div className="max-w-xl">
            <h2 className="text-display-sm mb-6 text-white">
              Rejoignez des milliers d'entreprises
            </h2>
            <p className="text-body-lg text-neutral-200 mb-12">
              Simplifiez votre logistique maritime et gagnez du temps sur chaque expédition.
            </p>

            <div className="space-y-6">
              <div className="flex items-start">
                <div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
                  <svg
                    className="w-6 h-6 text-white"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M5 13l4 4L19 7"
                    />
                  </svg>
                </div>
                <div className="ml-4">
                  <h3 className="text-h5 mb-1 text-white">Essai gratuit de 30 jours</h3>
                  <p className="text-body-sm text-neutral-300">
                    Testez toutes les fonctionnalités sans engagement
                  </p>
                </div>
              </div>

              <div className="flex items-start">
                <div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
                  <svg
                    className="w-6 h-6 text-white"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
                    />
                  </svg>
                </div>
                <div className="ml-4">
                  <h3 className="text-h5 mb-1 text-white">Sécurité maximale</h3>
                  <p className="text-body-sm text-neutral-300">
                    Vos données sont protégées et chiffrées
                  </p>
                </div>
              </div>

              <div className="flex items-start">
                <div className="flex-shrink-0 w-12 h-12 bg-brand-turquoise rounded-lg flex items-center justify-center">
                  <svg
                    className="w-6 h-6 text-white"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"
                    />
                  </svg>
                </div>
                <div className="ml-4">
                  <h3 className="text-h5 mb-1 text-white">Support 24/7</h3>
                  <p className="text-body-sm text-neutral-300">
                    Notre équipe est là pour vous accompagner
                  </p>
                </div>
              </div>
            </div>

            <div className="grid grid-cols-3 gap-8 mt-12 pt-12 border-t border-neutral-700">
              <div>
                <div className="text-display-sm text-brand-turquoise">2k+</div>
                <div className="text-body-sm text-neutral-300 mt-1">Entreprises</div>
              </div>
              <div>
                <div className="text-display-sm text-brand-turquoise">150+</div>
                <div className="text-body-sm text-neutral-300 mt-1">Pays couverts</div>
              </div>
              <div>
                <div className="text-display-sm text-brand-turquoise">24/7</div>
                <div className="text-body-sm text-neutral-300 mt-1">Support</div>
              </div>
            </div>
          </div>
        </div>

        <div className="absolute bottom-0 right-0 opacity-10">
          <svg width="400" height="400" viewBox="0 0 400 400" fill="none">
            <circle
              cx="200"
              cy="200"
              r="150"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white"
            />
            <circle
              cx="200"
              cy="200"
              r="100"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white"
            />
            <circle
              cx="200"
              cy="200"
              r="50"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white"
            />
          </svg>
        </div>
      </div>
    </div>
  );
}
