"use client"

import { useState, useRef, useTransition } from "react"
import { useRouter } from "next/navigation"
import { toast } from "sonner"
import { Camera, Loader2, X, Home } from "lucide-react"
import { updateBranding } from "@/app/actions/branding"

const HEX_RE = /^#[0-9a-fA-F]{6}$/

interface Props {
  brandName: string | null
  brandLogoUrl: string | null
  brandColor: string | null
  hidePoweredBy: boolean
}

export function BrandingForm({ brandName, brandLogoUrl, brandColor, hidePoweredBy }: Props) {
  const router = useRouter()
  const fileRef = useRef<HTMLInputElement>(null)
  const [isPending, startTransition] = useTransition()

  const [name, setName] = useState(brandName ?? "")
  const [logoUrl, setLogoUrl] = useState<string | null>(brandLogoUrl)
  const [color, setColor] = useState(brandColor ?? "#4f46e5")
  const [hidePb, setHidePb] = useState(hidePoweredBy)
  const [uploading, setUploading] = useState(false)
  const [error, setError] = useState("")

  const validColor = HEX_RE.test(color)
  const previewColor = validColor ? color : "#4f46e5"

  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 handleLogo(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    if (!file.type.startsWith("image/")) {
      toast.error("Please select an image file")
      return
    }
    if (file.size > 5 * 1024 * 1024) {
      toast.error("Logo must be under 5MB")
      return
    }

    setUploading(true)
    try {
      const fd = new FormData()
      fd.append("file", file)
      fd.append("scope", "misc")

      const res = await fetch("/api/upload", { method: "POST", body: fd })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(typeof data.error === "string" ? data.error : "Upload failed")
      }
      const { url } = await res.json()
      setLogoUrl(url)
      toast.success("Logo uploaded")
    } catch (err: any) {
      toast.error(err?.message ?? "Upload failed")
    } finally {
      setUploading(false)
      if (fileRef.current) fileRef.current.value = ""
    }
  }

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

    if (color.trim() && !validColor) {
      setError("Accent color must be a hex value like #4f46e5")
      return
    }

    const fd = new FormData()
    fd.set("brand_name", name)
    fd.set("brand_logo_url", logoUrl ?? "")
    fd.set("brand_color", color.trim() && validColor ? color : "")
    if (hidePb) fd.set("hide_powered_by", "on")

    startTransition(async () => {
      try {
        await updateBranding(fd)
        toast.success("Branding saved")
        router.refresh()
      } catch (err: any) {
        const msg = err?.message ?? "Failed to save branding"
        setError(msg)
        toast.error(msg)
      }
    })
  }

  return (
    <div className="grid gap-6 lg:grid-cols-[1fr_320px]">
      <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}>Brand Name</label>
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            maxLength={60}
            placeholder="Acme Property Management"
            className={inputClass}
          />
          <p className="mt-1 text-xs text-white/30">Shown in the tenant portal header instead of “Tenant Portal”.</p>
        </div>

        <div>
          <label className={labelClass}>Logo</label>
          {logoUrl ? (
            <div className="group relative h-28 w-full overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02]">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img src={logoUrl} alt="Brand logo" className="h-full w-full object-contain p-3" />
              <div className="absolute inset-0 flex items-center justify-center gap-2 bg-black/50 opacity-0 transition group-hover:opacity-100">
                <button
                  type="button"
                  onClick={() => fileRef.current?.click()}
                  disabled={uploading}
                  className="flex items-center gap-1.5 rounded-lg bg-white/10 px-3 py-2 text-xs text-white transition hover:bg-white/20"
                >
                  <Camera className="h-3.5 w-3.5" /> Change
                </button>
                <button
                  type="button"
                  onClick={() => setLogoUrl(null)}
                  disabled={uploading}
                  className="flex items-center gap-1.5 rounded-lg bg-red-500/20 px-3 py-2 text-xs text-red-400 transition hover:bg-red-500/30"
                >
                  <X className="h-3.5 w-3.5" /> Remove
                </button>
              </div>
              {uploading && (
                <div className="absolute inset-0 flex items-center justify-center bg-black/60">
                  <Loader2 className="h-6 w-6 animate-spin text-white" />
                </div>
              )}
            </div>
          ) : (
            <button
              type="button"
              onClick={() => fileRef.current?.click()}
              disabled={uploading}
              className="flex h-28 w-full flex-col items-center justify-center gap-2 rounded-xl border-2 border-dashed border-white/10 bg-white/[0.02] text-white/30 transition hover:border-indigo-500/40 hover:text-white/50 disabled:opacity-50"
            >
              {uploading ? (
                <Loader2 className="h-6 w-6 animate-spin" />
              ) : (
                <>
                  <Camera className="h-6 w-6" />
                  <span className="text-xs">Upload logo</span>
                </>
              )}
            </button>
          )}
          <input ref={fileRef} type="file" accept="image/*" className="hidden" onChange={handleLogo} />
          <p className="mt-1 text-xs text-white/30">PNG or SVG works best. Max 5MB.</p>
        </div>

        <div>
          <label className={labelClass}>Accent Color</label>
          <div className="flex items-center gap-3">
            <input
              type="color"
              value={previewColor}
              onChange={(e) => setColor(e.target.value)}
              className="h-10 w-12 shrink-0 cursor-pointer rounded-lg border border-white/10 bg-white/5 p-1"
              aria-label="Accent color picker"
            />
            <input
              value={color}
              onChange={(e) => setColor(e.target.value)}
              placeholder="#4f46e5"
              className={inputClass + (color.trim() && !validColor ? " border-red-500/40" : "")}
            />
          </div>
          <p className="mt-1 text-xs text-white/30">Used for highlights in the tenant portal. Hex like #RRGGBB.</p>
        </div>

        <label className="flex cursor-pointer items-start gap-3 rounded-lg border border-white/[0.06] bg-white/[0.02] p-4">
          <input
            type="checkbox"
            checked={hidePb}
            onChange={(e) => setHidePb(e.target.checked)}
            className="mt-0.5 h-4 w-4 accent-indigo-600"
          />
          <span>
            <span className="block text-sm font-medium text-white">Remove “Powered by” branding</span>
            <span className="mt-0.5 block text-xs text-white/40">
              Hides the “Powered by Property Management Network” line in the tenant portal.
            </span>
          </span>
        </label>

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

      {/* Live preview */}
      <div className="space-y-2">
        <p className="text-xs font-medium uppercase tracking-wide text-white/30">Preview</p>
        <div className="rounded-xl border border-white/[0.06] bg-[#16161f] p-5">
          <div className="mb-4 flex items-center gap-3">
            <div
              className="flex h-10 w-10 items-center justify-center overflow-hidden rounded-xl"
              style={{ backgroundColor: previewColor }}
            >
              {logoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={logoUrl} alt="Logo" className="h-full w-full object-contain p-1" />
              ) : (
                <Home className="h-5 w-5 text-white" />
              )}
            </div>
            <div>
              <p className="text-xs text-white/40">{name.trim() || "Tenant Portal"}</p>
              <h1 className="text-lg font-bold text-white">Jane Tenant</h1>
            </div>
          </div>
          <div className="rounded-lg border border-white/[0.06] p-3">
            <div className="flex items-center gap-2 text-sm" style={{ color: previewColor }}>
              <span className="h-2 w-2 rounded-full" style={{ backgroundColor: previewColor }} />
              <span className="font-medium">Rent History</span>
            </div>
          </div>
          {!hidePb && (
            <p className="mt-4 text-center text-[10px] text-white/20">
              Powered by Property Management Network
            </p>
          )}
        </div>
      </div>
    </div>
  )
}
