'use client'

import { useState, useEffect, Suspense } from 'react'
import { useSearchParams, useRouter } from 'next/navigation'
import { Header } from '@/components/Header'
import { Footer } from '@/components/Footer'
import { api } from '@/lib/api'
import { Lock, Eye, EyeOff, CheckCircle, AlertCircle, ArrowLeft } from 'lucide-react'
import Link from 'next/link'
import clsx from 'clsx'

function ResetPasswordContent() {
  const searchParams = useSearchParams()
  const router = useRouter()
  const token = searchParams.get('token')

  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!token) {
      setError('Invalid or missing reset token. Please request a new password reset link.')
    }
  }, [token])

  const validatePassword = (pwd: string): string | null => {
    if (pwd.length < 8) {
      return 'Password must be at least 8 characters'
    }
    return null
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    const passwordError = validatePassword(password)
    if (passwordError) {
      setError(passwordError)
      return
    }

    if (password !== confirmPassword) {
      setError('Passwords do not match')
      return
    }

    if (!token) {
      setError('Invalid reset token')
      return
    }

    setLoading(true)
    setError(null)

    try {
      await api.resetPassword(token, password)
      setSuccess(true)
      
      // Redirect to login after 3 seconds
      setTimeout(() => {
        router.push('/login?reset=success')
      }, 3000)
    } catch (err: any) {
      setError(err.message || 'Failed to reset password. The link may have expired.')
    } finally {
      setLoading(false)
    }
  }

  const passwordStrength = (pwd: string): { label: string; color: string; width: string } => {
    if (pwd.length === 0) return { label: '', color: 'bg-transparent', width: 'w-0' }
    if (pwd.length < 6) return { label: 'Weak', color: 'bg-danger', width: 'w-1/4' }
    if (pwd.length < 8) return { label: 'Fair', color: 'bg-warning', width: 'w-2/4' }
    if (pwd.length < 12) return { label: 'Good', color: 'bg-accent', width: 'w-3/4' }
    return { label: 'Strong', color: 'bg-accent', width: 'w-full' }
  }

  const strength = passwordStrength(password)

  return (
    <>
      <Header />
      <main className="min-h-screen flex items-center justify-center p-4 pt-24">
        <div className="w-full max-w-md">
          <Link
            href="/login"
            className="inline-flex items-center gap-2 text-foreground-muted hover:text-foreground mb-8 transition-colors"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to login
          </Link>

          {success ? (
            <div className="bg-background-secondary/50 border border-border rounded-2xl p-8 text-center">
              <div className="w-16 h-16 bg-accent/10 rounded-full flex items-center justify-center mx-auto mb-6">
                <CheckCircle className="w-8 h-8 text-accent" />
              </div>
              <h1 className="text-display-sm font-bold text-foreground mb-4">
                Password reset successful
              </h1>
              <p className="text-foreground-muted mb-6">
                Your password has been reset. Redirecting you to login...
              </p>
              <Link
                href="/login"
                className="inline-flex items-center justify-center px-6 py-3 bg-accent text-background font-medium rounded-xl hover:bg-accent-hover transition-all"
              >
                Go to login
              </Link>
            </div>
          ) : (
            <div className="bg-background-secondary/50 border border-border rounded-2xl p-8">
              <div className="text-center mb-8">
                <h1 className="text-display-sm font-bold text-foreground mb-2">
                  Reset your password
                </h1>
                <p className="text-foreground-muted">
                  Enter your new password below.
                </p>
              </div>

              <form onSubmit={handleSubmit} className="space-y-6">
                {error && (
                  <div className="flex items-center gap-3 p-4 bg-danger/10 border border-danger/20 rounded-xl text-danger">
                    <AlertCircle className="w-5 h-5 flex-shrink-0" />
                    <p className="text-body-sm">{error}</p>
                  </div>
                )}

                <div>
                  <label htmlFor="password" className="block text-body-sm font-medium text-foreground mb-2">
                    New password
                  </label>
                  <div className="relative">
                    <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-muted" />
                    <input
                      id="password"
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      required
                      minLength={8}
                      placeholder="At least 8 characters"
                      className="w-full pl-12 pr-12 py-3 bg-background-tertiary border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent transition-all"
                    />
                    <button
                      type="button"
                      onClick={() => setShowPassword(!showPassword)}
                      className="absolute right-4 top-1/2 -translate-y-1/2 text-foreground-muted hover:text-foreground"
                    >
                      {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                    </button>
                  </div>
                  
                  {/* Password strength indicator */}
                  {password && (
                    <div className="mt-2">
                      <div className="h-1 bg-background-tertiary rounded-full overflow-hidden">
                        <div className={clsx('h-full transition-all', strength.color, strength.width)} />
                      </div>
                      <p className="text-ui-xs text-foreground-muted mt-1">{strength.label}</p>
                    </div>
                  )}
                </div>

                <div>
                  <label htmlFor="confirmPassword" className="block text-body-sm font-medium text-foreground mb-2">
                    Confirm password
                  </label>
                  <div className="relative">
                    <Lock className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-foreground-muted" />
                    <input
                      id="confirmPassword"
                      type={showPassword ? 'text' : 'password'}
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      required
                      minLength={8}
                      placeholder="Confirm your password"
                      className="w-full pl-12 pr-4 py-3 bg-background-tertiary border border-border rounded-xl text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-accent/30 focus:border-accent transition-all"
                    />
                  </div>
                  {confirmPassword && password !== confirmPassword && (
                    <p className="text-ui-xs text-danger mt-1">Passwords do not match</p>
                  )}
                </div>

                <button
                  type="submit"
                  disabled={loading || !token}
                  className={clsx(
                    'w-full py-3 px-4 bg-accent text-background font-medium rounded-xl transition-all',
                    (loading || !token)
                      ? 'opacity-50 cursor-not-allowed'
                      : 'hover:bg-accent-hover active:scale-[0.98]'
                  )}
                >
                  {loading ? 'Resetting...' : 'Reset password'}
                </button>
              </form>
            </div>
          )}
        </div>
      </main>
      <Footer />
    </>
  )
}

export default function ResetPasswordPage() {
  return (
    <Suspense fallback={
      <main className="min-h-screen flex items-center justify-center">
        <div className="animate-pulse text-foreground-muted">Authenticating...</div>
      </main>
    }>
      <ResetPasswordContent />
    </Suspense>
  )
}

