"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

type Field = "currentPassword" | "newPassword" | "confirmPassword"

export default function ChangePasswordForm() {
  const [values, setValues] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  })
  const [show, setShow] = useState<Record<Field, boolean>>({
    currentPassword: false,
    newPassword: false,
    confirmPassword: false,
  })
  const [loading, setLoading] = useState(false)
  const [error, setError]     = useState("")
  const [success, setSuccess] = useState(false)

  function toggle(field: Field) {
    setShow(prev => ({ ...prev, [field]: !prev[field] }))
  }

  function onChange(field: Field, value: string) {
    setValues(prev => ({ ...prev, [field]: value }))
    setError("")
    setSuccess(false)
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError("")
    setSuccess(false)

    if (!values.currentPassword || !values.newPassword || !values.confirmPassword) {
      setError("All fields are required.")
      return
    }
    if (values.newPassword.length < 6) {
      setError("New password must be at least 6 characters.")
      return
    }
    if (values.newPassword !== values.confirmPassword) {
      setError("New passwords do not match.")
      return
    }
    if (values.currentPassword === values.newPassword) {
      setError("New password must be different from current password.")
      return
    }

    setLoading(true)
    try {
      const res  = await fetch("/api/auth/change-password", {
        method:  "POST",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({
          currentPassword: values.currentPassword,
          newPassword:     values.newPassword,
        }),
      })
      const data = await res.json()
      if (!res.ok) {
        setError(data.error ?? "Something went wrong.")
      } else {
        setSuccess(true)
        setValues({ currentPassword: "", newPassword: "", confirmPassword: "" })
      }
    } catch {
      setError("Network error. Please try again.")
    } finally {
      setLoading(false)
    }
  }

  const strength =
    values.newPassword.length >= 12 ? 4 :
    values.newPassword.length >= 8  ? 3 :
    values.newPassword.length >= 6  ? 2 :
    values.newPassword.length >  0  ? 1 : 0

  const strengthLabel = ["", "Too short", "Weak", "Good", "Strong"][strength]
  const strengthColor = ["", "bg-red-400", "bg-yellow-400", "bg-blue-400", "bg-green-400"][strength]

  const fields: { key: Field; label: string; placeholder: string }[] = [
    { key: "currentPassword", label: "Current Password",     placeholder: "Enter your current password" },
    { key: "newPassword",     label: "New Password",         placeholder: "At least 6 characters"       },
    { key: "confirmPassword", label: "Confirm New Password", placeholder: "Repeat new password"         },
  ]

  return (
    <form onSubmit={handleSubmit} className="space-y-6">

      {/* ── error / success banners ── */}
      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
          {error}
        </div>
      )}
      {success && (
        <div className="rounded-lg border border-green-300 bg-green-50 p-3 text-sm text-green-700">
          Password updated successfully!
        </div>
      )}

      {/* ── Save button top-right — exactly like dept form ── */}
      <div className="flex items-center justify-end">
        <Button type="submit" disabled={loading}>
          {loading ? "Saving..." : "Save"}
        </Button>
      </div>

      {/* ── Card — exactly like dept form ── */}
      <Card>
        <CardHeader>
          <CardTitle className="text-sm font-medium">Password</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">

          {fields.map(({ key, label, placeholder }) => (
            <div key={key} className="space-y-2">
              <Label>{label}</Label>
              <div className="relative">
                <Input
                  type={show[key] ? "text" : "password"}
                  value={values[key]}
                  onChange={e => onChange(key, e.target.value)}
                  placeholder={placeholder}
                  autoComplete={key === "currentPassword" ? "current-password" : "new-password"}
                  className="pr-10"
                />
                <button
                  type="button"
                  onClick={() => toggle(key)}
                  tabIndex={-1}
                  className="absolute right-2.5 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground transition-colors"
                >
                  {show[key] ? (
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94"/>
                      <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19"/>
                      <line x1="1" y1="1" x2="23" y2="23"/>
                    </svg>
                  ) : (
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                      <circle cx="12" cy="12" r="3"/>
                    </svg>
                  )}
                </button>
              </div>

              {/* strength bar only under New Password */}
              {key === "newPassword" && values.newPassword.length > 0 && (
                <div>
                  <div className="flex gap-1 mt-1">
                    {[1, 2, 3, 4].map(i => (
                      <div
                        key={i}
                        className={`h-1 flex-1 rounded-full transition-colors ${
                          i <= strength ? strengthColor : "bg-muted"
                        }`}
                      />
                    ))}
                  </div>
                  <p className="text-[11px] text-muted-foreground mt-1">{strengthLabel}</p>
                </div>
              )}
            </div>
          ))}

        </CardContent>
      </Card>
    </form>
  )
}