import { useEffect, useState } from 'react'
import { Save } from 'lucide-react'
import { useAuth } from '../context/AuthContext'
import { ApiError } from '../lib/api'
import { formatCellForDisplay } from '../lib/cellNumber'
import { updateProfile } from '../services/profileService'
import type { ProfileFormData } from '../types/profile'
import { emptyProfile } from '../types/profile'
import pageStyles from '../components/PageContent.module.css'
import styles from './ProfilePage.module.css'

function buildFormData(user: ReturnType<typeof useAuth>['user']): ProfileFormData {
  return {
    firstName: user?.firstName ?? '',
    lastName: user?.lastName ?? '',
    firstNameEn: user?.firstNameEn ?? '',
    lastNameEn: user?.lastNameEn ?? '',
    cellNumber: user ? formatCellForDisplay(user.cellNumber) : '',
    email: user?.email ?? '',
    about: user?.profile?.about ?? emptyProfile.about,
    city: user?.profile?.city ?? emptyProfile.city,
    address: user?.profile?.address ?? emptyProfile.address,
    landline: user?.profile?.landline ?? emptyProfile.landline,
    postalCode: user?.profile?.postalCode ?? emptyProfile.postalCode,
    instagram: user?.profile?.instagram ?? emptyProfile.instagram,
    telegramId: user?.profile?.telegramId ?? emptyProfile.telegramId,
    linkedin: user?.profile?.linkedin ?? emptyProfile.linkedin,
  }
}

export function ProfilePage() {
  const { user, setUser } = useAuth()
  const [form, setForm] = useState<ProfileFormData>(() => buildFormData(user))
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [isSaving, setIsSaving] = useState(false)

  useEffect(() => {
    setForm(buildFormData(user))
  }, [user])

  function updateField<K extends keyof ProfileFormData>(key: K, value: ProfileFormData[K]) {
    setForm((prev) => ({ ...prev, [key]: value }))
  }

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

    try {
      const result = await updateProfile(form)
      setUser(result.user)
      setSuccess('Profile saved successfully.')
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'Unable to save profile.')
    } finally {
      setIsSaving(false)
    }
  }

  return (
    <main className={pageStyles.content}>
      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>Profile</h2>
          <p className={pageStyles.pageSubtitle}>
            Manage your personal information and contact details.
          </p>
        </div>
      </div>

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

        <section className={styles.section}>
          <h3 className={styles.sectionTitle}>General</h3>
          <div className={styles.grid}>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="firstName">First name (FA)</label>
              <input
                id="firstName"
                type="text"
                value={form.firstName}
                onChange={(e) => updateField('firstName', e.target.value)}
                placeholder="First name"
                dir="rtl"
                lang="fa"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="lastName">Last name (FA)</label>
              <input
                id="lastName"
                type="text"
                value={form.lastName}
                onChange={(e) => updateField('lastName', e.target.value)}
                placeholder="Last name"
                dir="rtl"
                lang="fa"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="firstNameEn">First name (EN)</label>
              <input
                id="firstNameEn"
                type="text"
                value={form.firstNameEn}
                onChange={(e) => updateField('firstNameEn', e.target.value)}
                placeholder="First name"
                dir="ltr"
                lang="en"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="lastNameEn">Last name (EN)</label>
              <input
                id="lastNameEn"
                type="text"
                value={form.lastNameEn}
                onChange={(e) => updateField('lastNameEn', e.target.value)}
                placeholder="Last name"
                dir="ltr"
                lang="en"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="cellNumber">Cell number</label>
              <input
                id="cellNumber"
                type="tel"
                value={form.cellNumber}
                readOnly
                className={styles.readOnly}
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="email">Email</label>
              <input
                id="email"
                type="email"
                value={form.email}
                onChange={(e) => updateField('email', e.target.value)}
                placeholder="you@example.com"
              />
            </div>
            <div className={`${styles.field} ${styles.fullWidth}`}>
              <label htmlFor="about">About yourself</label>
              <textarea
                id="about"
                value={form.about}
                onChange={(e) => updateField('about', e.target.value)}
                placeholder="Tell us a little about yourself..."
                rows={4}
              />
            </div>
          </div>
        </section>

        <section className={styles.section}>
          <h3 className={styles.sectionTitle}>Address</h3>
          <div className={styles.grid}>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="city">City</label>
              <input
                id="city"
                type="text"
                value={form.city}
                onChange={(e) => updateField('city', e.target.value)}
                placeholder="City"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="postalCode">Postal code</label>
              <input
                id="postalCode"
                type="text"
                value={form.postalCode}
                onChange={(e) => updateField('postalCode', e.target.value)}
                placeholder="1234567890"
              />
            </div>
            <div className={`${styles.field} ${styles.fullWidth}`}>
              <label htmlFor="address">Address</label>
              <input
                id="address"
                type="text"
                value={form.address}
                onChange={(e) => updateField('address', e.target.value)}
                placeholder="Street address"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="landline">Landline</label>
              <input
                id="landline"
                type="tel"
                value={form.landline}
                onChange={(e) => updateField('landline', e.target.value)}
                placeholder="02112345678"
              />
            </div>
          </div>
        </section>

        <section className={styles.section}>
          <h3 className={styles.sectionTitle}>Social media</h3>
          <div className={styles.grid}>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="instagram">Instagram</label>
              <input
                id="instagram"
                type="text"
                value={form.instagram}
                onChange={(e) => updateField('instagram', e.target.value)}
                placeholder="@username"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="telegramId">Telegram ID</label>
              <input
                id="telegramId"
                type="text"
                value={form.telegramId}
                onChange={(e) => updateField('telegramId', e.target.value)}
                placeholder="@username"
              />
            </div>
            <div className={`${styles.field} ${styles.col3}`}>
              <label htmlFor="linkedin">LinkedIn</label>
              <input
                id="linkedin"
                type="url"
                value={form.linkedin}
                onChange={(e) => updateField('linkedin', e.target.value)}
                placeholder="https://linkedin.com/in/username"
              />
            </div>
          </div>
        </section>

        <div className={styles.actions}>
          <button type="submit" className={styles.saveBtn} disabled={isSaving}>
            <Save size={18} />
            {isSaving ? 'Saving...' : 'Save changes'}
          </button>
        </div>
      </form>
    </main>
  )
}
