/**
 * Private Gallery Unlock/Setup Page
 *
 * - First visit: Setup form to create password
 * - Subsequent visits: Unlock form to enter password
 */

import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Lock, Eye, EyeOff, ShieldCheck, Loader2, AlertCircle } from 'lucide-react'
import { usePrivateGalleryContext } from '../../components/private-gallery/PrivateGalleryProvider'

export default function PrivateGalleryUnlock() {
  const navigate = useNavigate()
  const { isLoading, isSetupComplete, error, setup, unlock, clearError } = usePrivateGalleryContext()

  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [localError, setLocalError] = useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const handleSetup = async (e: React.FormEvent) => {
    e.preventDefault()
    setLocalError(null)
    clearError()

    if (password.length < 8) {
      setLocalError('Password must be at least 8 characters')
      return
    }

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

    setIsSubmitting(true)
    const success = await setup(password)
    setIsSubmitting(false)

    if (success) {
      navigate('/private-gallery')
    }
  }

  const handleUnlock = async (e: React.FormEvent) => {
    e.preventDefault()
    setLocalError(null)
    clearError()

    if (!password) {
      setLocalError('Please enter your password')
      return
    }

    setIsSubmitting(true)
    const success = await unlock(password)
    setIsSubmitting(false)

    if (success) {
      navigate('/private-gallery')
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <div className="flex flex-col items-center gap-4">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
          <p className="text-muted-foreground">Loading...</p>
        </div>
      </div>
    )
  }

  const displayError = localError || error

  return (
    <div className="min-h-screen flex items-center justify-center bg-background p-4">
      <div className="w-full max-w-md">
        <div className="bg-card rounded-xl shadow-lg border border-border p-8">
          {/* Header */}
          <div className="flex flex-col items-center mb-8">
            <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4">
              {isSetupComplete ? (
                <Lock className="w-8 h-8 text-primary" />
              ) : (
                <ShieldCheck className="w-8 h-8 text-primary" />
              )}
            </div>
            <h1 className="text-2xl font-bold text-foreground">
              {isSetupComplete ? 'Unlock Private Gallery' : 'Setup Private Gallery'}
            </h1>
            <p className="text-muted-foreground text-center mt-2">
              {isSetupComplete
                ? 'Enter your password to access your private media'
                : 'Create a password to protect your private media'}
            </p>
          </div>

          {/* Error Message */}
          {displayError && (
            <div className="mb-6 p-4 rounded-lg bg-destructive/10 border border-destructive/20 flex items-start gap-3">
              <AlertCircle className="w-5 h-5 text-destructive flex-shrink-0 mt-0.5" />
              <p className="text-sm text-destructive">{displayError}</p>
            </div>
          )}

          {/* Form */}
          <form onSubmit={isSetupComplete ? handleUnlock : handleSetup}>
            {/* Password Field */}
            <div className="mb-4">
              <label htmlFor="password" className="block text-sm font-medium text-foreground mb-2">
                {isSetupComplete ? 'Password' : 'Create Password'}
              </label>
              <div className="relative">
                <input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="w-full px-4 py-3 rounded-lg border border-border bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                  placeholder={isSetupComplete ? 'Enter your password' : 'At least 8 characters'}
                  autoFocus
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>
            </div>

            {/* Confirm Password (Setup only) */}
            {!isSetupComplete && (
              <div className="mb-6">
                <label htmlFor="confirmPassword" className="block text-sm font-medium text-foreground mb-2">
                  Confirm Password
                </label>
                <input
                  id="confirmPassword"
                  type={showPassword ? 'text' : 'password'}
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  className="w-full px-4 py-3 rounded-lg border border-border bg-background text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                  placeholder="Re-enter your password"
                />
              </div>
            )}

            {/* Submit Button */}
            <button
              type="submit"
              disabled={isSubmitting}
              className="w-full py-3 px-4 rounded-lg bg-primary text-primary-foreground font-medium hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isSubmitting ? (
                <>
                  <Loader2 className="w-5 h-5 animate-spin" />
                  {isSetupComplete ? 'Unlocking...' : 'Setting up...'}
                </>
              ) : (
                <>
                  {isSetupComplete ? <Lock className="w-5 h-5" /> : <ShieldCheck className="w-5 h-5" />}
                  {isSetupComplete ? 'Unlock' : 'Create Gallery'}
                </>
              )}
            </button>
          </form>

          {/* Security Note */}
          <div className="mt-6 p-4 rounded-lg bg-secondary/50">
            <p className="text-xs text-muted-foreground text-center">
              {isSetupComplete
                ? 'Your media is encrypted at rest. The gallery will auto-lock after inactivity.'
                : 'Your password will be used to encrypt all media. Files are stored with UUID names for privacy.'}
            </p>
          </div>
        </div>

        {/* Keyboard Shortcut Hint */}
        <p className="text-center text-xs text-muted-foreground mt-4">
          Tip: Press <kbd className="px-1.5 py-0.5 rounded bg-secondary text-foreground">Ctrl</kbd> + <kbd className="px-1.5 py-0.5 rounded bg-secondary text-foreground">Shift</kbd> + <kbd className="px-1.5 py-0.5 rounded bg-secondary text-foreground">P</kbd> from anywhere to access the gallery
        </p>
      </div>
    </div>
  )
}
