import React, { useState, useEffect } from "react";
import { Property, Agent } from "../types";
import { formatIDR } from "../utils";
import { Database, Plus, Trash2, Edit3, MessageSquare, ClipboardList, CheckCircle, RefreshCcw, Landmark, Shield } from "lucide-react";

interface Inquiry {
  id: number;
  name: string;
  email: string;
  phone: string;
  interest: string;
  agent: string;
  message: string;
  transactionId: string;
  created_at: string;
}

export default function AdminPanel({ lang = "en" }: { lang: "en" | "id" }) {
  const isEn = lang === "en";
  const [properties, setProperties] = useState<Property[]>([]);
  const [agents, setAgents] = useState<Agent[]>([]);
  const [inquiries, setInquiries] = useState<Inquiry[]>([]);
  const [dbStatus, setDbStatus] = useState({ status: "Connecting", database: "Reading...", host: "" });
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"catalog" | "inquiries" | "add-asset">("catalog");

  // Form State
  const [formData, setFormData] = useState({
    id: "",
    title: "",
    slug: "luxury-residence",
    category: "villas",
    location: "Uluwatu, Bali",
    city: "Bali",
    price: "",
    beds: "4",
    baths: "4.5",
    area: "4200",
    lotSize: "1.2 Acres",
    yearBuilt: "2024",
    heroImage: "",
    narrativeTitle: "Architectural Symmetry",
    narrativeDescription: "Designed with clean structural modules, integrating local stone alignments with unclouded natural skylights.",
    specifications: "Preconditioned solid timber doors, Private saltwater lap pool, Italian Calacatta marble elements",
    lat: "-8.845",
    lng: "115.125",
    agentId: "agent-clara"
  });

  const [editingId, setEditingId] = useState<string | null>(null);
  const [statusMessage, setStatusMessage] = useState<{ text: string; isError: boolean } | null>(null);

  const getAdminToken = () => {
    try {
      const session = localStorage.getItem("luniar_admin_session");
      if (session) {
        const parsed = JSON.parse(session);
        return parsed?.token || "";
      }
    } catch (e) {
      console.warn(e);
    }
    return "";
  };

  const fetchAllData = async () => {
    setLoading(true);
    try {
      const token = getAdminToken();
      const authHeaders = token ? { "Authorization": `Bearer ${token}` } : {};

      // 1. Fetch properties
      const propsRes = await fetch("/api/properties");
      if (propsRes.ok) {
        const propsData = await propsRes.json();
        setProperties(propsData);
      }

      // 2. Fetch agents
      const agentsRes = await fetch("/api/agents");
      if (agentsRes.ok) {
        const agentsData = await agentsRes.json();
        setAgents(agentsData);
      }

      // 3. Fetch inquiries
      const inqsRes = await fetch("/api/inquiries", {
        headers: authHeaders
      });
      if (inqsRes.ok) {
        const inqsData = await inqsRes.json();
        setInquiries(inqsData);
      }

      // 4. Fetch DB Status
      const statusRes = await fetch("/api/db-status");
      if (statusRes.ok) {
        const statusData = await statusRes.json();
        setDbStatus(statusData);
      }
    } catch (err) {
      console.error("Failed fetching admin layout data:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchAllData();
  }, []);

  const triggerNotification = (text: string, isError: boolean = false) => {
    setStatusMessage({ text, isError });
    setTimeout(() => {
      setStatusMessage(null);
    }, 4500);
  };

  const resetForm = () => {
    setFormData({
      id: "",
      title: "",
      slug: "luxury-residence",
      category: "villas",
      location: "Uluwatu, Bali",
      city: "Bali",
      price: "",
      beds: "4",
      baths: "4.5",
      area: "4200",
      lotSize: "1.2 Acres",
      yearBuilt: "2024",
      heroImage: "https://images.unsplash.com/photo-1600585154340-be6161a56a0c?auto=format&fit=crop&q=80&w=1200",
      narrativeTitle: "Architectural Symmetry",
      narrativeDescription: "Designed with clean structural modules, integrating local stone alignments with unclouded natural skylights.",
      specifications: "Preconditioned solid timber doors, Private saltwater lap pool, Italian Calacatta marble elements",
      lat: "-8.845",
      lng: "115.125",
      agentId: "agent-clara"
    });
    setEditingId(null);
  };

  const handleEditClick = (p: Property) => {
    setFormData({
      id: p.id,
      title: p.title,
      slug: p.slug,
      category: p.category,
      location: p.location,
      city: p.city,
      price: String(p.price),
      beds: String(p.beds),
      baths: String(p.baths),
      area: String(p.area),
      lotSize: p.lotSize || "N/A",
      yearBuilt: String(p.yearBuilt),
      heroImage: p.heroImage,
      narrativeTitle: p.narrativeTitle,
      narrativeDescription: p.narrativeDescription,
      specifications: p.specifications.join(", "),
      lat: String(p.coordinates?.lat || -8.845),
      lng: String(p.coordinates?.lng || 115.125),
      agentId: p.agentId
    });
    setEditingId(p.id);
    setActiveTab("add-asset");
  };

  const handleDeleteProperty = async (id: string) => {
    if (!window.confirm("Are you absolutely sure you want to decommission and remove this asset from Luniar archives?")) return;
    try {
      const token = getAdminToken();
      const res = await fetch(`/api/properties/${id}`, { 
        method: "DELETE",
        headers: {
          "Authorization": token ? `Bearer ${token}` : ""
        }
      });
      if (res.ok) {
        triggerNotification(`Property ${id} decommissioned successfully.`);
        setProperties(properties.filter((p) => p.id !== id));
      } else {
        const err = await res.json();
        triggerNotification(err.error || "Decommission file failed.", true);
      }
    } catch (e: any) {
      triggerNotification(e.message, true);
    }
  };

  const handleResolveInquiry = async (id: number) => {
    try {
      const token = getAdminToken();
      const res = await fetch(`/api/inquiries/${id}`, { 
        method: "DELETE",
        headers: {
          "Authorization": token ? `Bearer ${token}` : ""
        }
      });
      if (res.ok) {
        triggerNotification(`Inquiry ledger #${id} has been marked secured and cleared.`);
        setInquiries(inquiries.filter((inq) => inq.id !== id));
      } else {
        const err = await res.json();
        triggerNotification(err.error || "Could not settle inquiry record.", true);
      }
    } catch (e: any) {
      triggerNotification(e.message, true);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.title || !formData.price || !formData.heroImage) {
      triggerNotification("Please fill out core fields including image URL and price.", true);
      return;
    }

    const payload = {
      ...formData,
      price: Number(formData.price),
      beds: Number(formData.beds),
      baths: Number(formData.baths),
      area: Number(formData.area),
      yearBuilt: Number(formData.yearBuilt),
      images: [formData.heroImage],
      specifications: formData.specifications.split(",").map((s) => s.trim()).filter(Boolean),
      coordinates: { lat: Number(formData.lat), lng: Number(formData.lng) }
    };

    try {
      const token = getAdminToken();
      const headersFull = {
        "Content-Type": "application/json",
        "Authorization": token ? `Bearer ${token}` : ""
      };

      if (editingId) {
        // PUT edit
        const res = await fetch(`/api/properties/${editingId}`, {
          method: "PUT",
          headers: headersFull,
          body: JSON.stringify(payload)
        });
        if (res.ok) {
          triggerNotification("Property specs updated successfully.");
          resetForm();
          fetchAllData();
          setActiveTab("catalog");
        } else {
          const err = await res.json();
          triggerNotification(err.error || "Failed applying parameter updates.", true);
        }
      } else {
        // POST add
        const res = await fetch("/api/properties", {
          method: "POST",
          headers: headersFull,
          body: JSON.stringify(payload)
        });
        if (res.ok) {
          triggerNotification("New asset logged and allocated inside general ledger.");
          resetForm();
          fetchAllData();
          setActiveTab("catalog");
        } else {
          const err = await res.json();
          triggerNotification(err.error || "Failed logging spatial asset.", true);
        }
      }
    } catch (e: any) {
      triggerNotification(e.message, true);
    }
  };

  return (
    <div className="bg-[#FDFCFB] min-h-[700px] py-10" id="admin-panel-main">
      {/* Upper Status Bar */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center border border-[#EEECE6] p-6 mb-10 bg-[#F5F3EF]/30" id="admin-status-tracker">
        <div className="space-y-1">
          <span className="font-sans text-[9px] font-bold uppercase tracking-[0.25em] text-[#C5A572] block">
            SOVEREIGN SERVER SYSTEMS
          </span>
          <h2 className="font-serif text-2xl font-light tracking-tight text-[#1A1A1A]">Admin Control Desk</h2>
        </div>

        {/* Database Diagnostic stats */}
        <div className="mt-4 md:mt-0 flex flex-wrap items-center gap-6">
          <div className="flex items-center space-x-3 text-xs">
            <div className={`w-2.5 h-2.5 rounded-full ${dbStatus.host !== "Localhost" ? "bg-emerald-500" : "bg-amber-500"} animate-pulse`} />
            <div>
              <span className="font-sans text-[8px] uppercase tracking-wider text-zinc-400 block font-bold">Storage Core Engine</span>
              <span className="font-mono text-[#1A1A1A] font-medium">{dbStatus.database}</span>
            </div>
          </div>
          <button
            onClick={fetchAllData}
            className="flex items-center gap-1.5 px-3 py-1.5 border border-[#EEECE6] hover:border-black text-[10px] font-sans font-bold uppercase tracking-widest transition-colors cursor-pointer focus:outline-none"
          >
            <RefreshCcw size={10} /> Sync System
          </button>
        </div>
      </div>

      {statusMessage && (
        <div className={`p-4 border text-xs font-sans tracking-wide mb-8 rounded-none transition-all ${
          statusMessage.isError 
            ? "bg-red-50/80 border-red-200 text-red-700" 
            : "bg-emerald-50/80 border-emerald-200 text-emerald-800"
        }`}>
          {statusMessage.text}
        </div>
      )}

      {/* Tabs Layout Button Rails */}
      <div className="flex border-b border-[#EEECE6] mb-10 gap-8" id="admin-tabs-nav">
        <button
          onClick={() => setActiveTab("catalog")}
          className={`pb-4 text-[10px] font-sans font-bold uppercase tracking-[0.25em] relative transition-all cursor-pointer focus:outline-none ${
            activeTab === "catalog" ? "text-black font-extrabold" : "text-zinc-400 hover:text-black"
          }`}
        >
          <span className="flex items-center gap-2">
            <ClipboardList size={13} /> Active Catalog ({properties.length})
          </span>
          {activeTab === "catalog" && <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#C5A572]" />}
        </button>

        <button
          onClick={() => setActiveTab("inquiries")}
          className={`pb-4 text-[10px] font-sans font-bold uppercase tracking-[0.25em] relative transition-all cursor-pointer focus:outline-none ${
            activeTab === "inquiries" ? "text-black font-extrabold" : "text-zinc-400 hover:text-black"
          }`}
        >
          <span className="flex items-center gap-2">
            <MessageSquare size={13} /> Client Inquiry Ledger ({inquiries.length})
          </span>
          {activeTab === "inquiries" && <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#C5A572]" />}
        </button>

        <button
          onClick={() => {
            resetForm();
            setActiveTab("add-asset");
          }}
          className={`pb-4 text-[10px] font-sans font-bold uppercase tracking-[0.25em] relative transition-all cursor-pointer focus:outline-none ${
            activeTab === "add-asset" ? "text-black font-extrabold" : "text-zinc-400 hover:text-black"
          }`}
        >
          <span className="flex items-center gap-1.5">
            <Plus size={13} /> {editingId ? "Edit Spatial Core Specs" : "Add Structural Asset"}
          </span>
          {activeTab === "add-asset" && <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#C5A572]" />}
        </button>
      </div>

      {loading ? (
        <div className="py-24 text-center text-zinc-400 text-xs font-sans tracking-[0.2em] uppercase animate-pulse">
          Exotic registry catalogs loading from secure database...
        </div>
      ) : (
        <div className="text-left" id="admin-workspace-grid">
          
          {/* TAB 1: Catalog List */}
          {activeTab === "catalog" && (
            <div className="space-y-6">
              {properties.length === 0 ? (
                <div className="py-16 text-center border border-dashed border-[#EEECE6] bg-[#F5F3EF]/30 text-zinc-400 font-serif italic text-sm">
                  Active registry contains zero spatial files. Press 'Add Structural Asset' to allocate model structures.
                </div>
              ) : (
                <div className="overflow-x-auto border border-[#EEECE6]">
                  <table className="w-full text-left border-collapse font-sans text-xs">
                    <thead>
                      <tr className="bg-[#F5F3EF]/70 text-[#1A1A1A] font-bold uppercase tracking-wider border-b border-[#EEECE6] text-[9px]">
                        <th className="p-4 pl-6">Model Asset</th>
                        <th className="p-4">Geographics</th>
                        <th className="p-4">Structural Layout Specs</th>
                        <th className="p-4">Capital Price Point</th>
                        <th className="p-4 pr-6 text-right">Actions</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-[#EEECE6]">
                      {properties.map((p) => (
                        <tr key={p.id} className="hover:bg-[#FDFCFB] transition-colors" id={`admin-row-${p.id}`}>
                          <td className="p-4 pl-6 max-w-sm">
                            <div className="flex items-center gap-4">
                              <img src={p.heroImage} alt={p.title} className="w-11 h-11 object-cover border border-zinc-200 rounded-none bg-zinc-100" />
                              <div className="space-y-0.5">
                                <span className="font-mono text-[8px] uppercase tracking-widest text-[#C5A572] font-semibold">{p.category}</span>
                                <h4 className="font-serif text-sm font-normal text-[#1A1A1A]">{p.title}</h4>
                              </div>
                            </div>
                          </td>
                          <td className="p-4">
                            <span className="text-[#1A1A1A] block">{p.location}</span>
                            <span className="text-zinc-400 font-light text-[10px]">{p.city}</span>
                          </td>
                          <td className="p-4 font-light text-zinc-600">
                            {p.beds} Beds • {p.baths} Baths • {p.area.toLocaleString()} SQFT
                          </td>
                          <td className="p-4 font-mono font-bold text-[#C5A572] text-[13px]">
                            {formatIDR(p.price)}
                          </td>
                          <td className="p-4 pr-6 text-right">
                            <div className="flex items-center justify-end gap-3">
                              <button
                                onClick={() => handleEditClick(p)}
                                className="p-2 border border-zinc-200 hover:border-black text-[#1A1A1A] hover:bg-black hover:text-white transition-all cursor-pointer focus:outline-none"
                                title="Edit specs"
                              >
                                <Edit3 size={11} />
                              </button>
                              <button
                                onClick={() => handleDeleteProperty(p.id)}
                                className="p-2 border border-red-200 text-red-600 hover:bg-red-600 hover:text-white hover:border-red-600 transition-all cursor-pointer focus:outline-none"
                                title="Decommission asset"
                              >
                                <Trash2 size={11} />
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          )}

          {/* TAB 2: Inquiries Ledger */}
          {activeTab === "inquiries" && (
            <div className="space-y-6">
              {inquiries.length === 0 ? (
                <div className="py-20 text-center border border-dashed border-[#EEECE6] bg-[#F5F3EF]/30 text-zinc-400 font-serif italic text-sm">
                  The active inquiry queue is completely clean and completed. No pending files.
                </div>
              ) : (
                <div className="grid grid-cols-1 gap-6">
                  {inquiries.map((inq) => (
                    <div key={inq.id} className="border border-[#EEECE6] p-6 space-y-4 bg-[#F5F3EF]/10" id={`inquiry-box-${inq.id}`}>
                      {/* Header block info */}
                      <div className="flex flex-col md:flex-row justify-between items-start md:items-center border-b border-[#EEECE6]/60 pb-3 gap-2">
                        <div>
                          <span className="font-mono text-[9px] bg-zinc-800 text-zinc-200 px-2 py-0.5 font-bold uppercase tracking-widest">{inq.transactionId}</span>
                          <span className="font-sans text-[10px] text-zinc-400 ml-3">{new Date(inq.created_at).toLocaleString()}</span>
                        </div>
                        <button
                          onClick={() => handleResolveInquiry(inq.id)}
                          className="flex items-center gap-1.5 px-3 py-1 bg-zinc-900 text-white hover:bg-[#C5A572] font-sans text-[9px] font-bold uppercase tracking-widest transition-colors cursor-pointer focus:outline-none"
                        >
                          <CheckCircle size={10} /> Clear & File Inquiry
                        </button>
                      </div>

                      {/* Client profile */}
                      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
                        <div>
                          <span className="text-zinc-400 block tracking-widest text-[8px] uppercase font-semibold">Prospective Collector</span>
                          <strong className="text-sm font-normal text-zinc-900 mt-1 block">{inq.name}</strong>
                          <span className="text-zinc-500 block leading-relaxed mt-0.5">{inq.email}</span>
                          <span className="text-zinc-500 block leading-none mt-1 font-mono">{inq.phone}</span>
                        </div>
                        <div>
                          <span className="text-zinc-400 block tracking-widest text-[8px] uppercase font-semibold">Acquisition Target</span>
                          <div className="text-zinc-900 font-serif mt-1 italic text-sm">{inq.interest}</div>
                        </div>
                        <div>
                          <span className="text-zinc-400 block tracking-widest text-[8px] uppercase font-semibold">Allocated Curation Officer</span>
                          <div className="text-zinc-800 font-sans mt-1 tracking-wide text-xs">{inq.agent}</div>
                        </div>
                      </div>

                      {/* Request message text */}
                      <div className="p-4 bg-[#F5F3EF]/60 border border-[#EEECE6]/40 text-xs text-zinc-700 leading-relaxed font-light italic">
                        "{inq.message}"
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* TAB 3: Add / Edit Property form */}
          {activeTab === "add-asset" && (
            <form onSubmit={handleSubmit} className="border border-[#EEECE6] p-6 md:p-10 space-y-8 max-w-4xl bg-white" id="admin-asset-form">
              <div className="border-b border-[#EEECE6] pb-4">
                <h3 className="font-serif text-lg font-normal text-[#1A1A1A]">
                  {editingId ? "Revamp Model Specifications" : "Allocate New Structural Asset"}
                </h3>
                <p className="text-xs text-zinc-400 font-light mt-1">
                  Drafting and appending precision structural properties straight into active repositories.
                </p>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6 text-xs text-left">
                {/* ID parameter (or auto generate) */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Archive Reference ID</label>
                  <input
                    type="text"
                    placeholder="e.g. prop-cliff-studio"
                    disabled={!!editingId}
                    value={formData.id}
                    onChange={(e) => setFormData({ ...formData, id: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono disabled:opacity-50"
                  />
                  {!editingId && <span className="text-[8px] text-zinc-400 block font-light">Leave blank to automatically construct an ID template.</span>}
                </div>

                {/* Title */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Bespoke Title</label>
                  <input
                    type="text"
                    placeholder="e.g. Modern Sandstone Pavilion"
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans font-medium"
                    required
                  />
                </div>

                {/* Region Category */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Structural Format Category</label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  >
                    <option value="villas">Villas</option>
                    <option value="apartments">Apartments</option>
                    <option value="houses">Houses</option>
                    <option value="commercial">Commercial Assets</option>
                  </select>
                </div>

                {/* City Anchor */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Metropolitan City Anchor</label>
                  <select
                    value={formData.city}
                    onChange={(e) => setFormData({ ...formData, city: e.target.value as any })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  >
                    <option value="Bali">Bali</option>
                    <option value="Jakarta">Jakarta</option>
                    <option value="Surabaya">Surabaya</option>
                    <option value="Bandung">Bandung</option>
                  </select>
                </div>

                {/* Location precise */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Geographic Location Anchor</label>
                  <input
                    type="text"
                    placeholder="e.g. Uluwatu Cliffside, Bali"
                    value={formData.location}
                    onChange={(e) => setFormData({ ...formData, location: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  />
                </div>

                {/* Capital Outlay Price */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Capital Cost Price Outlay (IDR)</label>
                  <input
                    type="number"
                    placeholder="e.g. 12000000000"
                    value={formData.price}
                    onChange={(e) => setFormData({ ...formData, price: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono"
                    required
                  />
                </div>

                {/* Room configurations info (bed, bath, area, yearBuilt) */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Chambres (Beds)</label>
                  <input
                    type="number"
                    value={formData.beds}
                    onChange={(e) => setFormData({ ...formData, beds: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Bathrooms</label>
                  <input
                    type="text"
                    value={formData.baths}
                    onChange={(e) => setFormData({ ...formData, baths: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Area Space (SQPT)</label>
                  <input
                    type="number"
                    value={formData.area}
                    onChange={(e) => setFormData({ ...formData, area: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Year Conceived Built</label>
                  <input
                    type="number"
                    value={formData.yearBuilt}
                    onChange={(e) => setFormData({ ...formData, yearBuilt: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono"
                  />
                </div>

                {/* Map coordinates specs */}
                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Spatial Latitude</label>
                  <input
                    type="text"
                    value={formData.lat}
                    onChange={(e) => setFormData({ ...formData, lat: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono"
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Spatial Longitude</label>
                  <input
                    type="text"
                    value={formData.lng}
                    onChange={(e) => setFormData({ ...formData, lng: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono"
                  />
                </div>

                {/* Assigned Architect curator */}
                <div className="space-y-1.5 md:col-span-2">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Assigned Curation Agent</label>
                  <select
                    value={formData.agentId}
                    onChange={(e) => setFormData({ ...formData, agentId: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  >
                    {agents.map((ag) => (
                      <option key={ag.id} value={ag.id}>{ag.name} ({ag.role})</option>
                    ))}
                  </select>
                </div>

                {/* Imagery asset URLs */}
                <div className="space-y-1.5 md:col-span-2">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Premium Hero Image (URL link)</label>
                  <input
                    type="text"
                    placeholder="https://images.unsplash.com/..."
                    value={formData.heroImage}
                    onChange={(e) => setFormData({ ...formData, heroImage: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-mono"
                    required
                  />
                </div>

                {/* Editorial text specifications */}
                <div className="space-y-1.5 md:col-span-2">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Architectural Narrative Heading</label>
                  <input
                    type="text"
                    placeholder="e.g. Dialogue of Form and Timber"
                    value={formData.narrativeTitle}
                    onChange={(e) => setFormData({ ...formData, narrativeTitle: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans font-medium"
                  />
                </div>

                <div className="space-y-1.5 md:col-span-2">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Architectural Narrative Description</label>
                  <textarea
                    rows={4}
                    placeholder="Detailed design concepts explaining vertical alignments and spatial balance..."
                    value={formData.narrativeDescription}
                    onChange={(e) => setFormData({ ...formData, narrativeDescription: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans resize-y leading-relaxed font-light"
                  />
                </div>

                <div className="space-y-1.5 md:col-span-2">
                  <label className="font-sans text-[9px] font-bold uppercase tracking-wider text-zinc-400 font-extrabold block">Bespoke Specifications (Comma Separated list)</label>
                  <input
                    type="text"
                    placeholder="Saltwater pool, Calacatta marble, VRV air system"
                    value={formData.specifications}
                    onChange={(e) => setFormData({ ...formData, specifications: e.target.value })}
                    className="w-full px-3 py-2.5 bg-[#F5F3EF]/40 border border-[#EEECE6] focus:border-black outline-none font-sans"
                  />
                  <span className="text-[8px] text-zinc-400 block font-light">Divide individual lines cleanly with simple punctuation commas.</span>
                </div>
              </div>

              {/* Form buttons row submission actions */}
              <div className="flex justify-end gap-4 border-t border-[#EEECE6] pt-6" id="form-buttons-row">
                <button
                  type="button"
                  onClick={resetForm}
                  className="px-6 py-3 border border-zinc-200 hover:border-black font-sans text-[10px] font-semibold uppercase tracking-[0.2em] transition-colors cursor-pointer focus:outline-none"
                >
                  Clear Fields
                </button>
                <button
                  type="submit"
                  className="px-8 py-3 bg-[#1A1A1A] hover:bg-[#C5A572] text-[#FDFCFB] font-sans text-[10px] font-bold uppercase tracking-[0.2em] transition-colors cursor-pointer focus:outline-none"
                >
                  {editingId ? "Apply Updated Specs" : "Insert Spatial Log"}
                </button>
              </div>
            </form>
          )}

        </div>
      )}
    </div>
  );
}
