"use client";

import React, { useEffect, useState, useMemo } from "react";
import Link from "next/link";
import dynamic from "next/dynamic";
import ErpNavbar from "@/components/ErpNavbar";
import {
  Plus,
  Compass,
  Mail,
  MapPin,
  FileText,
  Users,
  CheckCircle2,
  Clock,
  ExternalLink,
  Layers,
  Sprout,
  Inbox,
  Sliders,
  ArrowUpRight,
} from "lucide-react";

const GeoTraceMap = dynamic(() => import("@/components/GeoTraceMap"), {
  ssr: false,
  loading: () => (
    <div className="h-[360px] w-full rounded-xl bg-slate-900 animate-pulse flex items-center justify-center text-honey-400 text-sm font-bold">
      Loading ERP Master GIS Map...
    </div>
  ),
});

interface SiteItem {
  id: string;
  name: string;
  clientId: string;
  county: string;
  subLocation: string;
  latitude: number;
  longitude: number;
  totalHives: number;
  colonisedHives: number;
  hiveType: string;
  bioFenceMetres: number;
  areaHectares: number;
  status: string;
}

interface ClientItem {
  id: string;
  name: string;
  contactPerson: string;
  email: string;
  phone: string;
  clientType: string;
  county: string;
  subLocation: string;
  notes?: string;
  sites: SiteItem[];
}

interface PhotoItem {
  id: string;
  imageUrl: string;
  caption: string;
  tagCategory: string;
  latitude: number;
  longitude: number;
  gpsSource: string;
  sequenceOrder: number;
  includeInTrace: boolean;
}

interface ActivityItem {
  id: string;
  reportCode: string;
  shareToken: string;
  clientId: string;
  siteId: string;
  technicianName: string;
  visitDate: string;
  activityType: string;
  traceMode: "POLYGON" | "POLYLINE";
  calculatedAreaHa: number;
  calculatedAreaSqm: number;
  calculatedDistanceM: number;
  hivesInspected: number;
  colonisedCount: number;
  status: string;
  emailedAt?: string | null;
  emailedTo?: string | null;
  client: ClientItem;
  site: SiteItem;
  photos: PhotoItem[];
}

interface QuoteLeadItem {
  id: string;
  quoteNumber: string;
  clientName: string;
  organization?: string;
  email: string;
  phone: string;
  location: string;
  hiveCount: number;
  discountPercent: number;
  estimatedMinKes: number;
  estimatedMaxKes: number;
  itemsJson: string;
  notes?: string;
  status: string;
  createdAt: string;
}

