"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, 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 { Switch } from "@/components/ui/switch"
import { Shield, Smartphone, Eye, EyeOff, Loader2 } from "lucide-react"
import { toast } from "sonner"

interface SecuritySettingsProps {
  user: any
}

export function SecuritySettings({ user }: SecuritySettingsProps) {
  const [currentPassword, setCurrentPassword] = useState("")
  const [newPassword, setNewPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [showCurrentPassword, setShowCurrentPassword] = useState(false)
  const [showNewPassword, setShowNewPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)
  const [isUpdating, setIsUpdating] = useState(false)
  const [twoFactorEnabled, setTwoFactorEnabled] = useState(false)

  const handlePasswordUpdate = async () => {
    console.log("Password update button clicked") // Debug log

    // Check for empty fields with individual messages
    if (!currentPassword.trim()) {
      console.log("Current password is empty") // Debug log
      toast.error("Please enter your current password")
      return
    }

    if (!newPassword.trim()) {
      console.log("New password is empty") // Debug log
      toast.error("Please enter a new password")
      return
    }

    if (!confirmPassword.trim()) {
      console.log("Confirm password is empty") // Debug log
      toast.error("Please confirm your new password")
      return
    }

    // Check password length
    if (newPassword.length < 6) {
      console.log("Password too short") // Debug log
      toast.error("New password must be at least 6 characters long")
      return
    }

    // Check if new password and confirm password match
    if (newPassword !== confirmPassword) {
      console.log("Passwords don't match") // Debug log
      toast.error("New password and confirm password do not match")
      return
    }

    // Check if new password is different from current password
    if (currentPassword === newPassword) {
      console.log("Same password") // Debug log
      toast.error("New password must be different from current password")
      return
    }

    console.log("All validations passed, making API call") // Debug log
    setIsUpdating(true)

    try {
      const response = await fetch("/api/user/password", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        credentials: "include",
        body: JSON.stringify({
          currentPassword,
          newPassword,
        }),
      })

      const data = await response.json()
      console.log("API response:", response.status, data) // Debug log

      if (response.ok) {
        toast.success("Password updated successfully", {
          description: "Your password has been changed and saved to the database",
        })
        // Clear form
        setCurrentPassword("")
        setNewPassword("")
        setConfirmPassword("")
      } else {
        // Handle specific error messages from the server
        if (data.error === "Current password is incorrect") {
          toast.error("Current password is incorrect", {
            description: "Please enter your correct current password",
          })
        } else if (data.error === "Unauthorized") {
          toast.error("Authentication failed", {
            description: "Please log in again and try again",
          })
        } else {
          toast.error(data.error || "Failed to update password", {
            description: "Please try again or contact support if the problem persists",
          })
        }
      }
    } catch (error) {
      console.error("Password update error:", error)
      toast.error("An unexpected error occurred", {
        description: "Please check your internet connection and try again",
      })
    } finally {
      setIsUpdating(false)
    }
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Shield className="h-5 w-5" />
            Change Password
          </CardTitle>
          <CardDescription>Update your account password to keep your account secure</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="current-password">Current Password *</Label>
            <div className="relative">
              <Input
                id="current-password"
                type={showCurrentPassword ? "text" : "password"}
                placeholder="Enter your current password"
                value={currentPassword}
                onChange={(e) => setCurrentPassword(e.target.value)}
                disabled={isUpdating}
                className={!currentPassword && currentPassword !== "" ? "border-red-300" : ""}
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                onClick={() => setShowCurrentPassword(!showCurrentPassword)}
                disabled={isUpdating}
              >
                {showCurrentPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="new-password">New Password *</Label>
            <div className="relative">
              <Input
                id="new-password"
                type={showNewPassword ? "text" : "password"}
                placeholder="Enter your new password"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                disabled={isUpdating}
                className={!newPassword && newPassword !== "" ? "border-red-300" : ""}
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                onClick={() => setShowNewPassword(!showNewPassword)}
                disabled={isUpdating}
              >
                {showNewPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
            <p className="text-sm text-muted-foreground">Password must be at least 6 characters long</p>
          </div>

          <div className="space-y-2">
            <Label htmlFor="confirm-password">Confirm New Password *</Label>
            <div className="relative">
              <Input
                id="confirm-password"
                type={showConfirmPassword ? "text" : "password"}
                placeholder="Confirm your new password"
                value={confirmPassword}
                onChange={(e) => setConfirmPassword(e.target.value)}
                disabled={isUpdating}
                className={
                  (!confirmPassword && confirmPassword !== "") ||
                  (newPassword && confirmPassword && newPassword !== confirmPassword)
                    ? "border-red-300"
                    : ""
                }
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                disabled={isUpdating}
              >
                {showConfirmPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
            {newPassword && confirmPassword && newPassword !== confirmPassword && (
              <p className="text-sm text-red-500">Passwords do not match</p>
            )}
          </div>

          <div className="pt-2">
            <Button onClick={handlePasswordUpdate} disabled={isUpdating} className="w-full sm:w-auto">
              {isUpdating ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Updating Password...
                </>
              ) : (
                "Update Password"
              )}
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Smartphone className="h-5 w-5" />
            Two-Factor Authentication
          </CardTitle>
          <CardDescription>Add an extra layer of security to your account</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <Label htmlFor="2fa-toggle">Enable 2FA</Label>
              <p className="text-sm text-muted-foreground">Secure your account with 2FA</p>
            </div>
            <Switch id="2fa-toggle" checked={twoFactorEnabled} onCheckedChange={setTwoFactorEnabled} />
          </div>
          {twoFactorEnabled && (
            <div className="mt-4 p-4 bg-muted rounded-lg">
              <p className="text-sm text-muted-foreground">
                Two-factor authentication setup will be available in a future update.
              </p>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
