"use client"

import { useState, useEffect } from "react"
import { useAuth } from "@/hooks/use-auth"
import { DataAPI } from "@/lib/data-api"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { useToast } from "@/components/ui/toast"
import {
    User,
    Lock,
    Save,
    Loader2,
    Eye,
    EyeOff,
    ShieldCheck,
    Check,
    X,
    AlertCircle,
    Shield
} from "lucide-react"

export default function AdminSettingsPage() {
    const { user, isLoading: authLoading, refreshAuth } = useAuth()
    const router = useRouter()
    const toast = useToast()
    const [activeTab, setActiveTab] = useState("profile")
    const [isSaving, setIsSaving] = useState(false)

    // Profile Form State
    const [profileData, setProfileData] = useState({
        firstName: "",
        lastName: "",
        email: ""
    })

    // Password Form State
    const [passwordData, setPasswordData] = useState({
        current: "",
        new: "",
        confirm: ""
    })

    const [showCurrentPassword, setShowCurrentPassword] = useState(false)
    const [showNewPassword, setShowNewPassword] = useState(false)
    const [showConfirmPassword, setShowConfirmPassword] = useState(false)

    // Validation Logic
    const validatePassword = (password: string) => {
        const errors = []
        if (password.length < 8) errors.push("At least 8 characters")
        if (!/[A-Z]/.test(password)) errors.push("One uppercase letter")
        if (!/[a-z]/.test(password)) errors.push("One lowercase letter")
        if (!/[0-9]/.test(password)) errors.push("One number")
        if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) errors.push("One special character (!@#$%^&* etc.)")
        return errors
    }

    const passwordRequirements = [
        { text: "At least 8 characters", met: passwordData.new.length >= 8 },
        { text: "One uppercase letter", met: /[A-Z]/.test(passwordData.new) },
        { text: "One lowercase letter", met: /[a-z]/.test(passwordData.new) },
        { text: "One number", met: /[0-9]/.test(passwordData.new) },
        { text: "One special character (!@#$%^&* etc.)", met: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(passwordData.new) },
    ]

    const isPasswordValid = passwordRequirements.every(req => req.met)

    // Load initial data
    useEffect(() => {
        if (!authLoading) {
            if (!user) {
                router.push('/login')
                return
            }

            setProfileData({
                firstName: user.firstName || "",
                lastName: user.lastName || "",
                email: user.email || ""
            })
        }
    }, [user, authLoading, router])

    const handleProfileUpdate = async () => {
        if (!profileData.firstName.trim() || !profileData.lastName.trim()) {
            toast.error("First name and last name are required")
            return
        }

        setIsSaving(true)
        try {
            // Use generic updateProfile instead of admin user update
            const response = await DataAPI.auth.updateProfile({
                firstName: profileData.firstName,
                lastName: profileData.lastName,
            })

            if (response.success) {
                toast.success("Profile updated successfully")
                await refreshAuth()
            } else {
                throw new Error(response.message || "Failed to update profile")
            }
        } catch (error: any) {
            toast.error(error.message || "An error occurred")
        } finally {
            setIsSaving(false)
        }
    }

    const handlePasswordUpdate = async () => {
        if (!passwordData.current || !passwordData.new || !passwordData.confirm) {
            toast.error("All fields are required")
            return
        }

        if (passwordData.new !== passwordData.confirm) {
            toast.error("New passwords do not match")
            return
        }

        if (!isPasswordValid) {
            toast.error("Password does not meet all requirements")
            return
        }

        setIsSaving(true)
        try {
            const response = await DataAPI.auth.changePassword({
                currentPassword: passwordData.current,
                newPassword: passwordData.new
            })

            if (response.success) {
                toast.success("Password updated successfully")
                setPasswordData({ current: "", new: "", confirm: "" })
            } else {
                throw new Error(response.message || "Failed to update password")
            }
        } catch (error: any) {
            toast.error(error.message || "An error occurred")
        } finally {
            setIsSaving(false)
        }
    }

    if (authLoading) {
        return (
            <div className="flex flex-col items-center justify-center min-h-[60vh]">
                <Loader2 className="h-10 w-10 animate-spin text-blue-600 mb-4" />
                <p className="text-gray-500">Loading settings...</p>
            </div>
        )
    }

    if (!user) {
        return null // Will redirect in useEffect
    }

    return (
        <div className="max-w-4xl mx-auto space-y-8 pb-12 p-6 md:p-8">
            {/* Header */}
            <div className="flex flex-col gap-2">
                <h1 className="text-3xl font-bold text-gray-900 tracking-tight">
                    Admin Settings
                </h1>
                <p className="text-gray-500 text-lg">
                    Manage your account preferences and security
                </p>
            </div>

            {/* Tabs */}
            <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                <TabsList className="grid w-full grid-cols-2 h-12 p-1 bg-gray-100/80 backdrop-blur-sm rounded-xl mb-8 max-w-md">
                    <TabsTrigger
                        value="profile"
                        className="rounded-lg data-[state=active]:bg-white data-[state=active]:text-blue-600 data-[state=active]:shadow-sm transition-all duration-200 font-medium"
                    >
                        <User className="h-4 w-4 mr-2" />
                        Profile
                    </TabsTrigger>
                    <TabsTrigger
                        value="security"
                        className="rounded-lg data-[state=active]:bg-white data-[state=active]:text-blue-600 data-[state=active]:shadow-sm transition-all duration-200 font-medium"
                    >
                        <Lock className="h-4 w-4 mr-2" />
                        Security
                    </TabsTrigger>
                </TabsList>

                {/* Profile Content */}
                <TabsContent value="profile" className="space-y-6 focus-visible:outline-none">
                    <Card className="border-none shadow-lg bg-white/80 backdrop-blur-sm ring-1 ring-gray-200/50">
                        <CardHeader className="pb-6 pt-8 px-8">
                            <div className="flex items-center gap-4">
                                <div className="p-3 bg-blue-50 rounded-2xl border border-blue-100">
                                    <User className="h-8 w-8 text-blue-600" />
                                </div>
                                <div>
                                    <CardTitle className="text-2xl text-gray-900">Profile Information</CardTitle>
                                    <CardDescription className="text-base text-gray-500 mt-1">
                                        Update your personal details
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="p-6 md:p-8 space-y-6 pt-0">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div className="space-y-2">
                                    <Label htmlFor="firstName" className="text-sm font-medium text-gray-700">First Name</Label>
                                    <Input
                                        id="firstName"
                                        value={profileData.firstName}
                                        onChange={(e) => setProfileData(prev => ({ ...prev, firstName: e.target.value }))}
                                        className="h-11 bg-gray-50 focus:bg-white transition-colors"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="lastName" className="text-sm font-medium text-gray-700">Last Name</Label>
                                    <Input
                                        id="lastName"
                                        value={profileData.lastName}
                                        onChange={(e) => setProfileData(prev => ({ ...prev, lastName: e.target.value }))}
                                        className="h-11 bg-gray-50 focus:bg-white transition-colors"
                                    />
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="email" className="text-sm font-medium text-gray-700">Email Address</Label>
                                <Input
                                    id="email"
                                    value={profileData.email}
                                    disabled
                                    className="h-11 bg-gray-100/80 text-gray-500 border-gray-200 cursor-not-allowed"
                                />
                                <p className="text-xs text-gray-400">Email address cannot be changed</p>
                            </div>

                            <div className="pt-6 border-t border-gray-100 flex justify-end">
                                <Button
                                    onClick={handleProfileUpdate}
                                    disabled={isSaving}
                                    className="bg-blue-600 hover:bg-blue-700 text-white px-8 h-11 rounded-xl shadow-lg shadow-blue-200 hover:shadow-blue-300 transition-all duration-300"
                                >
                                    {isSaving ? (
                                        <span className="flex items-center gap-2">
                                            <Loader2 className="w-4 h-4 animate-spin" />
                                            Saving...
                                        </span>
                                    ) : (
                                        <span className="flex items-center gap-2">
                                            <Save className="h-4 w-4" />
                                            Save Changes
                                        </span>
                                    )}
                                </Button>
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>

                {/* Security Content */}
                <TabsContent value="security" className="space-y-6 focus-visible:outline-none">
                    <Card className="border-none shadow-lg bg-white/80 backdrop-blur-sm ring-1 ring-gray-200/50">
                        <CardHeader className="pb-6 pt-8 px-8">
                            <div className="flex items-center gap-4">
                                <div className="p-3 bg-amber-50 rounded-2xl border border-amber-100">
                                    <ShieldCheck className="h-8 w-8 text-amber-600" />
                                </div>
                                <div>
                                    <CardTitle className="text-2xl text-gray-900">Security Settings</CardTitle>
                                    <CardDescription className="text-base text-gray-500 mt-1">
                                        Update your password to keep your account secure
                                    </CardDescription>
                                </div>
                            </div>
                        </CardHeader>
                        <CardContent className="p-6 md:p-8 space-y-6 pt-0">
                            <div className="space-y-6 max-w-2xl">
                                <div className="space-y-2">
                                    <Label htmlFor="currentPassword">Current Password</Label>
                                    <div className="relative">
                                        <Input
                                            id="currentPassword"
                                            type={showCurrentPassword ? "text" : "password"}
                                            value={passwordData.current}
                                            onChange={(e) => setPasswordData(prev => ({ ...prev, current: e.target.value }))}
                                            className="h-11 bg-gray-50 focus:bg-white transition-colors pr-10"
                                            placeholder="Enter current password"
                                        />
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                                            className="absolute right-2 top-1.5 h-8 w-8 p-0 hover:bg-gray-100 hover:text-gray-900 text-gray-500 rounded-full"
                                        >
                                            {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                        </Button>
                                    </div>
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="newPassword">New Password</Label>
                                    <div className="relative">
                                        <Input
                                            id="newPassword"
                                            type={showNewPassword ? "text" : "password"}
                                            value={passwordData.new}
                                            onChange={(e) => setPasswordData(prev => ({ ...prev, new: e.target.value }))}
                                            className={`h-11 transition-colors pr-10 ${passwordData.new && isPasswordValid ? 'border-green-500 ring-green-500/20' :
                                                    passwordData.new ? 'border-amber-500 ring-amber-500/20' : 'bg-gray-50 focus:bg-white'
                                                }`}
                                            placeholder="Create new password"
                                        />
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setShowNewPassword(!showNewPassword)}
                                            className="absolute right-2 top-1.5 h-8 w-8 p-0 hover:bg-gray-100 hover:text-gray-900 text-gray-500 rounded-full"
                                        >
                                            {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                        </Button>
                                    </div>
                                </div>

                                {/* Password Requirements Display */}
                                {passwordData.new && (
                                    <div className={`rounded-xl p-4 border transition-all duration-200 ${isPasswordValid ? 'bg-green-50 border-green-200' : 'bg-gray-50 border-gray-200'
                                        }`}>
                                        <p className="text-sm font-medium text-gray-700 flex items-center gap-2 mb-3">
                                            <Shield className={`w-4 h-4 ${isPasswordValid ? 'text-green-600' : 'text-gray-500'}`} />
                                            Password Requirements
                                        </p>
                                        <div className="space-y-2">
                                            {passwordRequirements.map((req, index) => (
                                                <div key={index} className="flex items-center gap-2 text-sm">
                                                    {req.met ? (
                                                        <Check className="w-4 h-4 text-green-600 flex-shrink-0" />
                                                    ) : (
                                                        <div className="w-4 h-4 rounded-full border border-gray-300 flex items-center justify-center flex-shrink-0">
                                                            <div className="w-1.5 h-1.5 rounded-full bg-gray-300" />
                                                        </div>
                                                    )}
                                                    <span className={req.met ? "text-green-700" : "text-gray-500"}>
                                                        {req.text}
                                                    </span>
                                                </div>
                                            ))}
                                        </div>
                                    </div>
                                )}

                                <div className="space-y-2">
                                    <Label htmlFor="confirmPassword">Confirm New Password</Label>
                                    <div className="relative">
                                        <Input
                                            id="confirmPassword"
                                            type={showConfirmPassword ? "text" : "password"}
                                            value={passwordData.confirm}
                                            onChange={(e) => setPasswordData(prev => ({ ...prev, confirm: e.target.value }))}
                                            className={`h-11 transition-colors pr-10 ${passwordData.confirm && passwordData.confirm === passwordData.new ? 'border-green-500' : 'bg-gray-50 focus:bg-white'
                                                }`}
                                            placeholder="Re-enter new password"
                                        />
                                        <Button
                                            type="button"
                                            variant="ghost"
                                            size="sm"
                                            onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                                            className="absolute right-2 top-1.5 h-8 w-8 p-0 hover:bg-gray-100 hover:text-gray-900 text-gray-500 rounded-full"
                                        >
                                            {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                                        </Button>
                                    </div>
                                    {passwordData.confirm && passwordData.confirm !== passwordData.new && (
                                        <p className="text-sm text-red-500 flex items-center gap-1">
                                            <AlertCircle className="h-3 w-3" />
                                            Passwords do not match
                                        </p>
                                    )}
                                </div>

                                <div className="pt-4 flex justify-end">
                                    <Button
                                        onClick={handlePasswordUpdate}
                                        disabled={isSaving || !isPasswordValid || passwordData.new !== passwordData.confirm}
                                        className="bg-blue-600 hover:bg-blue-700 text-white px-8 h-11 rounded-xl shadow-lg shadow-blue-200 hover:shadow-blue-300 transition-all duration-300"
                                    >
                                        {isSaving ? (
                                            <span className="flex items-center gap-2">
                                                <Loader2 className="w-4 h-4 animate-spin" />
                                                Updating...
                                            </span>
                                        ) : (
                                            <span className="flex items-center gap-2">
                                                <Save className="h-4 w-4" />
                                                Update Password
                                            </span>
                                        )}
                                    </Button>
                                </div>
                            </div>
                        </CardContent>
                    </Card>
                </TabsContent>
            </Tabs>
        </div>
    )
}