export default function ErpDashboardPage() {
  const [currentUser, setCurrentUser] = useState<{
    id: string;
    name: string;
    email: string;
    role: "ADMIN" | "TECHNICIAN";
  } | null>(null);
  const [clients, setClients] = useState<ClientItem[]>([]);
  const [sites, setSites] = useState<SiteItem[]>([]);
  const [activities, setActivities] = useState<ActivityItem[]>([]);
  const [quotes, setQuotes] = useState<QuoteLeadItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<"REPORTS" | "CLIENTS" | "QUOTES">("REPORTS");

  // Modal state for adding Client + Site
  const [showAddClient, setShowAddClient] = useState(false);
  const [newClient, setNewClient] = useState({
    name: "",
    contactPerson: "",
    email: "",
    phone: "",
    clientType: "Commercial Farm",
    county: "Machakos",
    subLocation: "",
    siteName: "",
    latitude: "-1.2658",
    longitude: "37.3189",
    totalHives: "20",
    colonisedHives: "18",
    bioFenceMetres: "0",
    areaHectares: "2.5",
  });
  const [savingClient, setSavingClient] = useState(false);

  const loadErpData = async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/erp/bootstrap");
      const data = await res.json();
      if (data.currentUser) setCurrentUser(data.currentUser);
      setClients(data.clients || []);
      setSites(data.sites || []);
      setActivities(data.activities || []);
      setQuotes(data.quotes || []);
    } catch (err) {
      console.error("Failed to load ERP data:", err);
    } finally {
      setLoading(false);
    }
  };

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

  const kpis = useMemo(() => {
    const totalHives = sites.reduce((acc, s) => acc + (s.totalHives || 0), 0);
    const colonisedHives = sites.reduce((acc, s) => acc + (s.colonisedHives || 0), 0);
    const totalBioFence = sites.reduce((acc, s) => acc + (s.bioFenceMetres || 0), 0);
    const totalAreaHa = sites.reduce((acc, s) => acc + (s.areaHectares || 0), 0);
    const reportsEmailed = activities.filter((a) => a.status === "SENT_TO_CLIENT").length;
    return {
      totalHives,
      colonisedHives,
      occupancyRate: totalHives > 0 ? Math.round((colonisedHives / totalHives) * 100) : 0,
      totalBioFence: Math.round(totalBioFence),
      totalAreaHa: totalAreaHa.toFixed(1),
      reportsEmailed,
    };
  }, [sites, activities]);

  const masterMapWaypoints = useMemo(() => {
    return sites.map((s, idx) => ({
      id: s.id,
      latitude: s.latitude,
      longitude: s.longitude,
      caption: `${s.name} (${s.subLocation}) — ${s.colonisedHives}/${s.totalHives} Hives Colonised`,
      tagCategory: `${s.areaHectares} Ha • ${s.bioFenceMetres}m Bio-Fence`,
      imageUrl: idx % 2 === 0 ? "/images/kamuthanga-apiary.png" : "/images/langstroth-hives.png",
      gpsSource: "ERP Site Master",
      sequenceOrder: idx + 1,
      includeInTrace: true,
    }));
  }, [sites]);

  const handleCreateClient = async (e: React.FormEvent) => {
    e.preventDefault();
    setSavingClient(true);
    try {
      const res = await fetch("/api/clients", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newClient),
      });
      if (res.ok) {
        setShowAddClient(false);
        setNewClient({
          name: "",
          contactPerson: "",
          email: "",
          phone: "",
          clientType: "Commercial Farm",
          county: "Machakos",
          subLocation: "",
          siteName: "",
          latitude: "-1.2658",
          longitude: "37.3189",
          totalHives: "20",
          colonisedHives: "18",
          bioFenceMetres: "0",
          areaHectares: "2.5",
        });
        await loadErpData();
      }
    } finally {
      setSavingClient(false);
    }
  };

  const handleQuoteStatusChange = async (id: string, status: string) => {
    await fetch("/api/quotes", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id, status }),
    });
    await loadErpData();
  };

  return (
    <div className="min-h-screen flex flex-col bg-slate-50">
      <ErpNavbar />

      <main className="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 py-8 space-y-8">
        {/* Top Action Header */}
        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 bg-white p-6 rounded-2xl border border-slate-200 shadow-sm">
          <div>
            <div className="text-xs font-extrabold uppercase tracking-wider text-amber-600">
              Davally Apiculture Limited • Operations & GIS Command Center
            </div>
            <h1 className="text-2xl sm:text-3xl font-black text-slate-900 mt-0.5">
              ERP, Geo-Field Data & Client Reporting
            </h1>
            <p className="text-xs sm:text-sm text-slate-600 mt-1">
              Track apiary sites, collect dropdown field data with geo-located photos, trace area
              boundaries, and email verified PDF/GIS reports directly to clients.
            </p>
          </div>
          <div className="flex flex-wrap items-center gap-3">
            {currentUser?.role === "ADMIN" && (
              <button
                type="button"
                onClick={() => setShowAddClient(true)}
                className="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-bold text-xs sm:text-sm transition"
              >
                <Plus className="w-4 h-4" />
                Add Client & Apiary Site
              </button>
            )}
            <Link
              href="/erp/field-new"
              className="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-honey-500 hover:bg-honey-400 text-hive-950 font-black text-xs sm:text-sm shadow-md shadow-honey-500/20 transition"
            >
              <Compass className="w-4 h-4" />
              + Log Field Activity & GPS Photos
            </Link>
          </div>
        </div>

        {/* KPI Metrics Grid */}
        <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
          <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm">
            <div className="flex items-center justify-between text-xs font-bold text-slate-500 uppercase">
              <span>Colonised Hives Active</span>
              <Layers className="w-4 h-4 text-amber-500" />
            </div>
            <div className="text-2xl font-black text-slate-900 mt-2">
              {kpis.colonisedHives} / {kpis.totalHives}{" "}
              <span className="text-sm font-bold text-emerald-600">({kpis.occupancyRate}%)</span>
            </div>
            <div className="text-xs text-slate-500 mt-1">
              Across {sites.length} active Machakos & regional sites
            </div>
          </div>

          <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm">
            <div className="flex items-center justify-between text-xs font-bold text-slate-500 uppercase">
              <span>Traced Pollinator & Bio-Fence</span>
              <Sprout className="w-4 h-4 text-emerald-600" />
            </div>
            <div className="text-2xl font-black text-slate-900 mt-2">
              {kpis.totalAreaHa} Ha{" "}
              <span className="text-sm font-bold text-amber-700">• {kpis.totalBioFence}m</span>
            </div>
            <div className="text-xs text-slate-500 mt-1">
              Calculated from GPS photo & corner traces
            </div>
          </div>

          <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm">
            <div className="flex items-center justify-between text-xs font-bold text-slate-500 uppercase">
              <span>Field Reports & Client Emails</span>
              <Mail className="w-4 h-4 text-blue-600" />
            </div>
            <div className="text-2xl font-black text-slate-900 mt-2">
              {activities.length} Reports{" "}
              <span className="text-sm font-bold text-blue-600">
                ({kpis.reportsEmailed} Emailed)
              </span>
            </div>
            <div className="text-xs text-slate-500 mt-1">
              With interactive GIS share links & PDF layout
            </div>
          </div>

          <div className="bg-white p-5 rounded-2xl border border-slate-200 shadow-sm">
            <div className="flex items-center justify-between text-xs font-bold text-slate-500 uppercase">
              <span>Clients & Quote Leads</span>
              <Users className="w-4 h-4 text-purple-600" />
            </div>
            <div className="text-2xl font-black text-slate-900 mt-2">
              {clients.length} Clients{" "}
              <span className="text-sm font-bold text-purple-600">• {quotes.length} Quotes</span>
            </div>
            <div className="text-xs text-slate-500 mt-1">
              Farms, conservancies, cooperatives & NGOs
            </div>
          </div>
        </div>

        {/* Master GIS Overview Map */}
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-5 space-y-4">
          <div className="flex flex-wrap items-center justify-between gap-2">
            <div>
              <h2 className="text-lg font-extrabold text-slate-900 flex items-center gap-2">
                <MapPin className="w-5 h-5 text-amber-500" />
                Master Apiary & Bio-Fencing GIS Map
              </h2>
              <p className="text-xs text-slate-500">
                Click any numbered pin to inspect site hive occupancy, traced hectares, and photo
                evidence.
              </p>
            </div>
            {currentUser?.role === "ADMIN" && (
              <Link
                href="/erp/settings"
                className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-600 hover:text-amber-600 bg-slate-100 px-3 py-1.5 rounded-lg"
              >
                <Sliders className="w-3.5 h-3.5" />
                Configure Dropdowns, Catalogue & Staff Roles
              </Link>
            )}
          </div>

          <GeoTraceMap
            waypoints={masterMapWaypoints}
            traceMode="POLYGON"
            editable={false}
            height="360px"
          />
        </div>

        {/* Main ERP Tabs */}
        <div className="bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
          <div className="border-b border-slate-200 bg-slate-50 px-4 pt-3 flex flex-wrap gap-2">
            <button
              type="button"
              onClick={() => setActiveTab("REPORTS")}
              className={`px-4 py-2.5 rounded-t-xl text-xs sm:text-sm font-extrabold flex items-center gap-2 border-b-2 transition ${
                activeTab === "REPORTS"
                  ? "bg-white text-slate-900 border-honey-500 shadow-sm"
                  : "text-slate-600 border-transparent hover:text-slate-900"
              }`}
            >
              <FileText className="w-4 h-4 text-amber-500" />
              Field Reports & Email Dispatch ({activities.length})
            </button>

            <button
              type="button"
              onClick={() => setActiveTab("CLIENTS")}
              className={`px-4 py-2.5 rounded-t-xl text-xs sm:text-sm font-extrabold flex items-center gap-2 border-b-2 transition ${
                activeTab === "CLIENTS"
                  ? "bg-white text-slate-900 border-honey-500 shadow-sm"
                  : "text-slate-600 border-transparent hover:text-slate-900"
              }`}
            >
              <Users className="w-4 h-4 text-emerald-600" />
              Clients & Apiary Sites ({clients.length})
            </button>

            {currentUser?.role === "ADMIN" && (
              <button
                type="button"
                onClick={() => setActiveTab("QUOTES")}
                className={`px-4 py-2.5 rounded-t-xl text-xs sm:text-sm font-extrabold flex items-center gap-2 border-b-2 transition ${
                  activeTab === "QUOTES"
                    ? "bg-white text-slate-900 border-honey-500 shadow-sm"
                    : "text-slate-600 border-transparent hover:text-slate-900"
                }`}
              >
                <Inbox className="w-4 h-4 text-purple-600" />
                Website Quote Requests ({quotes.length})
              </button>
            )}
          </div>

          <div className="p-6">
            {loading ? (
              <div className="py-12 text-center text-sm text-slate-500">
                Loading Davally ERP records...
              </div>
            ) : activeTab === "REPORTS" ? (
              <div className="space-y-4">
                {activities.map((act) => (
                  <div
                    key={act.id}
                    className="rounded-xl border border-slate-200 p-5 hover:border-amber-400 transition flex flex-col lg:flex-row lg:items-center justify-between gap-4 bg-white"
                  >
                    <div className="space-y-1.5">
                      <div className="flex flex-wrap items-center gap-2">
                        <span className="font-mono text-xs font-black px-2.5 py-0.5 rounded bg-hive-900 text-honey-400">
                          {act.reportCode}
                        </span>
                        <span
                          className={`text-[11px] font-bold px-2.5 py-0.5 rounded-full ${
                            act.status === "SENT_TO_CLIENT"
                              ? "bg-emerald-100 text-emerald-800"
                              : act.status === "APPROVED"
                              ? "bg-blue-100 text-blue-800"
                              : "bg-amber-100 text-amber-800"
                          }`}
                        >
                          {act.status === "SENT_TO_CLIENT"
                            ? `Emailed to ${act.emailedTo || act.client?.email}`
                            : act.status.replace("_", " ")}
                        </span>
                        <span className="text-xs text-slate-500 flex items-center gap-1">
                          <Clock className="w-3.5 h-3.5" />
                          {new Date(act.visitDate).toLocaleDateString("en-KE", {
                            dateStyle: "medium",
                          })}
                        </span>
                      </div>

                      <h3 className="text-base sm:text-lg font-extrabold text-slate-900">
                        {act.activityType} — {act.site?.name}
                      </h3>

                      <div className="text-xs text-slate-600 flex flex-wrap items-center gap-x-4 gap-y-1">
                        <span>
                          Client: <strong>{act.client?.name}</strong> ({act.client?.email})
                        </span>
                        <span>
                          Technician: <strong>{act.technicianName}</strong>
                        </span>
                        <span>
                          Hives: <strong>{act.colonisedCount}/{act.hivesInspected} Colonised</strong>
                        </span>
                        <span className="text-amber-700 font-bold">
                          GIS Trace:{" "}
                          {act.traceMode === "POLYGON" && act.calculatedAreaHa > 0
                            ? `${act.calculatedAreaHa} Hectares (${act.calculatedDistanceM}m perimeter)`
                            : `${act.calculatedDistanceM}m Linear Bio-Fence / Line`}
                        </span>
                        <span>
                          GPS Photos: <strong>{act.photos?.length || 0} pins</strong>
                        </span>
                      </div>
                    </div>

                    <div className="flex flex-wrap items-center gap-2.5 shrink-0">
                      <Link
                        href={`/reports/share/${act.shareToken}`}
                        className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg text-xs font-bold bg-slate-100 text-slate-700 hover:bg-slate-200 transition"
                      >
                        <ExternalLink className="w-3.5 h-3.5" />
                        Client Share View
                      </Link>
                      <Link
                        href={`/erp/reports/${act.id}`}
                        className="inline-flex items-center gap-1.5 px-4 py-2 rounded-lg text-xs font-extrabold bg-hive-900 text-honey-400 hover:bg-hive-800 transition shadow-sm"
                      >
                        <Mail className="w-3.5 h-3.5" />
                        Review, Trace & Email Client
                      </Link>
                    </div>
                  </div>
                ))}
              </div>
            ) : activeTab === "CLIENTS" ? (
              <div className="grid md:grid-cols-2 gap-4">
                {clients.map((client) => (
                  <div
                    key={client.id}
                    className="rounded-xl border border-slate-200 p-5 space-y-3 bg-slate-50/50"
                  >
                    <div className="flex items-start justify-between gap-2">
                      <div>
                        <span className="text-[10px] font-bold uppercase px-2 py-0.5 rounded bg-amber-100 text-amber-800">
                          {client.clientType}
                        </span>
                        <h3 className="text-base font-extrabold text-slate-900 mt-1">
                          {client.name}
                        </h3>
                        <div className="text-xs text-slate-600">
                          Contact: <strong>{client.contactPerson}</strong> • {client.phone} •{" "}
                          <span className="text-amber-700 font-medium">{client.email}</span>
                        </div>
                      </div>
                      <Link
                        href={`/erp/field-new?clientId=${client.id}`}
                        className="text-xs font-bold text-amber-700 hover:text-amber-900 flex items-center gap-1 bg-white px-2.5 py-1.5 rounded-lg border border-slate-200"
                      >
                        Log Visit <ArrowUpRight className="w-3.5 h-3.5" />
                      </Link>
                    </div>

                    {client.notes && (
                      <p className="text-xs text-slate-600 bg-white p-2.5 rounded-lg border border-slate-200">
                        {client.notes}
                      </p>
                    )}

                    <div className="space-y-2 pt-1">
                      <div className="text-[11px] font-bold uppercase text-slate-500">
                        Registered Apiary & Bio-Fence Sites ({client.sites?.length || 0})
                      </div>
                      {client.sites?.map((site) => (
                        <div
                          key={site.id}
                          className="bg-white p-3 rounded-lg border border-slate-200 flex items-center justify-between text-xs"
                        >
                          <div>
                            <div className="font-bold text-slate-900">{site.name}</div>
                            <div className="text-slate-500 font-mono text-[11px]">
                              {site.subLocation}, {site.county} • GPS: {site.latitude.toFixed(4)},{" "}
                              {site.longitude.toFixed(4)}
                            </div>
                          </div>
                          <div className="text-right">
                            <div className="font-extrabold text-emerald-700">
                              {site.colonisedHives}/{site.totalHives} Hives
                            </div>
                            <div className="text-[11px] text-slate-500">
                              {site.areaHectares} Ha • {site.bioFenceMetres}m Fence
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="space-y-4">
                {quotes.map((qt) => {
                  let items: Array<{ sku: string; name: string; qty: number; unit: string }> = [];
                  try {
                    items = JSON.parse(qt.itemsJson || "[]");
                  } catch {
                    items = [];
                  }
                  return (
                    <div
                      key={qt.id}
                      className="rounded-xl border border-slate-200 p-5 bg-white flex flex-col lg:flex-row lg:items-center justify-between gap-4"
                    >
                      <div className="space-y-1.5">
                        <div className="flex items-center gap-2">
                          <span className="font-mono text-xs font-bold px-2.5 py-0.5 rounded bg-purple-100 text-purple-900">
                            {qt.quoteNumber}
                          </span>
                          <span className="text-xs font-bold text-slate-900">
                            {qt.clientName} {qt.organization ? `(${qt.organization})` : ""}
                          </span>
                          <span className="text-xs text-slate-500">• {qt.location}</span>
                        </div>
                        <div className="text-xs text-slate-600">
                          Email: <strong>{qt.email}</strong> &nbsp;|&nbsp; Phone:{" "}
                          <strong>{qt.phone}</strong> &nbsp;|&nbsp; Hives:{" "}
                          <strong>
                            {qt.hiveCount} ({qt.discountPercent}% Volume Discount)
                          </strong>
                        </div>
                        <div className="flex flex-wrap gap-1.5 pt-1">
                          {items.map((it, idx) => (
                            <span
                              key={idx}
                              className="text-[11px] bg-slate-100 px-2.5 py-1 rounded-md text-slate-700 font-medium"
                            >
                              {it.sku}: {it.qty} {it.unit}
                            </span>
                          ))}
                        </div>
                        {qt.notes && (
                          <div className="text-xs text-slate-500 italic pt-1">
                            &ldquo;{qt.notes}&rdquo;
                          </div>
                        )}
                      </div>

                      <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3 shrink-0">
                        <div className="text-right">
                          <div className="text-[10px] font-bold uppercase text-slate-400">
                            Estimated Range
                          </div>
                          <div className="text-sm font-black text-slate-900">
                            KES {qt.estimatedMinKes.toLocaleString()} –{" "}
                            {qt.estimatedMaxKes.toLocaleString()}
                          </div>
                        </div>
                        <select
                          value={qt.status}
                          onChange={(e) => handleQuoteStatusChange(qt.id, e.target.value)}
                          className="rounded-lg border border-slate-300 px-3 py-2 text-xs font-bold bg-slate-50"
                        >
                          <option value="NEW">Status: NEW</option>
                          <option value="CONTACTED">Status: CONTACTED</option>
                          <option value="CONVERTED">Status: CONVERTED</option>
                        </select>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </main>

      {/* Modal to Add New Client & Site */}
      {showAddClient && (
        <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-xl w-full p-6 shadow-2xl space-y-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between border-b border-slate-200 pb-3">
              <h3 className="text-lg font-black text-slate-900">
                Register New Client & Apiary Site
              </h3>
              <button
                type="button"
                onClick={() => setShowAddClient(false)}
                className="text-xs font-bold text-slate-500 hover:text-slate-800"
              >
                ESC / Close
              </button>
            </div>

            <form onSubmit={handleCreateClient} className="space-y-3 text-xs">
              <div className="grid sm:grid-cols-2 gap-3">
                <div>
                  <label className="font-bold text-slate-700 block mb-1">
                    Client / Organization Name *
                  </label>
                  <input
                    type="text"
                    required
                    value={newClient.name}
                    onChange={(e) => setNewClient({ ...newClient, name: e.target.value })}
                    placeholder="e.g. Kangundo Valley Orchards"
                    className="w-full border border-slate-300 rounded-lg px-3 py-2"
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Client Type</label>
                  <select
                    value={newClient.clientType}
                    onChange={(e) => setNewClient({ ...newClient, clientType: e.target.value })}
                    className="w-full border border-slate-300 rounded-lg px-3 py-2"
                  >
                    <option>Commercial Farm</option>
                    <option>Conservancy</option>
                    <option>Cooperative / Institution</option>
                    <option>NGO / Government</option>
                    <option>Individual Apiarist</option>
                  </select>
                </div>
              </div>

              <div className="grid sm:grid-cols-3 gap-3">
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Contact Person *</label>
                  <input
                    type="text"
                    required
                    value={newClient.contactPerson}
                    onChange={(e) =>
                      setNewClient({ ...newClient, contactPerson: e.target.value })
                    }
                    placeholder="Full Name"
                    className="w-full border border-slate-300 rounded-lg px-3 py-2"
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-700 block mb-1">
                    Client Email (for Reports) *
                  </label>
                  <input
                    type="email"
                    required
                    value={newClient.email}
                    onChange={(e) => setNewClient({ ...newClient, email: e.target.value })}
                    placeholder="client@domain.co.ke"
                    className="w-full border border-slate-300 rounded-lg px-3 py-2"
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-700 block mb-1">Phone Number *</label>
                  <input
                    type="text"
                    required
                    value={newClient.phone}
                    onChange={(e) => setNewClient({ ...newClient, phone: e.target.value })}
                    placeholder="07XX XXX XXX"
                    className="w-full border border-slate-300 rounded-lg px-3 py-2"
                  />
                </div>
              </div>

              <div className="border-t border-slate-200 pt-3">
                <div className="font-extrabold text-amber-700 uppercase text-[11px] mb-2">
                  Initial Apiary / Bio-Fence Site Details
                </div>
                <div className="grid sm:grid-cols-2 gap-3">
                  <div>
                    <label className="font-bold text-slate-700 block mb-1">Site Name *</label>
                    <input
                      type="text"
                      required
                      value={newClient.siteName}
                      onChange={(e) => setNewClient({ ...newClient, siteName: e.target.value })}
                      placeholder="e.g. Kangundo North Block B"
                      className="w-full border border-slate-300 rounded-lg px-3 py-2"
                    />
                  </div>
                  <div>
                    <label className="font-bold text-slate-700 block mb-1">
                      Town / Sub-Location *
                    </label>
                    <input
                      type="text"
                      required
                      value={newClient.subLocation}
                      onChange={(e) =>
                        setNewClient({ ...newClient, subLocation: e.target.value })
                      }
                      placeholder="e.g. Matetani, Kangundo"
                      className="w-full border border-slate-300 rounded-lg px-3 py-2"
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mt-3">
                  <div>
                    <label className="font-bold text-slate-700 block mb-1">Latitude</label>
                    <input
                      type="number"
                      step="any"
                      value={newClient.latitude}
                      onChange={(e) => setNewClient({ ...newClient, latitude: e.target.value })}
                      className="w-full border border-slate-300 rounded-lg px-3 py-2 font-mono"
                    />
                  </div>
                  <div>
                    <label className="font-bold text-slate-700 block mb-1">Longitude</label>
                    <input
                      type="number"
                      step="any"
                      value={newClient.longitude}
                      onChange={(e) => setNewClient({ ...newClient, longitude: e.target.value })}
                      className="w-full border border-slate-300 rounded-lg px-3 py-2 font-mono"
                    />
                  </div>
                  <div>
                    <label className="font-bold text-slate-700 block mb-1">Total Hives</label>
                    <input
                      type="number"
                      value={newClient.totalHives}
                      onChange={(e) => setNewClient({ ...newClient, totalHives: e.target.value })}
                      className="w-full border border-slate-300 rounded-lg px-3 py-2"
                    />
                  </div>
                  <div>
                    <label className="font-bold text-slate-700 block mb-1">Colonised</label>
                    <input
                      type="number"
                      value={newClient.colonisedHives}
                      onChange={(e) =>
                        setNewClient({ ...newClient, colonisedHives: e.target.value })
                      }
                      className="w-full border border-slate-300 rounded-lg px-3 py-2"
                    />
                  </div>
                </div>
              </div>

              <div className="flex justify-end gap-2 pt-4">
                <button
                  type="button"
                  onClick={() => setShowAddClient(false)}
                  className="px-4 py-2 rounded-lg border border-slate-300 font-bold text-slate-600"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={savingClient}
                  className="px-5 py-2 rounded-lg bg-hive-900 text-honey-400 font-extrabold"
                >
                  {savingClient ? "Saving..." : "Save Client & Site"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
