"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"

export function ProfileForm({ profile }: { profile: any }) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  const inputClass = "w-full rounded-lg border border-white/10 bg-white/5 px-4 py-2.5 text-sm text-white placeholder-white/30 outline-none ring-indigo-500 transition focus:border-indigo-500/50 focus:ring-1"
  const labelClass = "mb-1.5 block text-sm font-medium text-white/70"

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

    const formData = new FormData(e.currentTarget)

    const res = await fetch("/api/profile", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        full_name: formData.get("full_name") as string,
        phone: (formData.get("phone") as string) || null,
        company_name: (formData.get("company_name") as string) || null,
      }),
    })

    setLoading(false)

    if (!res.ok) {
      const data = await res.json().catch(() => ({}))
      setError(typeof data.error === "string" ? data.error : "Failed to save profile")
      return
    }

    toast.success("Profile saved")
    router.refresh()
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-5 rounded-xl border border-white/[0.06] bg-[#16161f] p-6">
      {error && (
        <div className="rounded-lg border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div>
      )}


      <div>
        <label className={labelClass}>Email</label>
        <input value={profile?.email ?? ""} disabled className={inputClass + " opacity-50 cursor-not-allowed"} readOnly />
        <p className="mt-1 text-xs text-white/30">Email cannot be changed</p>
      </div>

      <div>
        <label className={labelClass}>Full Name</label>
        <input name="full_name" defaultValue={profile?.full_name ?? ""} placeholder="John Smith" className={inputClass} />
      </div>

      <div>
        <label className={labelClass}>Phone</label>
        <input name="phone" defaultValue={profile?.phone ?? ""} placeholder="+1 555 000 0000" className={inputClass} />
      </div>

      <div>
        <label className={labelClass}>Company / Business Name</label>
        <input name="company_name" defaultValue={profile?.company_name ?? ""} placeholder="Smith Property Management" className={inputClass} />
      </div>

      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-lg bg-indigo-600 py-2.5 text-sm font-semibold text-white hover:bg-indigo-500 disabled:opacity-50 transition"
      >
        {loading ? "Saving..." : "Save Changes"}
      </button>
    </form>
  )
}
