import { useState } from 'react'
import Modal from '../ui/Modal'
import Button from '../ui/Button'
import { LabelledInput } from '../ui/Input'
import client from '../api/client'
import useAuthStore from '../store/authStore'

export default function EditProfileModal({ onClose }) {
  const { user, updateUser } = useAuthStore()

  const [fullName, setFullName] = useState(user?.full_name || '')
  const [username, setUsername] = useState(user?.username || '')

  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')

  const [newPin, setNewPin] = useState('')
  const [confirmPin, setConfirmPin] = useState('')

  const [error, setError] = useState('')
  const [saving, setSaving] = useState(false)

  const passwordTouched = currentPassword || newPassword || confirmPassword
  const pinTouched = newPin || confirmPin

  function validate() {
    if (passwordTouched) {
      if (!currentPassword) return 'Enter your current password.'
      if (!newPassword) return 'Enter a new password.'
      if (newPassword.length < 6) return 'New password must be at least 6 characters.'
      if (newPassword !== confirmPassword) return 'New passwords do not match.'
    }
    if (pinTouched) {
      if (newPin.length < 4) return 'PIN must be 4 digits.'
      if (newPin !== confirmPin) return 'PINs do not match.'
    }
    if (!username.trim()) return 'Username cannot be empty.'
    return null
  }

  async function handleSave() {
    const validationError = validate()
    if (validationError) { setError(validationError); return }

    const body = {}
    if (fullName !== (user?.full_name || '')) body.full_name = fullName
    if (username !== user?.username) body.username = username
    if (passwordTouched) {
      body.current_password = currentPassword
      body.new_password = newPassword
    }
    if (pinTouched) {
      body.new_pin = newPin
    }

    if (Object.keys(body).length === 0) { onClose(); return }

    setError('')
    setSaving(true)
    try {
      const { data } = await client.patch('/api/auth/me', body)
      updateUser(data)
      onClose()
    } catch (err) {
      const detail = err.response?.data?.detail
      setError(typeof detail === 'string' ? detail : 'Failed to save changes.')
    } finally {
      setSaving(false)
    }
  }

  function onlyDigits(val, max) {
    return val.replace(/\D/g, '').slice(0, max)
  }

  return (
    <Modal title="Edit Profile" onClose={onClose} maxWidth="max-w-lg">
      <div className="space-y-4">

        <div className="space-y-2">
          <LabelledInput
            label="Display Name"
            value={fullName}
            onChange={e => setFullName(e.target.value)}
            placeholder="e.g. Maria Papadopoulou"
          />
          <LabelledInput
            label="Username"
            value={username}
            onChange={e => setUsername(e.target.value)}
            autoComplete="off"
          />
        </div>

        <div className="border-t border-slate-100" />

        <div className="space-y-2">
          <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">
            Change Password <span className="normal-case font-normal">(leave blank to keep current)</span>
          </p>
          <LabelledInput
            label="Current Password"
            type="password"
            value={currentPassword}
            onChange={e => setCurrentPassword(e.target.value)}
            autoComplete="current-password"
          />
          <LabelledInput
            label="New Password"
            type="password"
            value={newPassword}
            onChange={e => setNewPassword(e.target.value)}
            autoComplete="new-password"
          />
          <LabelledInput
            label="Confirm New Password"
            type="password"
            value={confirmPassword}
            onChange={e => setConfirmPassword(e.target.value)}
            autoComplete="new-password"
          />
        </div>

        <div className="border-t border-slate-100" />

        <div className="space-y-2">
          <p className="text-[11px] font-semibold uppercase tracking-wider text-slate-400">
            Change PIN <span className="normal-case font-normal">(leave blank to keep current)</span>
          </p>
          <div className="flex gap-2">
            <LabelledInput
              label="New PIN"
              type="password"
              inputMode="numeric"
              value={newPin}
              onChange={e => setNewPin(onlyDigits(e.target.value, 4))}
              placeholder="••••"
              className="flex-1"
            />
            <LabelledInput
              label="Confirm PIN"
              type="password"
              inputMode="numeric"
              value={confirmPin}
              onChange={e => setConfirmPin(onlyDigits(e.target.value, 4))}
              placeholder="••••"
              className="flex-1"
            />
          </div>
        </div>

        {error && (
          <p className="text-[12px] text-rose-500">{error}</p>
        )}
      </div>

      <Modal.Footer>
        <Button variant="secondary" onClick={onClose} disabled={saving}>Cancel</Button>
        <Button variant="primary" onClick={handleSave} disabled={saving}>
          {saving ? 'Saving…' : 'Save Changes'}
        </Button>
      </Modal.Footer>
    </Modal>
  )
}
