'use client'

import { useState } from 'react'
import Link from 'next/link'

export default function RegisterPage() {
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setError(null)

    const fd = new FormData(e.currentTarget)
    const contactName = String(fd.get('contactName') ?? '').trim()
    const companyName = String(fd.get('companyName') ?? '').trim()
    const phone = String(fd.get('phone') ?? '').trim()
    const email = String(fd.get('email') ?? '').trim()
    const password = String(fd.get('password') ?? '')
    const passwordConfirm = String(fd.get('passwordConfirm') ?? '')

    if (!contactName || !companyName || !phone || !email || !password) {
      setError('Lütfen tüm alanları doldurun.')
      return
    }
    if (password.length < 8) {
      setError('Şifre en az 8 karakter olmalıdır.')
      return
    }
    if (password !== passwordConfirm) {
      setError('Şifreler eşleşmiyor.')
      return
    }

    setLoading(true)
    try {
      const res = await fetch('/api/register', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contactName, companyName, phone, email, password, passwordConfirm }),
      })
      const data = await res.json().catch(() => ({}))
      if (!res.ok) {
        setError(data.error ?? 'Başvuru gönderilemedi.')
        return
      }
      setSuccess(data.message ?? 'Başvurunuz alındı. Ekibimiz en kısa sürede değerlendirip size dönüş yapacaktır.')
    } catch {
      setError('Bir hata oluştu. Lütfen tekrar deneyin.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="min-h-screen flex bg-dark">
      {/* Left branding panel */}
      <div className="hidden md:flex flex-1 flex-col justify-between p-12 bg-[#141414]">
        <div>
          <p className="font-display text-2xl text-cream">
            Peyzaj<span className="text-orange">Art</span>
          </p>
          <p className="font-body text-xs tracking-widest uppercase text-cream/30 mt-1">Bayi Başvurusu</p>
        </div>
        <div>
          <p className="font-display text-3xl font-light text-cream/80 leading-snug max-w-xs">
            Bayimiz olun, toplu alım avantajlarından yararlanın.
          </p>
          <div className="mt-8 space-y-3">
            {['USD sabit fiyat', 'Öncelikli üretim', 'Özel bayi indirimi'].map(f => (
              <div key={f} className="flex items-center gap-2">
                <span className="w-4 h-4 bg-orange/20 flex items-center justify-center">
                  <span className="w-1.5 h-1.5 bg-orange rounded-full" />
                </span>
                <span className="font-body text-sm text-cream/50">{f}</span>
              </div>
            ))}
          </div>
        </div>
        <p className="font-body text-xs text-cream/20">© {new Date().getFullYear()} PeyzajArt</p>
      </div>

      {/* Right form */}
      <div className="flex-1 flex items-center justify-center px-6 py-12">
        <div className="w-full max-w-sm">
          <div className="md:hidden text-center mb-10">
            <p className="font-display text-2xl text-cream">
              Peyzaj<span className="text-orange">Art</span>
            </p>
            <p className="font-body text-xs tracking-widest uppercase text-cream/30 mt-1">Bayi Başvurusu</p>
          </div>

          <h2 className="font-display text-3xl font-light text-cream mb-2">Bayi Başvurusu</h2>
          <p className="font-body text-sm text-cream/40 mb-8">
            Bilgilerinizi doldurun, ekibimiz en kısa sürede başvurunuzu değerlendirsin.
          </p>

          {success ? (
            <div className="font-body text-sm text-green-200 bg-green-900/20 rounded-lg px-5 py-6 border border-green-600/30 text-center">
              <p className="font-display text-xl text-green-100 mb-2">Başvurunuz Alındı</p>
              <p>{success}</p>
              <Link href="/login"
                className="mt-5 inline-block px-6 py-2.5 rounded-lg border border-orange/60 text-orange font-body text-xs tracking-widest uppercase hover:bg-orange hover:text-cream transition-colors">
                Giriş Sayfasına Dön
              </Link>
            </div>
          ) : (
            <>
              <form onSubmit={handleSubmit} className="space-y-4">
                {[
                  { name: 'contactName', label: 'Ad Soyad', type: 'text', placeholder: 'Adınız Soyadınız' },
                  { name: 'companyName', label: 'Firma Adı', type: 'text', placeholder: 'Firma adı' },
                  { name: 'phone', label: 'Telefon', type: 'tel', placeholder: '+90 5XX XXX XX XX' },
                  { name: 'email', label: 'E-posta', type: 'email', placeholder: 'ornek@firma.com' },
                ].map(field => (
                  <div key={field.name}>
                    <label className="block font-body text-xs tracking-widest uppercase text-cream/40 mb-2">
                      {field.label} *
                    </label>
                    <input type={field.type} name={field.name} placeholder={field.placeholder} required
                      className="w-full px-4 py-3 rounded-lg bg-white/5 border border-white/10 text-cream font-body text-sm placeholder-cream/20 focus:outline-none focus:border-orange transition-colors" />
                  </div>
                ))}

                <div>
                  <label className="block font-body text-xs tracking-widest uppercase text-cream/40 mb-2">
                    Şifre * <span className="lowercase tracking-normal text-cream/25">(en az 8 karakter)</span>
                  </label>
                  <input type="password" name="password" required minLength={8}
                    className="w-full px-4 py-3 rounded-lg bg-white/5 border border-white/10 text-cream font-body text-sm focus:outline-none focus:border-orange transition-colors" />
                </div>
                <div>
                  <label className="block font-body text-xs tracking-widest uppercase text-cream/40 mb-2">
                    Şifre Tekrar *
                  </label>
                  <input type="password" name="passwordConfirm" required minLength={8}
                    className="w-full px-4 py-3 rounded-lg bg-white/5 border border-white/10 text-cream font-body text-sm focus:outline-none focus:border-orange transition-colors" />
                </div>

                {error && (
                  <p className="font-body text-sm text-red-400 bg-red-900/20 rounded-lg px-4 py-3 border border-red-800/30">
                    {error}
                  </p>
                )}

                <button type="submit" disabled={loading}
                  className="w-full py-3 rounded-lg bg-orange text-cream font-body text-sm tracking-widest uppercase hover:bg-orange-hover transition-colors disabled:opacity-60">
                  {loading ? 'Gönderiliyor...' : 'Başvuru Gönder'}
                </button>
              </form>

              <div className="mt-8 pt-6 border-t border-white/10 text-center">
                <p className="font-body text-sm text-cream/40">
                  Zaten hesabınız var mı?{' '}
                  <Link href="/login" className="text-orange hover:text-orange-hover transition-colors">
                    Giriş Yapın →
                  </Link>
                </p>
              </div>
            </>
          )}
        </div>
      </div>
    </main>
  )
}
