"use client";

import { useState, useTransition } from "react";
import { Input } from "@/components/ui/Input";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { changePassword } from "@/lib/actions/profile";
import { swalAlert } from "@/lib/utils/swal";
import { Eye, EyeOff } from "lucide-react";

export function ChangePasswordForm() {
  const [form, setForm] = useState({
    currentPassword: "",
    newPassword: "",
    confirmPassword: "",
  });
  const [showCurrent, setShowCurrent] = useState(false);
  const [showNew, setShowNew] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  function handleChange(field: keyof typeof form) {
    return (e: React.ChangeEvent<HTMLInputElement>) => {
      setForm((prev) => ({ ...prev, [field]: e.target.value }));
      setError(null);
    };
  }

  const passwordStrength = (() => {
    const p = form.newPassword;
    if (!p) return null;
    let score = 0;
    if (p.length >= 8) score++;
    if (p.length >= 12) score++;
    if (/[A-Z]/.test(p)) score++;
    if (/[0-9]/.test(p)) score++;
    if (/[^A-Za-z0-9]/.test(p)) score++;
    if (score <= 1) return { label: "Weak", color: "bg-danger", width: "w-1/4" };
    if (score <= 2) return { label: "Fair", color: "bg-warning", width: "w-2/4" };
    if (score <= 3) return { label: "Good", color: "bg-accent", width: "w-3/4" };
    return { label: "Strong", color: "bg-success", width: "w-full" };
  })();

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);

    if (form.newPassword !== form.confirmPassword) {
      setError("New passwords do not match");
      return;
    }

    startTransition(async () => {
      const result = await changePassword(form);
      if (result.success) {
        void swalAlert("Password changed!", "Your password has been updated successfully.", "success");
        setForm({ currentPassword: "", newPassword: "", confirmPassword: "" });
      } else {
        setError(result.error);
      }
    });
  }

  return (
    <Card className="p-6">
      <h2 className="mb-1 text-[15px] font-bold text-navy">Change Password</h2>
      <p className="mb-5 text-[13px] text-muted">
        Choose a strong password you don&apos;t use elsewhere.
      </p>

      <form onSubmit={handleSubmit} className="space-y-4">
        {/* Current password */}
        <div>
          <label className="mb-1.5 block text-[12.5px] font-semibold text-navy">
            Current Password
          </label>
          <div className="relative">
            <Input
              type={showCurrent ? "text" : "password"}
              value={form.currentPassword}
              onChange={handleChange("currentPassword")}
              placeholder="••••••••"
              required
              autoComplete="current-password"
              className="pr-10"
            />
            <button
              type="button"
              onClick={() => setShowCurrent((v) => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted hover:text-navy"
              tabIndex={-1}
            >
              {showCurrent ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>
        </div>

        {/* New password */}
        <div>
          <label className="mb-1.5 block text-[12.5px] font-semibold text-navy">
            New Password
          </label>
          <div className="relative">
            <Input
              type={showNew ? "text" : "password"}
              value={form.newPassword}
              onChange={handleChange("newPassword")}
              placeholder="Min. 8 characters"
              required
              minLength={8}
              autoComplete="new-password"
              className="pr-10"
            />
            <button
              type="button"
              onClick={() => setShowNew((v) => !v)}
              className="absolute right-3 top-1/2 -translate-y-1/2 text-muted hover:text-navy"
              tabIndex={-1}
            >
              {showNew ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
            </button>
          </div>

          {/* Strength bar */}
          {passwordStrength && (
            <div className="mt-2">
              <div className="h-1.5 w-full overflow-hidden rounded-full bg-border">
                <div
                  className={`h-full rounded-full transition-all duration-300 ${passwordStrength.color} ${passwordStrength.width}`}
                />
              </div>
              <p className={`mt-1 text-[11px] font-semibold`}>
                {passwordStrength.label === "Weak" && <span className="text-danger">{passwordStrength.label}</span>}
                {passwordStrength.label === "Fair" && <span className="text-warning">{passwordStrength.label}</span>}
                {passwordStrength.label === "Good" && <span className="text-accent">{passwordStrength.label}</span>}
                {passwordStrength.label === "Strong" && <span className="text-success">{passwordStrength.label}</span>}
              </p>
            </div>
          )}
        </div>

        {/* Confirm password */}
        <div>
          <label className="mb-1.5 block text-[12.5px] font-semibold text-navy">
            Confirm New Password
          </label>
          <Input
            type="password"
            value={form.confirmPassword}
            onChange={handleChange("confirmPassword")}
            placeholder="Repeat new password"
            required
            autoComplete="new-password"
          />
          {form.confirmPassword && form.newPassword !== form.confirmPassword && (
            <p className="mt-1 text-[11.5px] text-danger">Passwords do not match</p>
          )}
          {form.confirmPassword && form.newPassword === form.confirmPassword && form.confirmPassword.length > 0 && (
            <p className="mt-1 text-[11.5px] text-success">✓ Passwords match</p>
          )}
        </div>

        {error && (
          <p className="rounded-[8px] bg-danger-bg px-3 py-2 text-[12.5px] text-danger">
            {error}
          </p>
        )}

        <div className="pt-1">
          <Button
            type="submit"
            loading={isPending}
            disabled={!form.currentPassword || !form.newPassword || !form.confirmPassword}
          >
            Update Password
          </Button>
        </div>
      </form>
    </Card>
  );
}
