// src/app/(dashboard)/profile/page.tsx
'use client'

import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import { Button } from '@/components/ui/Button'
import { Input } from '@/components/ui/Input'
import { Textarea } from '@/components/ui/Textarea'
import { Spinner } from '@/components/ui/Spinner'

interface ProfileData {
  location?: string
  phone?: string
  bio?: string
  headline?: string
  skills?: string
  portfolioUrl?: string
  avatarUrl?: string
}

export default function ProfilePage() {
  const { data: session } = useSession()
  const [profile, setProfile] = useState<ProfileData>({})
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    fetch('/api/profile')
      .then((r) => r.json())
      .then((d) => {
        if (d.profile) setProfile(d.profile)
      })
      .finally(() => setLoading(false))
  }, [])

  function update(field: string, value: string) {
    setProfile((p) => ({ ...p, [field]: value }))
    setSuccess(false)
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true)
    setError('')
    setSuccess(false)

    try {
      const res = await fetch('/api/profile', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(profile),
      })
      if (!res.ok) {
        const d = await res.json()
        setError(d.error ?? 'Failed to save')
      } else {
        setSuccess(true)
      }
    } catch {
      setError('Something went wrong.')
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Spinner size="lg" />
      </div>
    )
  }

  return (
    <div className="max-w-2xl">
      <div className="page-header">
        <h1 className="page-title">Profile Settings</h1>
        <p className="page-subtitle">Update your public profile information</p>
      </div>

      {/* Account info (read-only) */}
      <div className="card p-6 mb-6">
        <h2 className="section-title">Account Information</h2>
        <div className="grid sm:grid-cols-2 gap-4 text-sm">
          <div>
            <p className="text-neutral-500">Name</p>
            <p className="font-semibold text-neutral-900 mt-0.5">
              {session?.user?.name} {session?.user?.surname}
            </p>
          </div>
          <div>
            <p className="text-neutral-500">Email</p>
            <p className="font-semibold text-neutral-900 mt-0.5">{session?.user?.email}</p>
          </div>
          <div>
            <p className="text-neutral-500">Role</p>
            <p className="font-semibold text-neutral-900 mt-0.5">
              {session?.user?.role?.replace(/_/g, ' ')}
            </p>
          </div>
        </div>
      </div>

      <form onSubmit={handleSave} className="card p-6 space-y-5">
        <h2 className="section-title">Public Profile</h2>

        {error && (
          <div className="p-3 bg-red-50 border border-red-200 rounded-xl text-sm text-red-700">{error}</div>
        )}
        {success && (
          <div className="p-3 bg-emerald-50 border border-emerald-200 rounded-xl text-sm text-emerald-700">
            Profile saved successfully!
          </div>
        )}

        <Input
          label="Professional headline"
          id="profile-headline"
          value={profile.headline ?? ''}
          onChange={(e) => update('headline', e.target.value)}
          placeholder="e.g. Senior Frontend Developer"
          maxLength={120}
        />
        <div className="grid sm:grid-cols-2 gap-4">
          <Input
            label="Location"
            id="profile-location"
            value={profile.location ?? ''}
            onChange={(e) => update('location', e.target.value)}
            placeholder="e.g. Cape Town, ZA"
          />
          <Input
            label="Phone number"
            id="profile-phone"
            type="tel"
            value={profile.phone ?? ''}
            onChange={(e) => update('phone', e.target.value)}
            placeholder="+27 82 555 0101"
          />
        </div>
        <Textarea
          label="Bio"
          id="profile-bio"
          value={profile.bio ?? ''}
          onChange={(e) => update('bio', e.target.value)}
          placeholder="A brief introduction about yourself..."
          maxLength={500}
          className="min-h-[120px]"
        />
        <Input
          label="Skills (comma-separated)"
          id="profile-skills"
          value={profile.skills ?? ''}
          onChange={(e) => update('skills', e.target.value)}
          placeholder="React, TypeScript, Node.js"
        />
        <Input
          label="Portfolio URL"
          id="profile-portfolio"
          type="url"
          value={profile.portfolioUrl ?? ''}
          onChange={(e) => update('portfolioUrl', e.target.value)}
          placeholder="https://yoursite.com"
        />

        <div className="pt-2">
          <Button type="submit" loading={saving} size="lg">
            Save Profile
          </Button>
        </div>
      </form>
    </div>
  )
}
