'use client'

import { useActionState, useRef, useState } from 'react'
import Image from 'next/image'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { updateProfileAction } from '@/actions/profile'

interface ProfileEditorProps {
  bio: string | null
  bioDetail: string | null
  hasAvatar: boolean
  avatarVersion: number
}

const ALLOWED = ['image/jpeg', 'image/png', 'image/webp']
const MAX_BYTES = 12 * 1024 * 1024

export function ProfileEditor({ bio, bioDetail, hasAvatar, avatarVersion }: ProfileEditorProps) {
  const [state, formAction, isPending] = useActionState(updateProfileAction, null)
  const [avatarSrc, setAvatarSrc] = useState<string | null>(
    hasAvatar ? `/api/profile/avatar?v=${avatarVersion}` : null
  )
  const [uploadError, setUploadError] = useState<string | null>(null)
  const [uploading, setUploading] = useState(false)
  const fileRef = useRef<HTMLInputElement>(null)

  async function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    setUploadError(null)

    if (!ALLOWED.includes(file.type)) {
      setUploadError('Alleen JPEG, PNG en WebP zijn toegestaan')
      return
    }
    if (file.size > MAX_BYTES) {
      setUploadError('Bestand is groter dan 12 MB')
      return
    }

    const reader = new FileReader()
    reader.onload = (ev) => setAvatarSrc(ev.target?.result as string)
    reader.readAsDataURL(file)

    setUploading(true)
    try {
      const fd = new FormData()
      fd.append('avatar', file)
      const res = await fetch('/api/profile/avatar', { method: 'POST', body: fd })
      const data = await res.json()
      if (!res.ok) {
        setUploadError(data.error ?? 'Upload mislukt')
        setAvatarSrc(hasAvatar ? `/api/profile/avatar?v=${avatarVersion}` : null)
      }
    } finally {
      setUploading(false)
      if (fileRef.current) fileRef.current.value = ''
    }
  }

  return (
    <div className="space-y-5">
      <div className="flex items-center gap-5">
        <button
          type="button"
          onClick={() => fileRef.current?.click()}
          disabled={uploading}
          className="relative w-20 h-20 rounded-full bg-surface-container border border-border overflow-hidden flex items-center justify-center hover:opacity-80 transition-opacity shrink-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
          aria-label="Profielfoto wijzigen"
        >
          {avatarSrc ? (
            <Image src={avatarSrc} alt="Profielfoto" fill className="object-cover" unoptimized />
          ) : (
            <span className="text-3xl select-none text-muted-foreground">?</span>
          )}
          {uploading && (
            <div className="absolute inset-0 bg-background/70 flex items-center justify-center">
              <span className="text-xs text-foreground font-medium">Laden…</span>
            </div>
          )}
        </button>

        <div className="space-y-1.5">
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => fileRef.current?.click()}
            disabled={uploading}
          >
            {uploading ? 'Uploaden…' : 'Foto wijzigen'}
          </Button>
          <p className="text-xs text-muted-foreground">JPEG, PNG of WebP — max 12 MB</p>
          {uploadError && <p className="text-xs text-error">{uploadError}</p>}
        </div>

        <input
          ref={fileRef}
          type="file"
          accept="image/jpeg,image/png,image/webp"
          className="hidden"
          onChange={handleFile}
        />
      </div>

      <form action={formAction} className="space-y-4">
        <div className="space-y-1.5">
          <label htmlFor="bio" className="text-xs font-medium text-foreground">
            Korte omschrijving
          </label>
          <Input
            id="bio"
            name="bio"
            defaultValue={bio ?? ''}
            placeholder="Bijv. Full-stack developer bij Acme"
            maxLength={160}
            disabled={isPending}
          />
          <p className="text-xs text-muted-foreground">Max. 160 tekens</p>
        </div>

        <div className="space-y-1.5">
          <label htmlFor="bio_detail" className="text-xs font-medium text-foreground">
            Uitgebreide beschrijving
          </label>
          <Textarea
            id="bio_detail"
            name="bio_detail"
            defaultValue={bioDetail ?? ''}
            placeholder="Vertel meer over jezelf, je werkwijze of je projecten…"
            maxLength={2000}
            rows={5}
            disabled={isPending}
          />
          <p className="text-xs text-muted-foreground">Max. 2000 tekens</p>
        </div>

        <div className="flex items-center gap-3">
          <Button type="submit" size="sm" disabled={isPending}>
            {isPending ? 'Opslaan…' : 'Opslaan'}
          </Button>
          {state && 'success' in state && (
            <p className="text-xs text-success">Profiel opgeslagen.</p>
          )}
          {state && 'error' in state && typeof state.error === 'string' && (
            <p className="text-xs text-error">{state.error}</p>
          )}
        </div>
      </form>
    </div>
  )
}
