'use client';

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { useAuthStore } from '@/lib/auth-store';
import { useState } from 'react';
import { Train, ShieldCheck } from 'lucide-react';

const registerSchema = z.object({
  fullName: z.string().min(2, 'Full name is required'),
  // Email is optional. If provided it must be a valid address; if left blank we fall back
  // to the phone number as the account identifier (see onSubmit).
  email: z
    .string()
    .email('Invalid email address')
    .optional()
    .or(z.literal('')),
  phone: z.string().min(9, 'Phone number is required'),
});

type RegisterForm = z.infer<typeof registerSchema>;

export default function RegisterPage() {
  const router = useRouter();
  const registerUser = useAuthStore((s) => s.register);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const { register, handleSubmit, formState: { errors } } = useForm<RegisterForm>({
    resolver: zodResolver(registerSchema as any),
  });

  const onSubmit = async (data: RegisterForm) => {
    setLoading(true);
    setError('');
    try {
      // No email? Use the phone number as the account identifier. The IAM (and our
      // relaxed RegisterDto) accept any non-empty string in the email field.
      const email = data.email?.trim() ? data.email.trim() : data.phone;
      const result = await registerUser({
        fullName: data.fullName,
        email,
        phone: data.phone,
      });
      const params = new URLSearchParams({
        email: result.email,
        userId: result.iamUserId,
        phone: result.phoneNumber,
      });
      router.push(`/verify-account?${params.toString()}`);
    } catch (err: any) {
      if (err.response?.status === 409) {
        setError('An account with this email or phone number already exists.');
      } else {
        setError(err.response?.data?.message || 'Registration failed. Please try again.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-[rgb(20_113_76)] from-10% via-transparent to-[rgb(20_113_76)] to-90% dark:from-gray-900 dark:to-gray-800 flex items-center justify-center py-12 px-4">
      <div className="max-w-md w-full">
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            <div className="w-12 h-12 bg-[rgb(20_113_76)] rounded-lg flex items-center justify-center">
              <Train className="w-6 h-6 text-white" />
            </div>
          </div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-gray-100">Create account</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-2">We&apos;ll text you a code to verify your phone</p>
        </div>

        <div className="card">
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
            {error && (
              <div className="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-700 dark:text-red-300 px-4 py-3 rounded">
                {error}
              </div>
            )}

            <div>
              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Full name</label>
              <input
                type="text"
                {...register('fullName')}
                className="input-field"
                placeholder="e.g. Abebe Kebede"
                autoComplete="name"
              />
              {errors.fullName && (
                <p className="text-red-500 text-sm mt-1">{errors.fullName.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">
                Email <span className="text-gray-400 font-normal">(optional)</span>
              </label>
              <input
                type="email"
                {...register('email')}
                className="input-field"
                placeholder="your@email.com"
                autoComplete="email"
              />
              {errors.email && (
                <p className="text-red-500 text-sm mt-1">{errors.email.message}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium mb-1 text-gray-700 dark:text-gray-300">Phone number</label>
              <input
                type="tel"
                {...register('phone')}
                className="input-field"
                placeholder="+251912345678"
                autoComplete="tel"
              />
              {errors.phone && (
                <p className="text-red-500 text-sm mt-1">{errors.phone.message}</p>
              )}
            </div>

            <button type="submit" className="btn-primary w-full" disabled={loading}>
              {loading ? 'Sending code...' : 'Send verification code'}
            </button>
          </form>

          <div className="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
            <Link
              href="/fayda-setup"
              className="flex items-center justify-center gap-2 w-full btn-secondary"
            >
              <ShieldCheck className="w-4 h-4" />
              Already verified with Fayda? Set up your password
            </Link>
          </div>

          <div className="mt-4 text-center">
            <span className="text-sm text-gray-600 dark:text-gray-400">Already have an account? </span>
            <Link href="/login" className="text-sm font-medium text-[rgb(20_113_76)] hover:underline">
              Sign in
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
