'use client'

import React, { useState } from 'react'
import { AuthLayout } from '@/components/layouts/AuthLayout'
import { Input } from '@/components/common/Input'
import { Button } from '@/components/common/Button'
import { Checkbox } from '@/components/common/Checkbox'
import { Link } from '@/components/common/Link'
import { useAuth } from '@/lib/hooks/useAuth'

export default function SignupPage() {
  const { signup, isLoading, error } = useAuth()
  const [formData, setFormData] = useState({
    email: '',
    password: '',
    confirmPassword: '',
    display_name: '',
    acceptTerms: false,
  })
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})

  const validateForm = () => {
    const errors: Record<string, string> = {}

    if (!formData.email) {
      errors.email = 'Email is required'
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      errors.email = 'Email is invalid'
    }

    if (!formData.password) {
      errors.password = 'Password is required'
    } else if (formData.password.length < 8) {
      errors.password = 'Password must be at least 8 characters'
    } else if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(formData.password)) {
      errors.password = 'Password must contain uppercase, lowercase, and number'
    }

    if (!formData.confirmPassword) {
      errors.confirmPassword = 'Please confirm your password'
    } else if (formData.password !== formData.confirmPassword) {
      errors.confirmPassword = 'Passwords do not match'
    }

    if (!formData.acceptTerms) {
      errors.acceptTerms = 'You must accept the terms and conditions'
    }

    setFormErrors(errors)
    return Object.keys(errors).length === 0
  }

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

    if (!validateForm()) {
      return
    }

    await signup({
      email: formData.email,
      password: formData.password,
      display_name: formData.display_name || undefined,
    })
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value, type, checked } = e.target
    setFormData((prev) => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }))

    // Clear error for this field
    if (formErrors[name]) {
      setFormErrors((prev) => {
        const newErrors = { ...prev }
        delete newErrors[name]
        return newErrors
      })
    }
  }

  return (
    <AuthLayout
      title="Create your account"
      subtitle="Join the MoreThanADiagnosis community"
    >
      <form onSubmit={handleSubmit} className="space-y-6">
        {error && (
          <div
            className="bg-error-50 border border-error-200 text-error-800 px-4 py-3 rounded-md"
            role="alert"
          >
            <p className="text-sm">
              {error.message || 'Signup failed. Please try again.'}
            </p>
          </div>
        )}

        <Input
          type="email"
          name="email"
          label="Email address"
          placeholder="you@example.com"
          value={formData.email}
          onChange={handleChange}
          error={formErrors.email}
          required
          fullWidth
          autoComplete="email"
        />

        <Input
          type="text"
          name="display_name"
          label="Display name (optional)"
          placeholder="How should we call you?"
          value={formData.display_name}
          onChange={handleChange}
          helperText="This will be your public display name"
          fullWidth
          autoComplete="name"
        />

        <Input
          type="password"
          name="password"
          label="Password"
          placeholder="••••••••"
          value={formData.password}
          onChange={handleChange}
          error={formErrors.password}
          helperText="At least 8 characters with uppercase, lowercase, and number"
          required
          fullWidth
          autoComplete="new-password"
        />

        <Input
          type="password"
          name="confirmPassword"
          label="Confirm password"
          placeholder="••••••••"
          value={formData.confirmPassword}
          onChange={handleChange}
          error={formErrors.confirmPassword}
          required
          fullWidth
          autoComplete="new-password"
        />

        <div>
          <Checkbox
            name="acceptTerms"
            checked={formData.acceptTerms}
            onChange={handleChange}
            error={formErrors.acceptTerms}
            label="I accept the Terms of Service and Privacy Policy"
          />
        </div>

        <Button
          type="submit"
          variant="primary"
          size="lg"
          fullWidth
          isLoading={isLoading}
          disabled={isLoading}
        >
          Create account
        </Button>

        <div className="text-center text-sm text-gray-600 dark:text-gray-400">
          Already have an account?{' '}
          <Link href="/login" variant="primary">
            Sign in
          </Link>
        </div>
      </form>
    </AuthLayout>
  )
}
