import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { FormField } from '@shared/ui'
import { PrimaryButton } from '@shared/ui'
import { Notification } from '@shared/ui'
import { ROUTES } from '@shared/config/routes'
import { passwordResetStart, passwordResetComplete } from '@features/auth/api/profileApi'
import logo from '@shared/assets/logo-full-white.png'
import styles from './RestorePasswordForm.module.css'

type NotificationState = { message: string; status: 'success' | 'error' }

export function RestorePasswordForm() {
  const [email, setEmail] = useState('')
  const [codeSent, setCodeSent] = useState(false)
  const [isSendingCode, setIsSendingCode] = useState(false)
  const [code, setCode] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')
  const [error, setError] = useState('')
  const [isLoading, setIsLoading] = useState(false)
  const [notification, setNotification] = useState<NotificationState | null>(null)
  const navigate = useNavigate()

  async function handleSendCode() {
    setError('')
    setIsSendingCode(true)
    try {
      await passwordResetStart({ email })
      setCodeSent(true)
      setNotification({ status: 'success', message: `Код отправлен на ${email}` })
    } catch {
      setNotification({ status: 'error', message: 'Не удалось отправить письмо. Проверьте email и попробуйте снова.' })
    } finally {
      setIsSendingCode(false)
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError('')

    if (newPassword !== confirmPassword) {
      setError('Пароли не совпадают')
      return
    }

    setIsLoading(true)
    try {
      await passwordResetComplete({ email, code, new_password: newPassword, confirm_password: confirmPassword })
      navigate(ROUTES.LOGIN)
    } catch {
      setError('Не удалось изменить пароль. Проверьте код и попробуйте снова.')
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <>
      <form className={styles.card} onSubmit={handleSubmit}>
        <div className={styles.logo}>
          <img src={logo} alt="ЭКСА" />
        </div>
        <h1 className={styles.title}>Восстановление пароля</h1>

        <div className={styles.fields}>
          <div className={styles.emailRow}>
            <FormField
              label="E-Mail"
              type="email"
              value={email}
              onChange={setEmail}
              placeholder="example@mail.com"
              required
            />
            <PrimaryButton
              label={isSendingCode ? 'Отправка...' : 'Получить код'}
              disabled={isSendingCode || !email}
              type="button"
              onClick={handleSendCode}
            />
          </div>

          {codeSent && (
            <>
              <FormField
                label="Код с почты"
                type="text"
                value={code}
                onChange={setCode}
                placeholder="000 000"
                required
              />
              <FormField
                label="Новый пароль"
                type="password"
                value={newPassword}
                onChange={setNewPassword}
                placeholder="••••••••"
                required
              />
              <FormField
                label="Повторить пароль"
                type="password"
                value={confirmPassword}
                onChange={setConfirmPassword}
                placeholder="••••••••"
                required
              />
            </>
          )}
        </div>

        {error && <p className={styles.error}>{error}</p>}

        {codeSent && (
          <div className={styles.submitWrapper}>
            <PrimaryButton label={isLoading ? 'Сохранение...' : 'Изменить пароль'} disabled={isLoading} />
          </div>
        )}

        <div className={styles.footer}>
          <a className={styles.back} onClick={() => navigate(ROUTES.LOGIN)}>
            Вернуться ко входу
          </a>
        </div>
      </form>
      {notification && (
        <Notification
          status={notification.status}
          message={notification.message}
          onClose={() => setNotification(null)}
        />
      )}
    </>
  )
}
