'use client'

import { useState } from 'react'
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { JefflixLogo } from "@/components/jefflix-logo"
import { UserPlus, CheckCircle, AlertCircle, ArrowLeft } from "lucide-react"
import Link from 'next/link'

export default function RequestAccessPage() {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    reason: '',
  })
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle')
  const [errorMessage, setErrorMessage] = useState('')

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setStatus('loading')
    setErrorMessage('')

    try {
      const response = await fetch('/api/request-access', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || 'Failed to submit request')
      }

      setStatus('success')
    } catch (error) {
      setStatus('error')
      setErrorMessage(error instanceof Error ? error.message : 'Something went wrong')
    }
  }

  if (status === 'success') {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <div className="max-w-md w-full text-center space-y-6">
          <div className="inline-block p-6 bg-green-100 dark:bg-green-900/30 rounded-full">
            <CheckCircle className="h-12 w-12 text-green-600 dark:text-green-400" />
          </div>
          <h1 className="text-2xl font-bold">Request Submitted!</h1>
          <p className="text-muted-foreground">
            Your access request has been sent. You'll receive an email once your account is ready.
          </p>
          <p className="text-sm text-muted-foreground">
            This usually happens within 24-48 hours.
          </p>
          <div className="text-left bg-muted/50 rounded-lg p-6 mt-4 space-y-3">
            <h3 className="font-bold text-center">Once you're approved:</h3>
            <ul className="text-sm text-muted-foreground space-y-2 list-disc list-inside">
              <li>Request movies & shows at <a href="https://requests.jefflix.lol" className="text-blue-600 hover:underline font-medium">requests.jefflix.lol</a></li>
              <li>Watch them at <a href="https://movies.jefflix.lol" className="text-red-600 hover:underline font-medium">movies.jefflix.lol</a></li>
              <li>Both sites can be installed as apps on your phone's home screen, or use the Jellyfin app on a smart TV</li>
            </ul>
          </div>
          <Link href="/">
            <Button variant="outline" className="mt-4">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Jefflix
            </Button>
          </Link>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-background">
      {/* Header */}
      <div className="border-b border-border">
        <div className="container mx-auto px-4 py-4">
          <Link href="/" className="inline-block">
            <JefflixLogo size="small" />
          </Link>
        </div>
      </div>

      {/* Main Content */}
      <div className="container mx-auto px-4 py-12 md:py-20">
        <div className="max-w-lg mx-auto">
          <div className="text-center space-y-4 mb-8">
            <div className="inline-block p-4 bg-orange-100 dark:bg-orange-900/30 rounded-full">
              <UserPlus className="h-10 w-10 text-orange-600 dark:text-orange-400" />
            </div>
            <h1 className="text-3xl font-bold font-marker">Request Access</h1>
            <p className="text-muted-foreground">
              Jefflix is a community media server. To protect the community and ensure quality access,
              we require approval for new accounts.
            </p>
            <Badge className="bg-orange-600 text-white">
              Required for Live Sports & Premium Content
            </Badge>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-2">
              <label htmlFor="name" className="text-sm font-medium">
                Your Name *
              </label>
              <input
                type="text"
                id="name"
                required
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="w-full px-4 py-3 rounded-lg border border-border bg-background focus:outline-none focus:ring-2 focus:ring-orange-500"
                placeholder="Enter your name"
              />
            </div>

            <div className="space-y-2">
              <label htmlFor="email" className="text-sm font-medium">
                Email Address *
              </label>
              <input
                type="email"
                id="email"
                required
                value={formData.email}
                onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                className="w-full px-4 py-3 rounded-lg border border-border bg-background focus:outline-none focus:ring-2 focus:ring-orange-500"
                placeholder="your@email.com"
              />
              <p className="text-xs text-muted-foreground">
                We'll send your login details to this address
              </p>
            </div>

            <div className="space-y-2">
              <label htmlFor="reason" className="text-sm font-medium">
                How do you know Jeff? (optional)
              </label>
              <textarea
                id="reason"
                value={formData.reason}
                onChange={(e) => setFormData({ ...formData, reason: e.target.value })}
                className="w-full px-4 py-3 rounded-lg border border-border bg-background focus:outline-none focus:ring-2 focus:ring-orange-500 min-h-[100px]"
                placeholder="Just helps me know who's joining the community..."
              />
            </div>

            {status === 'error' && (
              <div className="flex items-center gap-2 p-4 bg-red-100 dark:bg-red-900/30 rounded-lg text-red-600 dark:text-red-400">
                <AlertCircle className="h-5 w-5 flex-shrink-0" />
                <p className="text-sm">{errorMessage}</p>
              </div>
            )}

            <Button
              type="submit"
              disabled={status === 'loading'}
              className="w-full py-6 text-lg font-bold bg-orange-600 hover:bg-orange-700 text-white"
            >
              {status === 'loading' ? 'Submitting...' : 'Request Access'}
            </Button>
          </form>

          <div className="mt-8 p-6 bg-muted/50 rounded-lg space-y-4">
            <h3 className="font-bold mb-2">What happens next?</h3>
            <ol className="text-sm text-muted-foreground space-y-2 list-decimal list-inside">
              <li>Your request is sent to the admin for review</li>
              <li>Once approved, you'll get an email with your login details</li>
              <li>Request movies & shows at <a href="https://requests.jefflix.lol" className="text-blue-600 hover:underline font-medium">requests.jefflix.lol</a></li>
              <li>Watch them at <a href="https://movies.jefflix.lol" className="text-red-600 hover:underline font-medium">movies.jefflix.lol</a></li>
            </ol>
            <p className="text-xs text-muted-foreground border-t border-border pt-3">
              Both sites can be installed as apps on your phone's home screen. On a smart TV, use the Jellyfin app and connect to movies.jefflix.lol.
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
