"use client"

import type React from "react"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
import { useToast } from "@/components/ui/use-toast"
import { getSettings, updateSettings } from "@/services/student_page/query"
import { Loader2 } from "lucide-react"

// Password strength calculation
const calculatePasswordStrength = (password: string) => {
  if (!password) return { score: 0, label: "", color: "" }

  let score = 0
  const checks = {
    length: password.length >= 12,
    lowercase: /[a-z]/.test(password),
    uppercase: /[A-Z]/.test(password),
    numbers: /\d/.test(password),
    specialChars: (password.match(/[!@#$%^&*(),.?":{}|<>]/g) || []).length >= 3,
  }

  if (checks.length) score += 20
  if (checks.lowercase) score += 20
  if (checks.uppercase) score += 20
  if (checks.numbers) score += 20
  if (checks.specialChars) score += 20

  if (score < 40) return { score, label: "Weak", color: "bg-red-500" }
  if (score < 60) return { score, label: "Fair", color: "bg-orange-500" }
  if (score < 80) return { score, label: "Good", color: "bg-yellow-500" }
  if (score < 100) return { score, label: "Strong", color: "bg-blue-500" }
  return { score, label: "Very Strong", color: "bg-green-500" }
}

export default function StudentSettingsPage() {
  const router = useRouter()
  const { toast } = useToast()

  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [userData, setUserData] = useState<any>(null)
  const [studentData, setStudentData] = useState<any>(null)

  const [name, setName] = useState("")
  const [password, setPassword] = useState("")
  const [repeatPassword, setRepeatPassword] = useState("")
  const [passwordStrength, setPasswordStrength] = useState({ score: 0, label: "", color: "" })

  // Fetch settings data
  useEffect(() => {
    async function fetchSettings() {
      try {
        setLoading(true)
        setError(null)

        const response = await getSettings()
        console.log("[settings] Fetched settings:", {
          status: response.status,
          user: response.user ? { id: response.user.id, name: response.user.name } : null,
          student: response.student ? { id: response.student.id, name: response.student.name } : null,
        })

        if (response.status === "OK" && response.user && response.student) {
          setUserData(response.user)
          setStudentData(response.student)
          setName(response.user.name || "")
        } else {
          setError("Failed to load settings. Please try again.")
        }
      } catch (err) {
        console.error("[settings] Error fetching settings:", err)
        setError("An error occurred while loading your settings. Please try again.")
      } finally {
        setLoading(false)
      }
    }

    fetchSettings()
  }, [])

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // Validate form
    if (!name.trim()) {
      toast({
        title: "Error",
        description: "Name is required",
        variant: "destructive",
      })
      return
    }

    if (password && password !== repeatPassword) {
      toast({
        title: "Error",
        description: "Passwords do not match",
        variant: "destructive",
      })
      return
    }

    if (password && passwordStrength.score < 100) {
      toast({
        title: "Error",
        description: "Password does not meet all requirements",
        variant: "destructive",
      })
      return
    }

    try {
      setSaving(true)

      // Update user and student data
      const updatedUser = {
        ...userData,
        name: name.trim(),
        ...(password ? { password } : {}),
      }

      const updatedStudent = {
        ...studentData,
        name: name.trim(),
      }

      console.log("[settings] Updating settings:", {
        user: { id: updatedUser.id, name: updatedUser.name },
        student: { id: updatedStudent.id, name: updatedStudent.name },
      })

      const response = await updateSettings(updatedUser, updatedStudent)

      if (response && response.status === "OK") {
        toast({
          title: "Success",
          description: "Your settings have been updated",
        })

        // Update local state
        setUserData(updatedUser)
        setStudentData(updatedStudent)
        setPassword("")
        setRepeatPassword("")
      } else {
        throw new Error("Failed to update settings")
      }
    } catch (err) {
      console.error("[settings] Error updating settings:", err)
      toast({
        title: "Error",
        description: "Failed to update settings. Please try again.",
        variant: "destructive",
      })
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
        <span className="ml-2">Loading settings...</span>
      </div>
    )
  }

  if (error) {
    return (
      <Card>
        <CardHeader>
          <CardTitle>Error</CardTitle>
          <CardDescription>Failed to load settings</CardDescription>
        </CardHeader>
        <CardContent>
          <p>{error}</p>
        </CardContent>
        <CardFooter>
          <Button onClick={() => router.refresh()}>Try Again</Button>
        </CardFooter>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold">Account Settings</h1>
        <p className="text-gray-500">Manage your account settings and preferences</p>
      </div>

      <form onSubmit={handleSubmit}>
        <Card>
          <CardHeader>
            <CardTitle>Personal Information</CardTitle>
            <CardDescription>Update your personal details</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="space-y-2">
              <Label htmlFor="name">Name</Label>
              <Input
                id="name"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Your name"
                disabled={saving}
              />
              <p className="text-xs text-gray-500">This will update your name across the platform</p>
            </div>

            <Separator />

            <div className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="password">New Password</Label>
                <Input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => {
                    setPassword(e.target.value)
                    setPasswordStrength(calculatePasswordStrength(e.target.value))
                  }}
                  placeholder="Leave blank to keep current password"
                  disabled={saving}
                />
                <div className="text-xs text-gray-600 space-y-1">
                  <p>Password requirements:</p>
                  <ul className="list-disc list-inside space-y-0.5 ml-2">
                    <li>Minimum 12 characters</li>
                    <li>Include uppercase and lowercase letters</li>
                    <li>Include at least one number</li>
                    <li>Include at least 3 special characters: !@#$%^&*(),.?":{}|&lt;&gt;</li>
                  </ul>
                </div>
                {password && (
                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-xs">
                      <span>Password strength:</span>
                      <span
                        className={`font-medium ${
                          passwordStrength.score < 40
                            ? "text-red-600"
                            : passwordStrength.score < 60
                              ? "text-orange-600"
                              : passwordStrength.score < 80
                                ? "text-yellow-600"
                                : passwordStrength.score < 100
                                  ? "text-blue-600"
                                  : "text-green-600"
                        }`}
                      >
                        {passwordStrength.label}
                      </span>
                    </div>
                    <div className="w-full bg-gray-200 rounded-full h-2">
                      <div
                        className={`h-2 rounded-full transition-all duration-300 ${passwordStrength.color}`}
                        style={{ width: `${passwordStrength.score}%` }}
                      />
                    </div>
                  </div>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="repeatPassword">Confirm New Password</Label>
                <Input
                  id="repeatPassword"
                  type="password"
                  value={repeatPassword}
                  onChange={(e) => setRepeatPassword(e.target.value)}
                  placeholder="Confirm new password"
                  disabled={saving}
                />
              </div>
            </div>
          </CardContent>
          <CardFooter className="flex justify-end">
            <Button type="submit" disabled={saving}>
              {saving ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Saving...
                </>
              ) : (
                "Save Changes"
              )}
            </Button>
          </CardFooter>
        </Card>
      </form>
    </div>
  )
}
