'use client'

import { useState } from 'react'

interface Dealer {
  id: number
  dealerCode: string
  companyName: string
  contactName: string
  email: string
  phone: string | null
  address: string | null
  city: string | null
  discountRate: number
}

interface ProfileClientProps {
  dealer: Dealer
}

export default function ProfileClient({ dealer }: ProfileClientProps) {
  const [profile, setProfile] = useState({
    contactName: dealer.contactName,
    phone: dealer.phone ?? '',
    address: dealer.address ?? '',
    city: dealer.city ?? '',
  })
  const [profileSaving, setProfileSaving] = useState(false)
  const [profileMsg, setProfileMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  const [passwords, setPasswords] = useState({ current: '', next: '', confirm: '' })
  const [passSaving, setPassSaving] = useState(false)
  const [passMsg, setPassMsg] = useState<{ type: 'success' | 'error'; text: string } | null>(null)

  async function saveProfile(e: React.FormEvent) {
    e.preventDefault()
    setProfileSaving(true)
    setProfileMsg(null)
    try {
      const res = await fetch('/api/profile', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(profile),
      })
      if (res.ok) {
        setProfileMsg({ type: 'success', text: 'Profil güncellendi.' })
      } else {
        const d = await res.json()
        setProfileMsg({ type: 'error', text: d.error ?? 'Güncelleme başarısız.' })
      }
    } catch {
      setProfileMsg({ type: 'error', text: 'Bir hata oluştu.' })
    } finally {
      setProfileSaving(false)
    }
  }

  async function changePassword(e: React.FormEvent) {
    e.preventDefault()
    if (passwords.next !== passwords.confirm) {
      setPassMsg({ type: 'error', text: 'Yeni şifreler eşleşmiyor.' })
      return
    }
    setPassSaving(true)
    setPassMsg(null)
    try {
      const res = await fetch('/api/profile/password', {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ currentPassword: passwords.current, newPassword: passwords.next }),
      })
      const d = await res.json()
      if (res.ok) {
        setPassMsg({ type: 'success', text: 'Şifre başarıyla güncellendi.' })
        setPasswords({ current: '', next: '', confirm: '' })
      } else {
        setPassMsg({ type: 'error', text: d.error ?? 'Şifre güncellenemedi.' })
      }
    } catch {
      setPassMsg({ type: 'error', text: 'Bir hata oluştu.' })
    } finally {
      setPassSaving(false)
    }
  }

  const inputClass =
    'w-full px-3 py-2.5 rounded-lg border border-sand bg-cream font-body text-sm focus:outline-none focus:border-earth transition-colors'
  const labelClass = 'block font-body text-sm text-brown mb-1.5'

  return (
    <div className="space-y-6">
      {/* Firma bilgileri (salt okunur) */}
      <div className="bg-white p-6 shadow-sm rounded-xl">
        <h2 className="font-display text-xl text-brown mb-4">Firma Bilgileri</h2>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <div>
            <p className={labelClass}>Firma Adı</p>
            <p className="font-body text-sm text-brown bg-sand rounded-lg px-3 py-2.5">
              {dealer.companyName}
            </p>
          </div>
          <div>
            <p className={labelClass}>E-posta</p>
            <p className="font-body text-sm text-brown bg-sand rounded-lg px-3 py-2.5">
              {dealer.email}
            </p>
          </div>
        </div>
      </div>

      {/* Düzenlenebilir profil */}
      <form onSubmit={saveProfile} className="bg-white p-6 shadow-sm rounded-xl">
        <h2 className="font-display text-xl text-brown mb-5">İletişim Bilgileri</h2>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
          <div className="sm:col-span-2">
            <label className={labelClass}>Yetkili Adı Soyadı</label>
            <input
              type="text"
              value={profile.contactName}
              onChange={(e) => setProfile({ ...profile, contactName: e.target.value })}
              required
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Telefon</label>
            <input
              type="tel"
              value={profile.phone}
              onChange={(e) => setProfile({ ...profile, phone: e.target.value })}
              placeholder="+90 5xx xxx xx xx"
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Şehir</label>
            <input
              type="text"
              value={profile.city}
              onChange={(e) => setProfile({ ...profile, city: e.target.value })}
              placeholder="İstanbul"
              className={inputClass}
            />
          </div>
          <div className="sm:col-span-2">
            <label className={labelClass}>Teslimat Adresi</label>
            <textarea
              rows={3}
              value={profile.address}
              onChange={(e) => setProfile({ ...profile, address: e.target.value })}
              placeholder="Mahalle, cadde, bina no..."
              className={`${inputClass} resize-none`}
            />
          </div>
        </div>

        {profileMsg && (
          <p
            className={`mt-4 font-body text-sm rounded-lg px-3 py-2 ${
              profileMsg.type === 'success'
                ? 'bg-green-50 text-green-700'
                : 'bg-red-50 text-red-600'
            }`}
          >
            {profileMsg.text}
          </p>
        )}

        <div className="mt-5 flex justify-end">
          <button
            type="submit"
            disabled={profileSaving}
            className="px-6 py-2 rounded-lg bg-brown text-cream font-body text-sm tracking-widest uppercase hover:bg-earth transition-colors disabled:opacity-60"
          >
            {profileSaving ? 'Kaydediliyor...' : 'Kaydet'}
          </button>
        </div>
      </form>

      {/* Şifre değiştirme */}
      <form onSubmit={changePassword} className="bg-white p-6 shadow-sm rounded-xl">
        <h2 className="font-display text-xl text-brown mb-5">Şifre Değiştir</h2>

        <div className="space-y-4">
          <div>
            <label className={labelClass}>Mevcut Şifre</label>
            <input
              type="password"
              value={passwords.current}
              onChange={(e) => setPasswords({ ...passwords, current: e.target.value })}
              required
              autoComplete="current-password"
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Yeni Şifre</label>
            <input
              type="password"
              value={passwords.next}
              onChange={(e) => setPasswords({ ...passwords, next: e.target.value })}
              required
              minLength={8}
              autoComplete="new-password"
              className={inputClass}
            />
          </div>
          <div>
            <label className={labelClass}>Yeni Şifre (Tekrar)</label>
            <input
              type="password"
              value={passwords.confirm}
              onChange={(e) => setPasswords({ ...passwords, confirm: e.target.value })}
              required
              minLength={8}
              autoComplete="new-password"
              className={inputClass}
            />
          </div>
        </div>

        {passMsg && (
          <p
            className={`mt-4 font-body text-sm rounded-lg px-3 py-2 ${
              passMsg.type === 'success'
                ? 'bg-green-50 text-green-700'
                : 'bg-red-50 text-red-600'
            }`}
          >
            {passMsg.text}
          </p>
        )}

        <div className="mt-5 flex justify-end">
          <button
            type="submit"
            disabled={passSaving}
            className="px-6 py-2 rounded-lg bg-brown text-cream font-body text-sm tracking-widest uppercase hover:bg-earth transition-colors disabled:opacity-60"
          >
            {passSaving ? 'Güncelleniyor...' : 'Şifreyi Güncelle'}
          </button>
        </div>
      </form>
    </div>
  )
}
