'use client'

import { useState } from 'react'

type FormState = 'idle' | 'loading' | 'success' | 'error'

const T = {
  ink: '#0B1220',
  inkSoft: 'rgba(11,18,32,0.6)',
  border: 'rgba(11,18,32,0.12)',
  orange: '#F2600C',
  orangeSoft: '#FFF1E6',
  fontHead: '"Archivo", sans-serif',
}

export default function ContactFormV2() {
  const [state, setState] = useState<FormState>('idle')
  const [form, setForm] = useState({ name: '', org: '', email: '', phone: '', _hp: '' })

  const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement>) =>
    setForm(p => ({ ...p, [k]: e.target.value }))

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (form._hp) return
    setState('loading')
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: form.name, email: form.email, barNo: form.org, message: form.phone }),
      })
      setState(res.ok ? 'success' : 'error')
    } catch {
      setState('error')
    }
  }

  if (state === 'success') {
    return (
      <div style={{ borderRadius: '24px', padding: '40px', textAlign: 'center', background: T.orangeSoft, border: `1px solid ${T.border}` }}>
        <div style={{ width: '48px', height: '48px', borderRadius: '50%', background: T.orange, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px', color: '#fff', fontSize: '22px' }}>✓</div>
        <h3 style={{ fontFamily: T.fontHead, fontWeight: 800, fontSize: '20px', margin: '0 0 8px', color: T.ink }}>Talebiniz alındı!</h3>
        <p style={{ fontSize: '14px', margin: 0, color: T.inkSoft }}>
          Kurucu ekipten kısa süre içinde size dönüş yapılacak.
        </p>
      </div>
    )
  }

  const inputStyle: React.CSSProperties = {
    width: '100%', minHeight: '46px', padding: '10px 16px',
    fontFamily: 'inherit', fontSize: '14px', color: T.ink,
    background: '#fff',
    border: `1.5px solid ${T.border}`,
    borderRadius: '12px',
    transition: 'border-color .15s, box-shadow .15s',
    boxSizing: 'border-box',
    outline: 'none',
  }

  const labelStyle: React.CSSProperties = {
    display: 'block', fontSize: '13px', fontWeight: 600,
    marginBottom: '6px', color: T.ink,
  }

  const focusOn = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.style.borderColor = T.orange
    e.target.style.boxShadow = `0 0 0 4px ${T.orangeSoft}`
  }
  const focusOff = (e: React.FocusEvent<HTMLInputElement>) => {
    e.target.style.borderColor = T.border
    e.target.style.boxShadow = 'none'
  }

  return (
    <form
      onSubmit={handleSubmit}
      style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))',
        gap: '18px',
        borderRadius: '24px',
        border: `1px solid ${T.border}`,
        padding: '32px',
        background: '#fff',
        boxShadow: '0 12px 40px rgba(11,18,32,0.06)',
      }}
      noValidate
    >
      <div aria-hidden="true" style={{ display: 'none' }} tabIndex={-1}>
        <input type="text" name="_hp" value={form._hp} onChange={set('_hp')} autoComplete="off" tabIndex={-1} />
      </div>

      <div style={{ gridColumn: 'span 1' }}>
        <label style={labelStyle} htmlFor="af2_name">Ad Soyad <span style={{ color: T.orange }}>*</span></label>
        <input id="af2_name" type="text" required placeholder="Av. Ayşe Yılmaz" value={form.name} onChange={set('name')} style={inputStyle} onFocus={focusOn} onBlur={focusOff} />
      </div>

      <div>
        <label style={labelStyle} htmlFor="af2_org">Büro / Kurum</label>
        <input id="af2_org" type="text" placeholder="Yılmaz Hukuk Bürosu" value={form.org} onChange={set('org')} style={inputStyle} onFocus={focusOn} onBlur={focusOff} />
      </div>

      <div>
        <label style={labelStyle} htmlFor="af2_email">E-posta <span style={{ color: T.orange }}>*</span></label>
        <input id="af2_email" type="email" required placeholder="ayse@buro.com" value={form.email} onChange={set('email')} style={inputStyle} onFocus={focusOn} onBlur={focusOff} />
      </div>

      <div>
        <label style={labelStyle} htmlFor="af2_phone">Telefon</label>
        <input id="af2_phone" type="tel" placeholder="0532 000 00 00" value={form.phone} onChange={set('phone')} style={inputStyle} onFocus={focusOn} onBlur={focusOff} />
      </div>

      {state === 'error' && (
        <div style={{ gridColumn: '1 / -1', fontSize: '13px', color: '#DC2626' }}>
          Bir hata oluştu. Lütfen tekrar deneyin veya{' '}
          <a href="mailto:info@ayris.tech" style={{ color: '#DC2626' }}>info@ayris.tech</a> adresine yazın.
        </div>
      )}

      <button
        type="submit"
        disabled={state === 'loading'}
        style={{
          gridColumn: '1 / -1',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '8px',
          cursor: state === 'loading' ? 'not-allowed' : 'pointer',
          fontFamily: 'inherit', fontWeight: 700, fontSize: '15px',
          color: '#fff',
          background: T.orange,
          border: 'none',
          borderRadius: '999px',
          padding: '15px',
          transition: 'background .15s, transform .1s',
          opacity: state === 'loading' ? 0.7 : 1,
          marginTop: '4px',
        }}
        onMouseEnter={e => { if (state !== 'loading') (e.currentTarget as HTMLElement).style.background = '#D94E00' }}
        onMouseLeave={e => { if (state !== 'loading') (e.currentTarget as HTMLElement).style.background = T.orange }}
      >
        {state === 'loading' ? 'Gönderiliyor…' : 'Demo Talep Et →'}
      </button>
    </form>
  )
}
