import { useEffect, useState } from 'react'
import { Breadcrumbs, useToast } from '@meshkee/dashboard-ui'
import { useAuth } from '../context/AuthContext'
import { useT } from '../i18n/useT'
import { ApiError } from '../lib/api'
import { formatCellForDisplay } from '../lib/cellNumber'
import { updateProfile } from '../services/authService'
import pageStyles from '../components/PageContent.module.css'
import styles from './ProfilePage.module.css'

export function ProfilePage() {
  const { user, setUser } = useAuth()
  const { showToast } = useToast()
  const t = useT()

  const [firstName, setFirstName] = useState('')
  const [lastName, setLastName] = useState('')
  const [firstNameEn, setFirstNameEn] = useState('')
  const [lastNameEn, setLastNameEn] = useState('')
  const [email, setEmail] = useState('')
  const [landline, setLandline] = useState('')
  const [backupPhone, setBackupPhone] = useState('')
  const [about, setAbout] = useState('')
  const [instagram, setInstagram] = useState('')
  const [telegramId, setTelegramId] = useState('')
  const [linkedin, setLinkedin] = useState('')
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!user) return

    setFirstName(user.firstName ?? '')
    setLastName(user.lastName ?? '')
    setFirstNameEn(user.firstNameEn ?? '')
    setLastNameEn(user.lastNameEn ?? '')
    setEmail(user.email ?? '')
    setLandline(user.profile.landline ?? '')
    setBackupPhone(user.profile.backupPhone ?? '')
    setAbout(user.profile.about ?? '')
    setInstagram(user.profile.instagram ?? '')
    setTelegramId(user.profile.telegramId ?? '')
    setLinkedin(user.profile.linkedin ?? '')
  }, [user])

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

    try {
      const result = await updateProfile({
        firstName: firstName.trim(),
        lastName: lastName.trim(),
        firstNameEn: firstNameEn.trim(),
        lastNameEn: lastNameEn.trim(),
        email: email.trim() || undefined,
        landline: landline.trim(),
        backupPhone: backupPhone.trim(),
        about: about.trim(),
        instagram: instagram.trim(),
        telegramId: telegramId.trim(),
        linkedin: linkedin.trim(),
      })

      setUser(result.user)
      showToast(t('profile.toast.success'), 'success')
    } catch (err) {
      const message =
        err instanceof ApiError ? err.message : t('profile.error.update')
      setError(message)
      showToast(message, 'error')
    } finally {
      setIsSaving(false)
    }
  }

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs items={[{ label: t('nav.home'), href: '/' }, { label: t('profile.title') }]} />

      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>{t('profile.title')}</h2>
          <p className={pageStyles.pageSubtitle}>{t('profile.subtitle')}</p>
        </div>
      </div>

      <form className={styles.form} onSubmit={handleSubmit}>
        {error && (
          <div className={styles.error} role="alert">
            {error}
          </div>
        )}

        <section className={styles.section}>
          <h3 className={styles.sectionTitle}>{t('profile.section.account')}</h3>
          <div className={styles.grid}>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-cell">{t('profile.mobile')}</label>
              <input
                id="profile-cell"
                type="text"
                value={user ? formatCellForDisplay(user.cellNumber) : ''}
                disabled
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-email">{t('profile.email')}</label>
              <input
                id="profile-email"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder={t('profile.emailPlaceholder')}
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-first">{t('profile.firstName')}</label>
              <input
                id="profile-first"
                type="text"
                value={firstName}
                onChange={(e) => setFirstName(e.target.value)}
                required
                dir="rtl"
                lang="fa"
                className="faText"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-last">{t('profile.lastName')}</label>
              <input
                id="profile-last"
                type="text"
                value={lastName}
                onChange={(e) => setLastName(e.target.value)}
                required
                dir="rtl"
                lang="fa"
                className="faText"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-first-en">{t('profile.firstNameEn')}</label>
              <input
                id="profile-first-en"
                type="text"
                value={firstNameEn}
                onChange={(e) => setFirstNameEn(e.target.value)}
                dir="ltr"
                lang="en"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-last-en">{t('profile.lastNameEn')}</label>
              <input
                id="profile-last-en"
                type="text"
                value={lastNameEn}
                onChange={(e) => setLastNameEn(e.target.value)}
                dir="ltr"
                lang="en"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-landline">{t('profile.landline')}</label>
              <input
                id="profile-landline"
                type="text"
                value={landline}
                onChange={(e) => setLandline(e.target.value)}
                placeholder="02112345678"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="profile-backup-phone">{t('profile.backupPhone')}</label>
              <input
                id="profile-backup-phone"
                type="tel"
                inputMode="tel"
                value={backupPhone}
                onChange={(e) => setBackupPhone(e.target.value)}
                placeholder="09123456789"
              />
            </div>
          </div>
        </section>

        <section className={styles.section}>
          <h3 className={styles.sectionTitle}>{t('profile.section.about')}</h3>
          <div className={styles.grid}>
            <div className={`${styles.field} ${styles.col12}`}>
              <label htmlFor="profile-about">{t('profile.about')}</label>
              <textarea
                id="profile-about"
                value={about}
                onChange={(e) => setAbout(e.target.value)}
                rows={3}
              />
            </div>
          </div>
        </section>

        <section className={styles.section}>
          <h3 className={styles.sectionTitle}>{t('profile.section.social')}</h3>
          <div className={styles.grid}>
            <div className={`${styles.field} ${styles.col4}`}>
              <label htmlFor="profile-instagram">{t('profile.instagram')}</label>
              <input
                id="profile-instagram"
                type="text"
                value={instagram}
                onChange={(e) => setInstagram(e.target.value)}
              />
            </div>
            <div className={`${styles.field} ${styles.col4}`}>
              <label htmlFor="profile-telegram">{t('profile.telegram')}</label>
              <input
                id="profile-telegram"
                type="text"
                value={telegramId}
                onChange={(e) => setTelegramId(e.target.value)}
              />
            </div>
            <div className={`${styles.field} ${styles.col4}`}>
              <label htmlFor="profile-linkedin">{t('profile.linkedin')}</label>
              <input
                id="profile-linkedin"
                type="text"
                value={linkedin}
                onChange={(e) => setLinkedin(e.target.value)}
              />
            </div>
          </div>
        </section>

        <div className={styles.actions}>
          <button type="submit" className={styles.saveBtn} disabled={isSaving}>
            {isSaving ? t('profile.saving') : t('profile.save')}
          </button>
        </div>
      </form>
    </main>
  )
}
