import { useState, useEffect } from 'react'
import { MdClose, MdVisibility, MdVisibilityOff } from 'react-icons/md'
import './PasswordForm.css'

const EMPTY_FORM = {
  name: '',
  url: '',
  username: '',
  password: '',
  tag: '',
  notes: '',
}

function getStrength(password) {
  if (!password) return 0
  let score = 0
  if (password.length >= 8) score++
  if (password.length >= 12) score++
  if (/[A-Z]/.test(password)) score++
  if (/[0-9]/.test(password)) score++
  if (/[^A-Za-z0-9]/.test(password)) score++
  return score
}

function StrengthBar({ password }) {
  const score = getStrength(password)
  const labels = ['', 'Very weak', 'Weak', 'Fair', 'Strong', 'Very strong']
  const colors = ['', '#ff4d6d', '#ff7c43', '#fbbf24', '#4ade80', '#00d4ff']

  if (!password) return null

  return (
    <div className="strength-bar-wrapper">
      <div className="strength-bar">
        {[1, 2, 3, 4, 5].map(i => (
          <div
            key={i}
            className="strength-segment"
            style={{ background: i <= score ? colors[score] : 'var(--border)' }}
          />
        ))}
      </div>
      <span className="strength-label" style={{ color: colors[score] }}>
        {labels[score]}
      </span>
    </div>
  )
}

export default function PasswordForm({ entry, onSave, onClose }) {
  const [form, setForm] = useState(EMPTY_FORM)
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (entry) {
      setForm({
        name: entry.name || '',
        url: entry.url || '',
        username: entry.username || '',
        password: entry.password || '',
        tag: entry.tag || '',
        notes: entry.notes || '',
      })
    } else {
      setForm(EMPTY_FORM)
    }
  }, [entry])

  function handleChange(e) {
    const { name, value } = e.target
    setForm(prev => ({ ...prev, [name]: value }))
  }

  async function handleSubmit(e) {
    e.preventDefault()
    if (!form.name.trim() || !form.password.trim()) {
      setError('Name and password are required')
      return
    }
    setError('')
    setLoading(true)
    try {
      const payload = {
        name: form.name.trim(),
        password: form.password,
        ...(form.url.trim() ? { url: form.url.trim() } : {}),
        ...(form.username.trim() ? { username: form.username.trim() } : {}),
        ...(form.tag.trim() ? { tag: form.tag.trim() } : {}),
        ...(form.notes.trim() ? { notes: form.notes.trim() } : {}),
      }
      await onSave(payload)
    } catch (err) {
      setError(err.message || 'Save failed')
      setLoading(false)
    }
  }

  return (
    <div className="modal-overlay" onClick={e => e.target === e.currentTarget && onClose()}>
      <div className="modal" role="dialog" aria-modal="true" aria-label={entry ? 'Edit password' : 'Add password'}>
        <div className="modal-header">
          <h2>{entry ? 'Edit Password' : 'Add Password'}</h2>
          <button className="btn-icon modal-close" onClick={onClose} aria-label="Close">
            <MdClose size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="modal-form">
          {error && <div className="modal-error">{error}</div>}

          <div className="form-group">
            <label htmlFor="pf-name">Name *</label>
            <input
              id="pf-name"
              name="name"
              type="text"
              value={form.name}
              onChange={handleChange}
              placeholder="e.g. GitHub account"
              required
              autoFocus
            />
          </div>

          <div className="form-group">
            <label htmlFor="pf-url">URL</label>
            <input
              id="pf-url"
              name="url"
              type="url"
              value={form.url}
              onChange={handleChange}
              placeholder="https://example.com"
            />
          </div>

          <div className="form-group">
            <label htmlFor="pf-username">Username</label>
            <input
              id="pf-username"
              name="username"
              type="text"
              value={form.username}
              onChange={handleChange}
              placeholder="username or email"
              autoComplete="off"
            />
          </div>

          <div className="form-group">
            <label htmlFor="pf-password">Password *</label>
            <div className="input-with-icon">
              <input
                id="pf-password"
                name="password"
                type={showPassword ? 'text' : 'password'}
                value={form.password}
                onChange={handleChange}
                placeholder="Enter password"
                required
                autoComplete="new-password"
              />
              <button
                type="button"
                className="btn-icon input-icon-btn"
                onClick={() => setShowPassword(v => !v)}
                aria-label={showPassword ? 'Hide password' : 'Show password'}
              >
                {showPassword ? <MdVisibilityOff size={18} /> : <MdVisibility size={18} />}
              </button>
            </div>
            <StrengthBar password={form.password} />
          </div>

          <div className="form-group">
            <label htmlFor="pf-tag">Tag</label>
            <input
              id="pf-tag"
              name="tag"
              type="text"
              value={form.tag}
              onChange={handleChange}
              placeholder="e.g. work, personal"
            />
          </div>

          <div className="form-group">
            <label htmlFor="pf-notes">Notes</label>
            <textarea
              id="pf-notes"
              name="notes"
              value={form.notes}
              onChange={handleChange}
              placeholder="Optional notes"
            />
          </div>

          <div className="modal-actions">
            <button type="button" className="btn btn-secondary" onClick={onClose}>
              Cancel
            </button>
            <button type="submit" className="btn btn-primary" disabled={loading}>
              {loading ? 'Saving…' : entry ? 'Save Changes' : 'Add Password'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
