'use client'

import React, { useState, useEffect, Suspense } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { AuthLayout } from '@/components/layouts/AuthLayout'
import { Input } from '@/components/common/Input'
import { Button } from '@/components/common/Button'
import { Link } from '@/components/common/Link'
import { useApi } from '@/lib/hooks/useApi'

function ResetPasswordConfirmContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const { execute, isLoading, error } = useApi()
  const [token, setToken] = useState('')
  const [formData, setFormData] = useState({
    password: '',
    confirmPassword: '',
  })
  const [formErrors, setFormErrors] = useState<Record<string, string>>({})
  const [success, setSuccess] = useState(false)

  useEffect(() => {
    const tokenParam = searchParams.get('token')
    if (tokenParam) {
      setToken(tokenParam)
    } else {
      // Redirect to reset password page if no token
      router.push('/auth/reset-password')
    }
  }, [searchParams, router])

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

    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'
    }

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

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

    if (!validateForm()) {
      return
    }

    const data = await execute({
      method: 'POST',
      url: '/auth/reset-password/confirm',
      data: {
        token,
        password: formData.password,
      },
    })

    if (data) {
      setSuccess(true)
    }
  }

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

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

  if (success) {
    return (
      <AuthLayout
        title="Password reset successful"
        subtitle="Your password has been updated"
      >
        <div className="text-center space-y-4">
          <div className="w-16 h-16 bg-success-100 rounded-full flex items-center justify-center mx-auto">
            <svg
              className="w-8 h-8 text-success-600"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M5 13l4 4L19 7"
              />
            </svg>
          </div>

          <p className="text-gray-600 dark:text-gray-400">
            Your password has been successfully reset. You can now sign in with your new password.
          </p>

          <div className="pt-4">
            <Link href="/auth/login">
              <Button variant="primary" size="lg" fullWidth>
                Go to login
              </Button>
            </Link>
          </div>
        </div>
      </AuthLayout>
    )
  }

  return (
    <AuthLayout
      title="Set new password"
      subtitle="Enter your new password below"
    >
      <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 || 'Failed to reset password. The link may have expired.'}
            </p>
          </div>
        )}

        <Input
          type="password"
          name="password"
          label="New 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 new password"
          placeholder="••••••••"
          value={formData.confirmPassword}
          onChange={handleChange}
          error={formErrors.confirmPassword}
          required
          fullWidth
          autoComplete="new-password"
        />

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

        <div className="text-center text-sm text-gray-600 dark:text-gray-400">
          Remember your password?{' '}
          <Link href="/auth/login" variant="primary">
            Sign in
          </Link>
        </div>
      </form>
    </AuthLayout>
  )
}

export default function ResetPasswordConfirmPage() {
  return (
    <Suspense fallback={
      <AuthLayout title="Loading..." subtitle="Please wait">
        <div className="flex justify-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
        </div>
      </AuthLayout>
    }>
      <ResetPasswordConfirmContent />
    </Suspense>
  )
}
