'use client'

import React, { useEffect, useState } from 'react'
import Link from 'next/link'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { motion } from 'framer-motion'
import { Button } from '@/components/ui'
import './page.css'

type Status = 'PENDING' | 'APPROVED' | 'REJECTED' | 'REVISION'

interface UserProfile {
  bio?: string | null
  location?: string | null
  phone?: string | null
  website?: string | null
  instagram?: string | null
  droneEquipment?: string | null
  certA1A3?: boolean
  certA2?: boolean
  certSTS01?: boolean
  certSTS02?: boolean
  certLUC?: boolean
  droneClasses?: string[]
  hasInsurance?: boolean
  certNotes?: string | null
}

interface ProfileData {
  user: {
    id: string; name: string | null; email: string; role: string
    image: string | null; createdAt: string; profile: UserProfile | null
  }
  spots: { id: string; name: string; status: Status; difficulty: string; createdAt: string; viewCount: number }[]
  reviews: { id: string; rating: number; body: string; status: Status; createdAt: string; spot: { id: string; name: string } }[]
}

const STATUS_LABELS: Record<Status, string> = {
  PENDING: 'Pendente', APPROVED: 'Aprovado', REJECTED: 'Rejeitado', REVISION: 'Em revisão',
}

const DRONE_CLASSES = ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6']

const CERTS = [
  { key: 'certA1A3', label: 'A1/A3', desc: 'Categoria Aberta — subcategorias A1 e A3' },
  { key: 'certA2',   label: 'A2',    desc: 'Categoria Aberta — subcategoria A2' },
  { key: 'certSTS01',label: 'STS-01',desc: 'Cenário Padrão 01 (BVLOS em área pouco populosa)' },
  { key: 'certSTS02',label: 'STS-02',desc: 'Cenário Padrão 02 (BVLOS em área urbana)' },
  { key: 'certLUC',  label: 'LUC',   desc: 'Light UAS Operator Certificate' },
] as const

