'use client'

import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { Lock, Loader2, ArrowLeft, RefreshCw, Calendar, Mail, Globe } from 'lucide-react'
import { Button } from '@/components/ui/button'
import Link from 'next/link'

interface Lead {
    id: string
    email: string
    source: string
    referrer: string
    created_at: string
}

export default function AdminPage() {
    const [isAuthenticated, setIsAuthenticated] = useState(false)
    const [password, setPassword] = useState('')
    const [isLoading, setIsLoading] = useState(false)
    const [error, setError] = useState('')
    const [data, setData] = useState<{ total: number; leads: Lead[] } | null>(null)

    const handleLogin = async (e: React.FormEvent) => {
        e.preventDefault()
        setIsLoading(true)
        setError('')

        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3002'}/api/waitlist/admin`, {
                headers: {
                    'x-admin-password': password
                }
            })

            const result = await response.json()

            if (result.success) {
                setIsAuthenticated(true)
                setData(result)
            } else {
                setError('Invalid password')
            }
        } catch (err) {
            setError('Connection error')
        } finally {
            setIsLoading(false)
        }
    }

    const refreshData = async () => {
        setIsLoading(true)
        try {
            const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3002'}/api/waitlist/admin`, {
                headers: {
                    'x-admin-password': password
                }
            })
            const result = await response.json()
            if (result.success) setData(result)
        } finally {
            setIsLoading(false)
        }
    }

    // LOGIN SCREEN
    if (!isAuthenticated) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-background p-6">
                <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="w-full max-w-sm"
                >
                    <div className="text-center mb-8">
                        <Link href="/" className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors mb-6">
                            <ArrowLeft className="mr-2 h-4 w-4" />
                            Back to Website
                        </Link>
                        <h1 className="text-2xl font-bold text-foreground">Admin Access</h1>
                        <p className="text-muted-foreground mt-2">Enter password to view waitlist</p>
                    </div>

                    <div className="bg-card border border-border rounded-xl p-6 shadow-xl">
                        <form onSubmit={handleLogin} className="space-y-4">
                            <div className="relative">
                                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                                <input
                                    type="password"
                                    value={password}
                                    onChange={(e) => setPassword(e.target.value)}
                                    className="w-full h-10 pl-10 pr-4 rounded-lg border border-border bg-background focus:ring-2 focus:ring-primary/20 outline-none transition-all"
                                    placeholder="Password"
                                    autoFocus
                                />
                            </div>

                            {error && (
                                <div className="text-sm text-red-500 font-medium text-center">
                                    {error}
                                </div>
                            )}

                            <Button type="submit" className="w-full" disabled={isLoading}>
                                {isLoading ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Login'}
                            </Button>
                        </form>
                    </div>
                </motion.div>
            </div>
        )
    }

    // DASHBOARD
    return (
        <div className="min-h-screen bg-secondary/10 p-6 md:p-12">
            <div className="max-w-5xl mx-auto space-y-8">
                {/* Header */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-3xl font-bold text-foreground">Waitlist Dashboard</h1>
                        <p className="text-muted-foreground mt-1">Real-time stats and signups</p>
                    </div>
                    <div className="flex gap-3">
                        <Button variant="outline" onClick={refreshData} disabled={isLoading}>
                            <RefreshCw className={`h-4 w-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
                            Refresh
                        </Button>
                        <Button variant="ghost" onClick={() => setIsAuthenticated(false)}>
                            Logout
                        </Button>
                    </div>
                </div>

                {/* Stats Cards */}
                <div className="grid md:grid-cols-3 gap-6">
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        className="bg-card border border-border p-6 rounded-xl shadow-sm"
                    >
                        <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">Total Signups</h3>
                        <div className="mt-2 text-4xl font-bold text-[hsl(var(--primary))]">
                            {data?.total || 0}
                        </div>
                    </motion.div>

                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ delay: 0.1 }}
                        className="bg-card border border-border p-6 rounded-xl shadow-sm"
                    >
                        <h3 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">Latest Signup</h3>
                        <div className="mt-2 text-lg font-medium text-foreground truncate">
                            {data?.leads[0]?.email || 'N/A'}
                        </div>
                        <div className="text-xs text-muted-foreground mt-1">
                            {data?.leads[0] ? new Date(data.leads[0].created_at).toLocaleString() : '-'}
                        </div>
                    </motion.div>
                </div>

                {/* Listings Table */}
                <motion.div
                    initial={{ opacity: 0, y: 20 }}
                    animate={{ opacity: 1, y: 0 }}
                    transition={{ delay: 0.2 }}
                    className="bg-card border border-border rounded-xl shadow-sm overflow-hidden"
                >
                    <div className="px-6 py-4 border-b border-border bg-secondary/5">
                        <h3 className="font-semibold text-foreground">Recent Signups</h3>
                    </div>
                    <div className="overflow-x-auto">
                        <table className="w-full text-sm text-left">
                            <thead className="bg-secondary/20 text-muted-foreground font-medium">
                                <tr>
                                    <th className="px-6 py-3">Email</th>
                                    <th className="px-6 py-3">Source</th>
                                    <th className="px-6 py-3">Date</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-border">
                                {data?.leads.map((lead) => (
                                    <tr key={lead.id} className="hover:bg-secondary/5 transition-colors">
                                        <td className="px-6 py-4 font-medium text-foreground flex items-center gap-2">
                                            <Mail className="h-3 w-3 text-muted-foreground" />
                                            {lead.email}
                                        </td>
                                        <td className="px-6 py-4 text-muted-foreground">
                                            {lead.source}
                                            {lead.referrer && <span className="text-xs ml-2 opacity-70">via {new URL(lead.referrer).hostname}</span>}
                                        </td>
                                        <td className="px-6 py-4 text-muted-foreground whitespace-nowrap">
                                            {new Date(lead.created_at).toLocaleString()}
                                        </td>
                                    </tr>
                                ))}
                                {data?.leads.length === 0 && (
                                    <tr>
                                        <td colSpan={3} className="px-6 py-8 text-center text-muted-foreground">
                                            No signups yet.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </motion.div>
            </div>
        </div>
    )
}
