'use client';

import Link from 'next/link';
import { useMemo, useState } from 'react';

type Props = {
  token: string;
  invitation: {
    email: string;
    name: string;
    roleName: string;
    expiresAt: string | null;
  };
};

function passwordChecks(password: string) {
  return {
    minLength: password.length >= 8,
    hasNumber: /\d/.test(password),
    hasSpecial: /[^A-Za-z0-9]/.test(password),
  };
}

export function SetPasswordCard({ token, invitation }: Props) {
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [message, setMessage] = useState('');
  const [error, setError] = useState('');
  const [pending, setPending] = useState(false);

  const checks = useMemo(() => passwordChecks(password), [password]);
  const strengthCount = [checks.minLength, checks.hasNumber, checks.hasSpecial].filter(Boolean).length;
  const strengthLabel = strengthCount <= 1 ? 'Weak' : strengthCount === 2 ? 'Medium' : 'Strong';

  async function submit() {
    setError('');
    setMessage('');
    if (password !== confirmPassword) {
      setError('Password confirmation does not match.');
      return;
    }

    setPending(true);
    try {
      const response = await fetch(`/api/invitations/${token}/complete`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ password }),
      });
      const payload = await response.json();
      if (!response.ok) {
        setError(payload.message || 'Failed to activate account');
        return;
      }

      setMessage('Account activated. You can now log in with your email and password.');
    } finally {
      setPending(false);
    }
  }

  return (
    <div className="invite-page">
      <div className="invite-brand">
        <div className="invite-brand-mark">
          <span className="material-symbols-outlined">chat</span>
        </div>
        <span>WA Business</span>
      </div>

      <main className="invite-card">
        <div className="invite-card-head">
          <h1>Set Your Password</h1>
          <p>
            Welcome, {invitation.name}. Create a secure password to activate your account for{' '}
            <strong>{invitation.email}</strong> as <strong>{invitation.roleName}</strong>.
          </p>
        </div>

        <div className="invite-form">
          <label className="invite-field">
            <span>New Password</span>
            <div className="invite-password-wrap">
              <input
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                placeholder="Enter your password"
              />
              <button type="button" onClick={() => setShowPassword((current) => !current)}>
                <span className="material-symbols-outlined">{showPassword ? 'visibility_off' : 'visibility'}</span>
              </button>
            </div>
          </label>

          <label className="invite-field">
            <span>Confirm New Password</span>
            <input
              type="password"
              value={confirmPassword}
              onChange={(event) => setConfirmPassword(event.target.value)}
              placeholder="Repeat your password"
            />
          </label>

          <div className="invite-strength">
            <div className="invite-strength-head">
              <span>Password Strength</span>
              <strong>{strengthLabel}</strong>
            </div>
            <div className="invite-strength-bars">
              {[0, 1, 2, 3].map((index) => (
                <span key={index} className={index < strengthCount + 1 ? 'is-active' : ''} />
              ))}
            </div>
          </div>

          <div className="invite-checklist">
            <div className={checks.minLength ? 'is-done' : ''}>
              <span className="material-symbols-outlined">{checks.minLength ? 'check_circle' : 'circle'}</span>
              Minimum 8 characters
            </div>
            <div className={checks.hasNumber ? 'is-done' : ''}>
              <span className="material-symbols-outlined">{checks.hasNumber ? 'check_circle' : 'circle'}</span>
              At least one number
            </div>
            <div className={checks.hasSpecial ? 'is-done' : ''}>
              <span className="material-symbols-outlined">{checks.hasSpecial ? 'check_circle' : 'circle'}</span>
              One special character (@, #, $, etc.)
            </div>
          </div>

          <button type="button" className="invite-submit-button" onClick={submit} disabled={pending}>
            {pending ? 'Activating...' : 'Activate Account'}
          </button>

          {error ? <p className="form-error">{error}</p> : null}
          {message ? <p className="form-success">{message}</p> : null}
        </div>

        <div className="invite-footer">
          <span>Need help? Contact your admin or</span>
          <Link href="/login">go to login</Link>
        </div>
      </main>
    </div>
  );
}