export default function PerfilPage() {
  const { status: authStatus } = useSession()
  const router = useRouter()
  const [data, setData] = useState<ProfileData | null>(null)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [saveMsg, setSaveMsg] = useState('')

  // Form state — account
  const [name, setName] = useState('')
  // Form state — profile
  const [bio, setBio] = useState('')
  const [location, setLocation] = useState('')
  const [phone, setPhone] = useState('')
  const [website, setWebsite] = useState('')
  const [instagram, setInstagram] = useState('')
  const [droneEquipment, setDroneEquipment] = useState('')
  const [certA1A3, setCertA1A3] = useState(false)
  const [certA2, setCertA2] = useState(false)
  const [certSTS01, setCertSTS01] = useState(false)
  const [certSTS02, setCertSTS02] = useState(false)
  const [certLUC, setCertLUC] = useState(false)
  const [droneClasses, setDroneClasses] = useState<string[]>([])
  const [hasInsurance, setHasInsurance] = useState(false)
  const [certNotes, setCertNotes] = useState('')

  useEffect(() => {
    if (authStatus === 'unauthenticated') { router.replace('/auth/login'); return }
    if (authStatus !== 'authenticated') return
    fetch('/api/user/me')
      .then((r) => r.json())
      .then((d: ProfileData) => {
        setData(d)
        setName(d.user?.name ?? '')
        const p = d.user?.profile
        if (p) {
          setBio(p.bio ?? '')
          setLocation(p.location ?? '')
          setPhone(p.phone ?? '')
          setWebsite(p.website ?? '')
          setInstagram(p.instagram ?? '')
          setDroneEquipment(p.droneEquipment ?? '')
          setCertA1A3(p.certA1A3 ?? false)
          setCertA2(p.certA2 ?? false)
          setCertSTS01(p.certSTS01 ?? false)
          setCertSTS02(p.certSTS02 ?? false)
          setCertLUC(p.certLUC ?? false)
          setDroneClasses(p.droneClasses ?? [])
          setHasInsurance(p.hasInsurance ?? false)
          setCertNotes(p.certNotes ?? '')
        }
        setLoading(false)
      })
  }, [authStatus, router])

  const toggleClass = (cls: string) =>
    setDroneClasses((prev) => prev.includes(cls) ? prev.filter((c) => c !== cls) : [...prev, cls])

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    setSaveMsg('')
    const res = await fetch('/api/user/me', {
      method: 'PATCH',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name,
        bio, location, phone, website, instagram, droneEquipment,
        certA1A3, certA2, certSTS01, certSTS02, certLUC,
        droneClasses, hasInsurance, certNotes,
      }),
    })
    setSaveMsg(res.ok ? 'Perfil guardado!' : 'Erro ao guardar.')
    if (res.ok) {
      const d = await res.json()
      setData((prev) => prev ? { ...prev, user: { ...prev.user, ...d.user } } : prev)
    }
    setSaving(false)
    setTimeout(() => setSaveMsg(''), 3000)
  }

  if (authStatus === 'loading' || loading) {
    return <div className="perfil-page"><div className="perfil-container"><div className="perfil-empty">A carregar…</div></div></div>
  }

  if (!data) return null
  const { user, spots, reviews } = data
  const initials = (user.name ?? user.email).charAt(0).toUpperCase()

  return (
    <div className="perfil-page">
      <div className="perfil-container">

        {/* Hero */}
        <motion.div className="perfil-hero"
          initial={{ opacity: 0, y: 16 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35 }}>
          <div className="perfil-avatar">{initials}</div>
          <div className="perfil-info">
            <h1 className="perfil-name">{user.name ?? '(sem nome)'}</h1>
            <p className="perfil-email">{user.email}</p>
            <span className="perfil-role-badge">{user.role}</span>
            <div className="perfil-stats">
              <div className="perfil-stat"><span className="perfil-stat-num">{spots.length}</span><span className="perfil-stat-label">Spots</span></div>
              <div className="perfil-stat"><span className="perfil-stat-num">{reviews.length}</span><span className="perfil-stat-label">Reviews</span></div>
              <div className="perfil-stat"><span className="perfil-stat-num">{spots.filter((s) => s.status === 'APPROVED').length}</span><span className="perfil-stat-label">Aprovados</span></div>
            </div>
          </div>
          {(user.role === 'ADMIN' || user.role === 'MODERATOR') && (
            <Link href="/admin" className="perfil-admin-link">Backoffice →</Link>
          )}
        </motion.div>

        {/* Left col: edit form */}
        <div className="perfil-main-col">
        <motion.form className="perfil-card" onSubmit={handleSave}
          initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.05 }}>

          {/* Conta */}
          <div className="perfil-card-header">
            <h2 className="perfil-card-title">Definições de conta</h2>
          </div>
          <div className="perfil-card-body">
            <div className="perfil-field-grid">
              <div className="form-group">
                <label className="form-label" htmlFor="p-name">Nome de exibição</label>
                <input id="p-name" className="form-input" value={name} onChange={(e) => setName(e.target.value)} minLength={2} maxLength={60} required />
              </div>
            </div>
          </div>

          {/* Contactos */}
          <div className="perfil-card-header perfil-card-header--inner">
            <h2 className="perfil-card-title">Contactos e localização</h2>
          </div>
          <div className="perfil-card-body">
            <div className="perfil-field-grid perfil-field-grid--2">
              <div className="form-group">
                <label className="form-label" htmlFor="p-location">Localização</label>
                <input id="p-location" className="form-input" value={location} onChange={(e) => setLocation(e.target.value)} maxLength={100} placeholder="Ex: Lisboa, Portugal" />
              </div>
              <div className="form-group">
                <label className="form-label" htmlFor="p-phone">Telemóvel</label>
                <input id="p-phone" className="form-input" value={phone} onChange={(e) => setPhone(e.target.value)} maxLength={20} placeholder="+351 9xx xxx xxx" type="tel" />
              </div>
              <div className="form-group">
                <label className="form-label" htmlFor="p-website">Website</label>
                <input id="p-website" className="form-input" value={website} onChange={(e) => setWebsite(e.target.value)} maxLength={200} placeholder="https://..." type="url" />
              </div>
              <div className="form-group">
                <label className="form-label" htmlFor="p-instagram">Instagram</label>
                <input id="p-instagram" className="form-input" value={instagram} onChange={(e) => setInstagram(e.target.value)} maxLength={50} placeholder="@username" />
              </div>
            </div>
            <div className="form-group">
              <label className="form-label" htmlFor="p-bio">Bio</label>
              <textarea id="p-bio" className="form-input" value={bio} onChange={(e) => setBio(e.target.value)} rows={3} maxLength={500} placeholder="Conta-nos um pouco sobre ti como piloto…" style={{ resize: 'vertical' }} />
            </div>
          </div>

          {/* Equipamento */}
          <div className="perfil-card-header perfil-card-header--inner">
            <h2 className="perfil-card-title">Equipamento</h2>
          </div>
          <div className="perfil-card-body">
            <div className="form-group">
              <label className="form-label" htmlFor="p-drones">Drones que operas</label>
              <input id="p-drones" className="form-input" value={droneEquipment} onChange={(e) => setDroneEquipment(e.target.value)} maxLength={300} placeholder="Ex: DJI Mini 4 Pro, Autel EVO Nano+" />
              <p className="perfil-field-hint">Separa múltiplos drones por vírgula</p>
            </div>

            <div>
              <label className="form-label" style={{ display: 'block', marginBottom: 'var(--ov-space-2)' }}>
                Classes de drone (Reg. EU 2019/945)
              </label>
              <div className="perfil-class-grid">
                {DRONE_CLASSES.map((cls) => (
                  <label key={cls} className={`perfil-class-chip ${droneClasses.includes(cls) ? 'perfil-class-chip--active' : ''}`}>
                    <input type="checkbox" checked={droneClasses.includes(cls)} onChange={() => toggleClass(cls)} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} />
                    {cls}
                  </label>
                ))}
              </div>
              <p className="perfil-field-hint">C0 &lt;250g · C1 250g–900g · C2 900g–4kg · C3 4–25kg · C4 25–150kg</p>
            </div>
          </div>

          {/* Certificações EU */}
          <div className="perfil-card-header perfil-card-header--inner">
            <h2 className="perfil-card-title">Certificações — Reg. EU 2019/947</h2>
          </div>
          <div className="perfil-card-body">
            <div className="perfil-cert-list">
              {CERTS.map(({ key, label, desc }) => {
                const vals: Record<string, boolean> = { certA1A3, certA2, certSTS01, certSTS02, certLUC }
                const setters: Record<string, (v: boolean) => void> = {
                  certA1A3: setCertA1A3, certA2: setCertA2,
                  certSTS01: setCertSTS01, certSTS02: setCertSTS02, certLUC: setCertLUC,
                }
                return (
                  <label key={key} className={`perfil-cert-row ${vals[key] ? 'perfil-cert-row--active' : ''}`}>
                    <input type="checkbox" checked={vals[key]} onChange={(e) => setters[key](e.target.checked)} className="perfil-cert-check" />
                    <div>
                      <span className="perfil-cert-label">{label}</span>
                      <span className="perfil-cert-desc">{desc}</span>
                    </div>
                  </label>
                )
              })}
              <label className={`perfil-cert-row ${hasInsurance ? 'perfil-cert-row--active' : ''}`}>
                <input type="checkbox" checked={hasInsurance} onChange={(e) => setHasInsurance(e.target.checked)} className="perfil-cert-check" />
                <div>
                  <span className="perfil-cert-label">Seguro RC</span>
                  <span className="perfil-cert-desc">Seguro de responsabilidade civil para UAS</span>
                </div>
              </label>
            </div>
            <div className="form-group" style={{ marginTop: 'var(--ov-space-4)' }}>
              <label className="form-label" htmlFor="p-certnotes">Notas / outras licenças</label>
              <textarea id="p-certnotes" className="form-input" value={certNotes} onChange={(e) => setCertNotes(e.target.value)} rows={2} maxLength={300} placeholder="Ex: ATPL(A), número de registo UAS: PTR-XXXXXXXX…" style={{ resize: 'vertical' }} />
            </div>
          </div>

          {/* Save */}
          <div className="perfil-card-footer">
            <Button type="submit" variant="primary" loading={saving}>
              Guardar perfil
            </Button>
            {saveMsg && (
              <span className={`perfil-save-msg ${saveMsg.includes('Erro') ? 'perfil-save-msg--error' : ''}`}>
                {saveMsg}
              </span>
            )}
          </div>
        </motion.form>
        </div>{/* end perfil-main-col */}

        {/* Right col: activity sidebar */}
        <div className="perfil-side-col">
        {/* My spots */}
        <motion.div className="perfil-card"
          initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.1 }}>
          <div className="perfil-card-header">
            <h2 className="perfil-card-title">Os meus spots</h2>
            <Link href="/spots/novo" className="perfil-card-action">+ Novo spot</Link>
          </div>
          <div className="perfil-card-body perfil-card-body--flush">
            {spots.length === 0 ? (
              <p className="perfil-empty">Ainda não submeteste nenhum spot.</p>
            ) : spots.map((spot) => (
              <Link key={spot.id} href={`/spots/${spot.id}`} className="perfil-spot-row">
                <span className="perfil-spot-name">{spot.name}</span>
                <span className="perfil-spot-meta">{spot.viewCount} views</span>
                <span className={`perfil-status perfil-status--${spot.status}`}>{STATUS_LABELS[spot.status]}</span>
              </Link>
            ))}
          </div>
        </motion.div>

        {/* My reviews */}
        <motion.div className="perfil-card"
          initial={{ opacity: 0, y: 12 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.15 }}>
          <div className="perfil-card-header">
            <h2 className="perfil-card-title">As minhas reviews</h2>
          </div>
          <div className="perfil-card-body perfil-card-body--flush">
            {reviews.length === 0 ? (
              <p className="perfil-empty">Ainda não escreveste nenhuma review.</p>
            ) : reviews.map((review) => (
              <Link key={review.id} href={`/spots/${review.spot.id}`} className="perfil-spot-row">
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="perfil-spot-name">{review.spot.name}</div>
                  <div className="perfil-spot-meta">{'★'.repeat(review.rating)}{'☆'.repeat(5 - review.rating)} · {review.body.slice(0, 60)}{review.body.length > 60 ? '…' : ''}</div>
                </div>
                <span className={`perfil-status perfil-status--${review.status}`}>{STATUS_LABELS[review.status]}</span>
              </Link>
            ))}
          </div>
        </motion.div>
        </div>{/* end perfil-side-col */}

      </div>
    </div>
  )
}
