'use client';

import { useEffect, useState, type FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { useAuthStore } from '@/stores/auth';
import { api } from '@/lib/api';
import { authDestination, INVITATION_PATH } from '@/lib/invitation-continuation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';

export default function RegisterPage() {
  const router = useRouter();
  const { register } = useAuthStore();
  const [invitation, setInvitation] = useState(false);
  useEffect(() => { setInvitation(authDestination() === INVITATION_PATH); }, []);
  const [phone, setPhone] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [passwordConfirmation, setPasswordConfirmation] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [fieldErrors, setFieldErrors] = useState<Record<string, string[]>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  async function handleSocialLogin(provider: 'google' | 'apple') {
    try {
      const response = await api.auth.socialRedirect(provider);
      window.location.href = response.url;
    } catch {
      setError(`Failed to connect to ${provider}.`);
    }
  }

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

    if (authDestination() === INVITATION_PATH && !phone.trim()) {
      setFieldErrors({ phone: ['Phone number is required to join your store.'] });
      return;
    }

    if (password !== passwordConfirmation) {
      setFieldErrors({ password: ['Passwords do not match.'] });
      return;
    }

    setIsSubmitting(true);

    try {
      if (phone.trim()) await register(name, email, password, phone.trim());
      else await register(name, email, password);
      router.push(authDestination());
    } catch (err: unknown) {
      const apiErr = err as { message?: string; errors?: Record<string, string[]> };
      setError(apiErr.message || 'Registration failed.');
      setFieldErrors(apiErr.errors || {});
    } finally {
      setIsSubmitting(false);
    }
  }

  return (
    <div>
      <h1 className="text-2xl font-bold text-slate-900 text-center">Create your account</h1>
      <p className="mt-1.5 text-sm text-slate-500 text-center">
        Join Alqove to shop sustainable resale.
      </p>

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

      <form onSubmit={handleSubmit} className="mt-6 space-y-4">
        <div>
          <label htmlFor="name" className="block text-sm font-medium text-slate-700">Name</label>
          <Input id="name" type="text" required value={name} onChange={(e) => setName(e.target.value)} className="mt-1" placeholder="Jane Doe" />
          {fieldErrors.name && <p className="mt-1 text-xs text-red-600">{fieldErrors.name[0]}</p>}
        </div>

        <div>
          <label htmlFor="email" className="block text-sm font-medium text-slate-700">Email</label>
          <Input id="email" type="email" required value={email} onChange={(e) => setEmail(e.target.value)} className="mt-1" placeholder="you@example.com" />
          {fieldErrors.email && <p className="mt-1 text-xs text-red-600">{fieldErrors.email[0]}</p>}
        </div>

        <div>
          <label htmlFor="phone" className="block text-sm font-medium text-slate-700">Phone number</label>
          <Input id="phone" type="tel" autoComplete="tel" required={invitation} value={phone} onChange={(e) => setPhone(e.target.value)} className="mt-1" placeholder="+1 312 555 0123" />
          <p className="mt-1 text-xs text-slate-500">{invitation ? 'Required to connect your existing store customer account. Use the phone number your store has on file.' : 'Optional. Use the number your store has on file to connect your customer account.'}</p>
          {fieldErrors.phone && <p className="mt-1 text-xs text-red-600">{fieldErrors.phone[0]}</p>}
        </div>

        <div>
          <label htmlFor="password" className="block text-sm font-medium text-slate-700">Password</label>
          <Input id="password" type="password" required minLength={8} value={password} onChange={(e) => setPassword(e.target.value)} className="mt-1" placeholder="••••••••" />
          {fieldErrors.password && <p className="mt-1 text-xs text-red-600">{fieldErrors.password[0]}</p>}
        </div>

        <div>
          <label htmlFor="password_confirmation" className="block text-sm font-medium text-slate-700">Confirm password</label>
          <Input id="password_confirmation" type="password" required minLength={8} value={passwordConfirmation} onChange={(e) => setPasswordConfirmation(e.target.value)} className="mt-1" placeholder="••••••••" />
        </div>

        <Button type="submit" disabled={isSubmitting} className="w-full">
          {isSubmitting ? 'Creating account...' : 'Create Account'}
        </Button>
      </form>

      {!invitation && <>
      <div className="relative my-6">
        <Separator />
        <span className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-white px-3 text-xs text-slate-400 uppercase">
          or
        </span>
      </div>

      <div className="space-y-2">
        <Button
          variant="outline"
          className="w-full"
          onClick={() => handleSocialLogin('google')}
        >
          Continue with Google
        </Button>
        <Button
          variant="outline"
          className="w-full"
          onClick={() => handleSocialLogin('apple')}
        >
          Continue with Apple
        </Button>
      </div>

      </>}

      <p className="mt-6 text-center text-sm text-slate-500">
        Already have an account?{' '}
        <a href="/login" className="font-medium text-forest-600 hover:text-forest-700">
          Sign in
        </a>
      </p>
    </div>
  );
}
