'use client'

import { useState, type FormEvent } from 'react'
import { Shield, Eye, EyeOff, Loader2, CheckCircle2, AlertTriangle, XCircle } from 'lucide-react'
import { cmsApi } from '../lib/api.js'

export interface ResetPasswordProps {
  onNavigate: (path: string) => void
  token: string | null
}

const fieldClass =
  'w-full rounded-lg border border-border bg-input-background px-3 py-2.5 text-sm text-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none'

export function ResetPassword({ onNavigate, token }: ResetPasswordProps) {
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState('')

  if (!token) {
    return (
      <div className="bg-muted flex min-h-screen items-center justify-center px-4">
        <div className="w-full max-w-md">
          <div className="mb-8 text-center">
            <div className="bg-destructive/10 mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-xl">
              <XCircle className="text-destructive h-7 w-7" />
            </div>
            <h1 className="text-foreground text-2xl font-medium">Invalid Reset Link</h1>
            <p className="text-muted-foreground mt-2">
              This password reset link is invalid or has expired.
            </p>
          </div>
          <div className="border-border bg-card space-y-4 rounded-xl border p-6 text-center shadow-sm">
            <button
              type="button"
              onClick={() => onNavigate('/forgot-password')}
              className="bg-primary text-primary-foreground hover:bg-primary/90 w-full rounded-lg py-2.5 font-medium transition-colors"
            >
              Request New Reset Link
            </button>
            <button
              type="button"
              onClick={() => onNavigate('/login')}
              className="text-muted-foreground hover:text-foreground w-full text-sm transition-colors"
            >
              Back to Sign In
            </button>
          </div>
        </div>
      </div>
    )
  }

  const passwordsMatch = password === confirmPassword
  const meetsLength = password.length >= 8
  const canSubmit = password && confirmPassword && passwordsMatch && meetsLength && !submitting

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault()
    if (!canSubmit) return

    setError('')
    setSubmitting(true)

    try {
      const result = await cmsApi<{ success: boolean }>('/auth/reset-password', {
        method: 'POST',
        body: JSON.stringify({ token, password }),
      })

      if (result.error) {
        setError(result.error)
      } else {
        setSuccess(true)
      }
    } catch {
      setError('An unexpected error occurred. Please try again.')
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="bg-muted flex min-h-screen items-center justify-center px-4">
      <div className="w-full max-w-md">
        <div className="mb-8 text-center">
          <div className="bg-primary mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-xl">
            <Shield className="text-primary-foreground h-7 w-7" />
          </div>
          <h1 className="text-foreground text-2xl font-medium">
            {success ? 'Password Reset' : 'Choose New Password'}
          </h1>
          <p className="text-muted-foreground mt-2">
            {success ? 'Your password has been updated' : 'Enter your new password below'}
          </p>
        </div>

        <div className="border-border bg-card space-y-5 rounded-xl border p-6 shadow-sm">
          {success ? (
            <div className="space-y-4 text-center">
              <div className="bg-success/10 mx-auto flex h-12 w-12 items-center justify-center rounded-full">
                <CheckCircle2 className="text-success h-6 w-6" />
              </div>
              <p className="text-muted-foreground text-sm">
                Your password has been successfully reset. All existing sessions have been revoked
                for security.
              </p>
              <button
                type="button"
                onClick={() => onNavigate('/login')}
                className="bg-primary text-primary-foreground hover:bg-primary/90 w-full rounded-lg py-2.5 font-medium transition-colors"
              >
                Sign In with New Password
              </button>
            </div>
          ) : (
            <form onSubmit={handleSubmit} className="space-y-5">
              {error && (
                <div className="border-destructive/30 bg-destructive/10 flex items-start gap-3 rounded-lg border p-3">
                  <AlertTriangle className="text-destructive mt-0.5 h-5 w-5 shrink-0" />
                  <p className="text-destructive text-sm">{error}</p>
                </div>
              )}

              <div>
                <label
                  htmlFor="reset-password"
                  className="text-foreground mb-1.5 block text-sm font-medium"
                >
                  New Password
                </label>
                <div className="relative">
                  <input
                    id="reset-password"
                    type={showPassword ? 'text' : 'password'}
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    placeholder="Enter new password"
                    className={`${fieldClass} pr-10`}
                    required
                    autoFocus
                    autoComplete="new-password"
                    minLength={8}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="text-muted-foreground hover:text-foreground absolute top-1/2 right-3 -translate-y-1/2"
                    tabIndex={-1}
                  >
                    {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
                {password && !meetsLength && (
                  <p className="text-destructive mt-1 text-xs">
                    Password must be at least 8 characters
                  </p>
                )}
              </div>

              <div>
                <label
                  htmlFor="reset-confirm"
                  className="text-foreground mb-1.5 block text-sm font-medium"
                >
                  Confirm Password
                </label>
                <input
                  id="reset-confirm"
                  type={showPassword ? 'text' : 'password'}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="Confirm new password"
                  className={fieldClass}
                  required
                  autoComplete="new-password"
                />
                {confirmPassword && !passwordsMatch && (
                  <p className="text-destructive mt-1 text-xs">Passwords do not match</p>
                )}
              </div>

              <button
                type="submit"
                disabled={!canSubmit}
                className="bg-primary text-primary-foreground hover:bg-primary/90 flex w-full items-center justify-center gap-2 rounded-lg py-2.5 font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
              >
                {submitting ? (
                  <>
                    <Loader2 className="h-4 w-4 animate-spin" />
                    Resetting...
                  </>
                ) : (
                  'Reset Password'
                )}
              </button>
            </form>
          )}
        </div>
      </div>
    </div>
  )
}
