'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Lock, Eye, EyeOff } from 'lucide-react'
import { toast } from 'sonner'

export default function AdminLoginPage() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const router = useRouter()

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

    try {
      const response = await fetch('/api/admin/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      })

      const data = await response.json()

      if (response.ok) {
        toast.success('Login successful!')
        router.push('/admin/dashboard')
      } else {
        toast.error(data.error || 'Invalid credentials')
      }
    } catch {
      toast.error('An error occurred')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="min-h-screen bg-[#0b0b0b] flex items-center justify-center px-4">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold font-[family-name:var(--font-poppins)] text-[#e50914]">
            WATCHFLIX
          </h1>
          <p className="text-gray-400 mt-2">Admin Panel</p>
        </div>

        {/* Login Form */}
        <div className="bg-[#141414] rounded-2xl p-8 border border-white/10">
          <div className="flex items-center justify-center w-16 h-16 mx-auto mb-6 rounded-full bg-[#e50914]/10">
            <Lock className="w-8 h-8 text-[#e50914]" />
          </div>

          <h2 className="text-2xl font-bold text-white text-center mb-6">
            Admin Login
          </h2>

          <form onSubmit={handleSubmit} className="space-y-5">
            <div>
              <label htmlFor="email" className="block text-sm font-medium text-gray-400 mb-2">
                Email
              </label>
              <input
                id="email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="admin@watchflix.com"
                required
                className="w-full px-4 py-3 bg-[#0b0b0b] border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-[#e50914] transition-colors"
              />
            </div>

            <div>
              <label htmlFor="password" className="block text-sm font-medium text-gray-400 mb-2">
                Password
              </label>
              <div className="relative">
                <input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter your password"
                  required
                  className="w-full px-4 py-3 bg-[#0b0b0b] border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-[#e50914] transition-colors pr-12"
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white"
                >
                  {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                </button>
              </div>
            </div>

            <button
              type="submit"
              disabled={isLoading}
              className="w-full py-3 bg-[#e50914] text-white rounded-xl font-semibold hover:bg-[#f40612] transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            >
              {isLoading ? (
                <>
                  <div className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  Signing in...
                </>
              ) : (
                'Sign In'
              )}
            </button>
          </form>

          <p className="text-center text-gray-500 text-sm mt-6">
            First time? Use the setup below to create an admin account.
          </p>
        </div>

        {/* Setup Section */}
        <SetupAdmin />
      </div>
    </div>
  )
}

function SetupAdmin() {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [isExpanded, setIsExpanded] = useState(false)

  const handleSetup = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsLoading(true)

    try {
      const response = await fetch('/api/admin/setup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      })

      const data = await response.json()

      if (response.ok) {
        toast.success('Admin account created! You can now login.')
        setEmail('')
        setPassword('')
        setIsExpanded(false)
      } else {
        toast.error(data.error || 'Failed to create admin')
      }
    } catch {
      toast.error('An error occurred')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="mt-6">
      <button
        onClick={() => setIsExpanded(!isExpanded)}
        className="w-full text-center text-sm text-gray-400 hover:text-white transition-colors"
      >
        {isExpanded ? 'Hide setup' : 'Create admin account'}
      </button>

      {isExpanded && (
        <div className="mt-4 bg-[#141414] rounded-2xl p-6 border border-white/10">
          <h3 className="text-lg font-semibold text-white mb-4">Create Admin</h3>
          <form onSubmit={handleSetup} className="space-y-4">
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="Admin email"
              required
              className="w-full px-4 py-3 bg-[#0b0b0b] border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-[#e50914]"
            />
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Admin password"
              required
              minLength={6}
              className="w-full px-4 py-3 bg-[#0b0b0b] border border-white/10 rounded-xl text-white placeholder-gray-500 focus:outline-none focus:border-[#e50914]"
            />
            <button
              type="submit"
              disabled={isLoading}
              className="w-full py-3 bg-white/10 text-white rounded-xl font-medium hover:bg-white/20 transition-colors disabled:opacity-50"
            >
              {isLoading ? 'Creating...' : 'Create Admin'}
            </button>
          </form>
        </div>
      )}
    </div>
  )
}
