"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";
import exifr from "exifr";
import ErpNavbar from "@/components/ErpNavbar";
import { computeGeoTrace } from "@/lib/geo";
import {
  Camera,
  MapPin,
  Navigation,
  Trash2,
  CheckCircle2,
  Sparkles,
  Layers,
  Send,
  Save,
  RotateCcw,
  FileCheck2,
  Plus,
} from "lucide-react";

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

interface DropdownCategoryItem {
  id: string;
  key: string;
  label: string;
  groupName: string;
  description?: string;
  optionsJson: string;
}

interface SiteOption {
  id: string;
  name: string;
  clientId: string;
  subLocation: string;
  county: string;
  latitude: number;
  longitude: number;
  totalHives: number;
  colonisedHives: number;
}

interface ClientOption {
  id: string;
  name: string;
  contactPerson: string;
  email: string;
  subLocation: string;
  sites: SiteOption[];
}

interface FieldPhotoPin {
  tempId: string;
  imageUrl: string;
  caption: string;
  tagCategory: string;
  latitude: number;
  longitude: number;
  altitude?: number | null;
  accuracy?: number | null;
  gpsSource: "EXIF_METADATA" | "LIVE_DEVICE_GPS" | "MAP_PIN";
  capturedAt: string;
  sequenceOrder: number;
  includeInTrace: boolean;
}

const DRAFT_STORAGE_KEY = "davally_field_activity_draft_v1";

export default function FieldDataCollectorPage() {
  const router = useRouter();

  const [currentUser, setCurrentUser] = useState<{
    id: string;
    name: string;
    email: string;
    role: "ADMIN" | "TECHNICIAN";
  } | null>(null);
  const [clients, setClients] = useState<ClientOption[]>([]);
  const [dropdownCategories, setDropdownCategories] = useState<DropdownCategoryItem[]>([]);
  const [loadingInit, setLoadingInit] = useState(true);

  // Selected Client & Site
  const [selectedClientId, setSelectedClientId] = useState("");
  const [selectedSiteId, setSelectedSiteId] = useState("");
  const [technicianName, setTechnicianName] = useState("Mr. David Mwangangi Kyalo");
  const [visitDate, setVisitDate] = useState(() =>
    new Date().toISOString().slice(0, 16)
  );
  const [hivesInspected, setHivesInspected] = useState<number>(20);
  const [colonisedCount, setColonisedCount] = useState<number>(18);

  // Dynamic Dropdown Values
  const [dropdownValues, setDropdownValues] = useState<Record<string, string>>({});

  // Geo-Located Photos & Waypoints + Trace Mode
  const [traceMode, setTraceMode] = useState<"POLYGON" | "POLYLINE">("POLYGON");
  const [photos, setPhotos] = useState<FieldPhotoPin[]>([]);
  const [gpsStatusMsg, setGpsStatusMsg] = useState<string>("");

  // Notes & Submission
  const [summaryNotes, setSummaryNotes] = useState("");
  const [recommendations, setRecommendations] = useState("");
  const [sendEmailImmediately, setSendEmailImmediately] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [draftSavedAt, setDraftSavedAt] = useState<string | null>(null);

  // Load Clients, Sites & Dynamic Dropdowns
  useEffect(() => {
    async function init() {
      setLoadingInit(true);
      try {
        const res = await fetch("/api/erp/bootstrap");
        const data = await res.json();
        if (data.currentUser) {
          setCurrentUser(data.currentUser);
          setTechnicianName(data.currentUser.name);
        }
        const loadedClients: ClientOption[] = data.clients || [];
        const loadedDropdowns: DropdownCategoryItem[] = data.dropdowns || [];

        setClients(loadedClients);
        setDropdownCategories(loadedDropdowns);

        // Initialize default dropdown choices
        const initialDropdowns: Record<string, string> = {};
        for (const cat of loadedDropdowns) {
          try {
            const opts = JSON.parse(cat.optionsJson || "[]");
            if (opts.length > 0) {
              initialDropdowns[cat.key] = opts[0];
            }
          } catch {
            // ignore
          }
        }

        // Check if there is a saved offline draft
        const savedDraftRaw = localStorage.getItem(DRAFT_STORAGE_KEY);
        if (savedDraftRaw) {
          try {
            const saved = JSON.parse(savedDraftRaw);
            if (saved.selectedClientId) setSelectedClientId(saved.selectedClientId);
            if (saved.selectedSiteId) setSelectedSiteId(saved.selectedSiteId);
            if (saved.dropdownValues) {
              setDropdownValues({ ...initialDropdowns, ...saved.dropdownValues });
            } else {
              setDropdownValues(initialDropdowns);
            }
            if (Array.isArray(saved.photos) && saved.photos.length > 0) {
              setPhotos(saved.photos);
            }
            if (saved.summaryNotes) setSummaryNotes(saved.summaryNotes);
            if (saved.recommendations) setRecommendations(saved.recommendations);
            if (saved.traceMode) setTraceMode(saved.traceMode);
            setDraftSavedAt("Restored from local device cache");
            setLoadingInit(false);
            return;
          } catch {
            // ignore invalid draft
          }
        }

        setDropdownValues(initialDropdowns);

        if (loadedClients.length > 0) {
          setSelectedClientId(loadedClients[0].id);
          if (loadedClients[0].sites?.length > 0) {
            const firstSite = loadedClients[0].sites[0];
            setSelectedSiteId(firstSite.id);
            setHivesInspected(firstSite.totalHives || 20);
            setColonisedCount(firstSite.colonisedHives || 18);
          }
        }
      } catch (err) {
        console.error("Failed to initialize field form:", err);
      } finally {
        setLoadingInit(false);
      }
    }
    init();
  }, []);

  // Auto-save draft to LocalStorage for offline field resilience
  useEffect(() => {
    if (loadingInit) return;
    try {
      const payload = {
        selectedClientId,
        selectedSiteId,
        technicianName,
        hivesInspected,
        colonisedCount,
        dropdownValues,
        traceMode,
        photos,
        summaryNotes,
        recommendations,
      };
      localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(payload));
      setDraftSavedAt(new Date().toLocaleTimeString());
    } catch {
      // Quota exceeded if many huge base64 images; ignore gracefully
    }
  }, [
    loadingInit,
    selectedClientId,
    selectedSiteId,
    technicianName,
    hivesInspected,
    colonisedCount,
    dropdownValues,
    traceMode,
    photos,
    summaryNotes,
    recommendations,
  ]);

  const selectedClient = useMemo(
    () => clients.find((c) => c.id === selectedClientId),
    [clients, selectedClientId]
  );

  const selectedSite = useMemo(
    () => selectedClient?.sites?.find((s) => s.id === selectedSiteId),
    [selectedClient, selectedSiteId]
  );

  const photoTagOptions = useMemo(() => {
    const tagCat = dropdownCategories.find((d) => d.key === "photo_tag_category");
    if (!tagCat) {
      return [
        "Boundary Corner / Perimeter Waypoint",
        "Tree-Hung Hive Installation",
        "Ground Stand Hive Array",
        "Grafted Queen & Brood Comb",
        "Bio-Fence Line Segment",
      ];
    }
    try {
      return JSON.parse(tagCat.optionsJson || "[]");
    } catch {
      return ["Hive Inspection"];
    }
  }, [dropdownCategories]);

  // Group dropdowns by groupName (excluding photo_tag_category which is used per-photo)
  const groupedDropdowns = useMemo(() => {
    const groups = new Map<string, DropdownCategoryItem[]>();
    for (const cat of dropdownCategories) {
      if (cat.key === "photo_tag_category") continue;
      const list = groups.get(cat.groupName) || [];
      list.push(cat);
      groups.set(cat.groupName, list);
    }
    return Array.from(groups.entries());
  }, [dropdownCategories]);

  // Compute live Turf.js Polygon Area (Hectares) or Polyline Distance (Metres)
  const liveTrace = useMemo(() => {
    return computeGeoTrace(
      photos.map((p) => ({
        latitude: p.latitude,
        longitude: p.longitude,
        sequenceOrder: p.sequenceOrder,
        includeInTrace: p.includeInTrace,
      })),
      traceMode
    );
  }, [photos, traceMode]);

  // Helper to get current device GPS or fallback around site center
  const getDeviceOrSiteCoords = useCallback(
    (offsetIndex = 0): Promise<{
      lat: number;
      lng: number;
      alt: number | null;
      acc: number | null;
      source: "LIVE_DEVICE_GPS" | "MAP_PIN";
    }> => {
      const baseLat = selectedSite?.latitude ?? -1.2844;
      const baseLng = selectedSite?.longitude ?? 37.2411;
      // Corner offsets so multiple non-EXIF photos automatically form a clean traceable boundary box
      const offsets = [
        [0.0008, -0.0009],
        [0.0009, 0.0011],
        [-0.0008, 0.0012],
        [-0.0009, -0.0008],
        [0.0002, 0.0002],
      ];
      const [dLat, dLng] = offsets[offsetIndex % offsets.length];

      return new Promise((resolve) => {
        if (typeof window !== "undefined" && "geolocation" in navigator) {
          navigator.geolocation.getCurrentPosition(
            (pos) => {
              resolve({
                lat: Number(pos.coords.latitude.toFixed(6)),
                lng: Number(pos.coords.longitude.toFixed(6)),
                alt: pos.coords.altitude ? Number(pos.coords.altitude.toFixed(1)) : null,
                acc: pos.coords.accuracy ? Number(pos.coords.accuracy.toFixed(1)) : null,
                source: "LIVE_DEVICE_GPS",
              });
            },
            () => {
              resolve({
                lat: Number((baseLat + dLat).toFixed(6)),
                lng: Number((baseLng + dLng).toFixed(6)),
                alt: 1510,
                acc: 4.5,
                source: "MAP_PIN",
              });
            },
            { enableHighAccuracy: true, timeout: 3500 }
          );
        } else {
          resolve({
            lat: Number((baseLat + dLat).toFixed(6)),
            lng: Number((baseLng + dLng).toFixed(6)),
            alt: 1510,
            acc: 4.5,
            source: "MAP_PIN",
          });
        }
      });
    },
    [selectedSite]
  );

  // Handle Photo File Selection -> Extract EXIF GPS or fallback to Live Device GPS
  const handlePhotoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setGpsStatusMsg("Reading photo EXIF metadata & GPS coordinates...");
    const newPins: FieldPhotoPin[] = [];

    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const seq = photos.length + i + 1;

      // Convert to DataURL for preview & upload
      const dataUrl = await new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.onload = () => resolve(String(reader.result || ""));
        reader.readAsDataURL(file);
      });

      // Attempt EXIF GPS extraction via exifr
      let lat: number | null = null;
      let lng: number | null = null;
      let alt: number | null = null;
      let capturedDate = new Date().toISOString();
      let source: "EXIF_METADATA" | "LIVE_DEVICE_GPS" | "MAP_PIN" = "EXIF_METADATA";

      try {
        const gps = await exifr.gps(file);
        if (
          gps &&
          typeof gps.latitude === "number" &&
          typeof gps.longitude === "number" &&
          !Number.isNaN(gps.latitude) &&
          !Number.isNaN(gps.longitude)
        ) {
          lat = Number(gps.latitude.toFixed(6));
          lng = Number(gps.longitude.toFixed(6));
        }
        const meta = await exifr.parse(file, ["GPSAltitude", "DateTimeOriginal"]);
        if (meta?.GPSAltitude) alt = Number(Number(meta.GPSAltitude).toFixed(1));
        if (meta?.DateTimeOriginal) {
          capturedDate = new Date(meta.DateTimeOriginal).toISOString();
        }
      } catch {
        // No EXIF tags in image
      }

      let acc: number | null = 3.0;
      if (lat === null || lng === null) {
        const fallback = await getDeviceOrSiteCoords(seq - 1);
        lat = fallback.lat;
        lng = fallback.lng;
        alt = fallback.alt;
        acc = fallback.acc;
        source = fallback.source;
      }

      newPins.push({
        tempId: `pin-${Date.now()}-${i}`,
        imageUrl: dataUrl,
        caption: file.name.replace(/\.[^/.]+$/, "").replace(/[-_]/g, " "),
        tagCategory: photoTagOptions[0] || "Boundary Corner / Perimeter Waypoint",
        latitude: lat,
        longitude: lng,
        altitude: alt,
        accuracy: acc,
        gpsSource: source,
        capturedAt: capturedDate,
        sequenceOrder: seq,
        includeInTrace: true,
      });
    }

    setPhotos((prev) => [...prev, ...newPins]);
    setGpsStatusMsg(
      `Added ${newPins.length} geo-located photo(s) and updated ${traceMode.toLowerCase()} trace.`
    );
    e.target.value = "";
  };

  // Capture live GPS waypoint without photo or with default field image
  const handleCaptureLiveGpsWaypoint = async () => {
    setGpsStatusMsg("Acquiring live GPS coordinates...");
    const seq = photos.length + 1;
    const coords = await getDeviceOrSiteCoords(seq - 1);

    const newPin: FieldPhotoPin = {
      tempId: `gps-${Date.now()}`,
      imageUrl:
        seq % 2 === 1 ? "/images/kamuthanga-apiary.png" : "/images/langstroth-hives.png",
      caption: `Field GPS Waypoint #${seq} (${selectedSite?.subLocation || "Machakos"})`,
      tagCategory: "Boundary Corner / Perimeter Waypoint",
      latitude: coords.lat,
      longitude: coords.lng,
      altitude: coords.alt,
      accuracy: coords.acc,
      gpsSource: coords.source,
      capturedAt: new Date().toISOString(),
      sequenceOrder: seq,
      includeInTrace: true,
    };

    setPhotos((prev) => [...prev, newPin]);
    setGpsStatusMsg(
      `Captured Waypoint #${seq} (${coords.lat.toFixed(5)}, ${coords.lng.toFixed(5)}) via ${coords.source}.`
    );
  };

  // Load 4 realistic geo-tagged photos around the selected site for instant testing
  const handleLoadSampleBoundaryPhotos = () => {
    const baseLat = selectedSite?.latitude ?? -1.2844;
    const baseLng = selectedSite?.longitude ?? 37.2411;

    const demoPhotos: FieldPhotoPin[] = [
      {
        tempId: `demo-1-${Date.now()}`,
        imageUrl: "/images/kamuthanga-apiary.png",
        caption: "NW Corner — Tree-hung Langstroth hives at bee-landing level",
        tagCategory: "Tree-Hung Hive Installation",
        latitude: Number((baseLat + 0.0011).toFixed(6)),
        longitude: Number((baseLng - 0.0013).toFixed(6)),
        altitude: 1514.2,
        accuracy: 2.8,
        gpsSource: "EXIF_METADATA",
        capturedAt: new Date().toISOString(),
        sequenceOrder: 1,
        includeInTrace: true,
      },
      {
        tempId: `demo-2-${Date.now()}`,
        imageUrl: "/images/langstroth-hives.png",
        caption: "NE Corner — Colonised Langstroth hive staging & forage border",
        tagCategory: "Boundary Corner / Perimeter Waypoint",
        latitude: Number((baseLat + 0.0012).toFixed(6)),
        longitude: Number((baseLng + 0.0014).toFixed(6)),
        altitude: 1518.5,
        accuracy: 2.4,
        gpsSource: "EXIF_METADATA",
        capturedAt: new Date().toISOString(),
        sequenceOrder: 2,
        includeInTrace: true,
      },
      {
        tempId: `demo-3-${Date.now()}`,
        imageUrl: "/images/hero-bee.png",
        caption: "SE Corner — Grafted A. m. scutellata worker active on flora",
        tagCategory: "Grafted Queen & Brood Comb",
        latitude: Number((baseLat - 0.0011).toFixed(6)),
        longitude: Number((baseLng + 0.0015).toFixed(6)),
        altitude: 1509.0,
        accuracy: 3.1,
        gpsSource: "LIVE_DEVICE_GPS",
        capturedAt: new Date().toISOString(),
        sequenceOrder: 3,
        includeInTrace: true,
      },
      {
        tempId: `demo-4-${Date.now()}`,
        imageUrl: "/images/kamuthanga-apiary.png",
        caption: "SW Corner — Bio-fence perimeter post & water station check",
        tagCategory: "Bio-Fence Line Segment",
        latitude: Number((baseLat - 0.0012).toFixed(6)),
        longitude: Number((baseLng - 0.0011).toFixed(6)),
        altitude: 1506.4,
        accuracy: 2.9,
        gpsSource: "LIVE_DEVICE_GPS",
        capturedAt: new Date().toISOString(),
        sequenceOrder: 4,
        includeInTrace: true,
      },
    ];

    setPhotos(demoPhotos);
    setGpsStatusMsg(
      "Loaded 4 geo-located corner photos and traced site boundary automatically!"
    );
  };

  // Map click callback to add a waypoint
  const handleMapClickAddPoint = useCallback(
    (lat: number, lng: number) => {
      setPhotos((prev) => {
        const seq = prev.length + 1;
        return [
          ...prev,
          {
            tempId: `map-${Date.now()}`,
            imageUrl: "/images/kamuthanga-apiary.png",
            caption: `Map Traced Corner #${seq}`,
            tagCategory: "Boundary Corner / Perimeter Waypoint",
            latitude: lat,
            longitude: lng,
            altitude: 1510,
            accuracy: 2.0,
            gpsSource: "MAP_PIN",
            capturedAt: new Date().toISOString(),
            sequenceOrder: seq,
            includeInTrace: true,
          },
        ];
      });
    },
    []
  );

  // Map marker drag callback
  const handleWaypointDragEnd = useCallback(
    (index: number, lat: number, lng: number) => {
      setPhotos((prev) =>
        prev.map((item, idx) =>
          idx === index ? { ...item, latitude: lat, longitude: lng } : item
        )
      );
    },
    []
  );

  const handleClearDraft = () => {
    localStorage.removeItem(DRAFT_STORAGE_KEY);
    setPhotos([]);
    setSummaryNotes("");
    setRecommendations("");
    setDraftSavedAt(null);
  };

  const handleSubmitFieldActivity = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedClientId || !selectedSiteId) return;
    setSubmitting(true);

    try {
      const res = await fetch("/api/activities", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          clientId: selectedClientId,
          siteId: selectedSiteId,
          technicianName,
          visitDate,
          activityType:
            dropdownValues["activity_type"] ||
            "Routine Monthly/Quarterly Maintenance (AM-01/02)",
          traceMode,
          dropdownData: dropdownValues,
          hivesInspected,
          colonisedCount,
          summaryNotes:
            summaryNotes ||
            `Field activity (${dropdownValues["activity_type"] || "Inspection"}) completed at ${selectedSite?.name}. Traced ${liveTrace.pointCount} GPS waypoints (${
              traceMode === "POLYGON"
                ? `${liveTrace.areaHectares} Ha / ${liveTrace.distanceMetres}m perimeter`
                : `${liveTrace.distanceMetres}m linear distance`
            }).`,
          recommendations:
            recommendations ||
            `Next scheduled step: ${dropdownValues["follow_up_action"] || "Routine 30-day inspection"}.`,
          photos,
          sendEmailImmediately,
        }),
      });

      const data = await res.json();
      if (data.activity?.id) {
        localStorage.removeItem(DRAFT_STORAGE_KEY);
        router.push(`/erp/reports/${data.activity.id}`);
      }
    } catch (err) {
      console.error("Failed to submit field activity:", err);
    } finally {
      setSubmitting(false);
    }
  };

  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">
        <form onSubmit={handleSubmitFieldActivity} className="space-y-8">
          {/* Header Banner with Offline Cache Status */}
          <div className="bg-hive-950 text-white rounded-2xl p-6 border-b-4 border-honey-500 flex flex-col md:flex-row md:items-center justify-between gap-4 shadow-md">
            <div>
              <div className="inline-flex items-center gap-2 text-honey-400 text-xs font-bold uppercase tracking-wider">
                <Sparkles className="w-3.5 h-3.5" />
                Mobile-First Field Data & GIS Area Collector
              </div>
              <h1 className="text-2xl sm:text-3xl font-black mt-1">
                Log Field Activity, Dropdowns & Geo-Located Photos
              </h1>
              <p className="text-xs sm:text-sm text-slate-300 mt-1">
                Select standardized apiculture dropdowns, upload or snap GPS photos, and automatically
                trace the farm area (Hectares) or bio-fence line (Metres).
              </p>
            </div>

            <div className="flex flex-col items-start md:items-end gap-2 shrink-0">
              {draftSavedAt && (
                <div className="inline-flex items-center gap-1.5 text-xs bg-emerald-500/20 text-emerald-300 px-3 py-1.5 rounded-lg border border-emerald-500/30">
                  <Save className="w-3.5 h-3.5" />
                  Offline-Safe Draft Saved ({draftSavedAt})
                </div>
              )}
              <button
                type="button"
                onClick={handleClearDraft}
                className="text-xs text-slate-400 hover:text-white inline-flex items-center gap-1"
              >
                <RotateCcw className="w-3.5 h-3.5" /> Reset Form / Clear Draft
              </button>
            </div>
          </div>

          {/* Step 1: Client, Site & Visit Context */}
          <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-5">
            <div className="flex items-center justify-between border-b border-slate-200 pb-3">
              <h2 className="text-lg font-black text-slate-900 flex items-center gap-2">
                <span className="w-6 h-6 rounded-full bg-honey-500 text-hive-950 text-xs font-black flex items-center justify-center">
                  1
                </span>
                Client, Apiary Site & Hive Counts
              </h2>
              <span className="text-xs text-slate-500">
                Select target farm, conservancy, or project site
              </span>
            </div>

            <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Client / Organization *
                </label>
                <select
                  required
                  value={selectedClientId}
                  onChange={(e) => {
                    const cid = e.target.value;
                    setSelectedClientId(cid);
                    const c = clients.find((cl) => cl.id === cid);
                    if (c && c.sites?.length > 0) {
                      setSelectedSiteId(c.sites[0].id);
                      setHivesInspected(c.sites[0].totalHives || 20);
                      setColonisedCount(c.sites[0].colonisedHives || 18);
                    }
                  }}
                  className="w-full rounded-xl border border-slate-300 px-3.5 py-2.5 text-sm font-semibold bg-slate-50 focus:bg-white focus:border-amber-500 focus:outline-none"
                >
                  {clients.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name} ({c.subLocation})
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Apiary / Bio-Fence Site *
                </label>
                <select
                  required
                  value={selectedSiteId}
                  onChange={(e) => {
                    const sid = e.target.value;
                    setSelectedSiteId(sid);
                    const s = selectedClient?.sites?.find((st) => st.id === sid);
                    if (s) {
                      setHivesInspected(s.totalHives || 20);
                      setColonisedCount(s.colonisedHives || 18);
                    }
                  }}
                  className="w-full rounded-xl border border-slate-300 px-3.5 py-2.5 text-sm font-semibold bg-slate-50 focus:bg-white focus:border-amber-500 focus:outline-none"
                >
                  {selectedClient?.sites?.map((s) => (
                    <option key={s.id} value={s.id}>
                      {s.name} — {s.subLocation}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Field Apiarist / Technician
                </label>
                <select
                  value={technicianName}
                  onChange={(e) => setTechnicianName(e.target.value)}
                  className="w-full rounded-xl border border-slate-300 px-3.5 py-2.5 text-sm font-semibold bg-slate-50 focus:bg-white focus:border-amber-500 focus:outline-none"
                >
                  <option value="Mr. David Mwangangi Kyalo">
                    Mr. David Mwangangi Kyalo (Lead Apiarist)
                  </option>
                  <option value="Mr. Maveke">Mr. Maveke (Operations Director)</option>
                  <option value="Peter Mutua">Peter Mutua (Queen Grafting & GIS Tech)</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Visit Date & Time
                </label>
                <input
                  type="datetime-local"
                  value={visitDate}
                  onChange={(e) => setVisitDate(e.target.value)}
                  className="w-full rounded-xl border border-slate-300 px-3.5 py-2 text-sm font-semibold bg-slate-50 focus:bg-white"
                />
              </div>
            </div>

            <div className="grid sm:grid-cols-3 gap-4 pt-2">
              <div className="bg-amber-50/60 p-3.5 rounded-xl border border-amber-200">
                <label className="block text-xs font-bold text-amber-900 mb-1">
                  Total Hives Inspected / Deployed
                </label>
                <input
                  type="number"
                  min={0}
                  value={hivesInspected}
                  onChange={(e) => setHivesInspected(Number(e.target.value))}
                  className="w-full rounded-lg border border-amber-300 px-3 py-1.5 text-sm font-black text-slate-900 bg-white"
                />
              </div>

              <div className="bg-emerald-50/60 p-3.5 rounded-xl border border-emerald-200">
                <label className="block text-xs font-bold text-emerald-900 mb-1">
                  Active Colonised Hives Count
                </label>
                <input
                  type="number"
                  min={0}
                  value={colonisedCount}
                  onChange={(e) => setColonisedCount(Number(e.target.value))}
                  className="w-full rounded-lg border border-emerald-300 px-3 py-1.5 text-sm font-black text-emerald-900 bg-white"
                />
              </div>

              <div className="bg-slate-100 p-3.5 rounded-xl border border-slate-200 flex flex-col justify-center">
                <div className="text-xs font-bold text-slate-500">Client Report Recipient</div>
                <div className="text-sm font-extrabold text-slate-900 truncate mt-0.5">
                  {selectedClient?.contactPerson} ({selectedClient?.email})
                </div>
                <div className="text-[11px] text-slate-500">
                  Site Base GPS: {selectedSite?.latitude.toFixed(4)},{" "}
                  {selectedSite?.longitude.toFixed(4)}
                </div>
              </div>
            </div>
          </div>

          {/* Step 2: Standardized Field Activity Dropdowns */}
          <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-6">
            <div className="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200 pb-3">
              <div>
                <h2 className="text-lg font-black text-slate-900 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-honey-500 text-hive-950 text-xs font-black flex items-center justify-center">
                    2
                  </span>
                  Dropdown-Driven Field Assessment Metrics
                </h2>
                <p className="text-xs text-slate-500 mt-0.5">
                  Fast, standardized dropdown data collection tailored to Davally Apiculture&apos;s
                  services.
                </p>
              </div>
            </div>

            {groupedDropdowns.map(([groupName, items]) => (
              <div key={groupName} className="space-y-3">
                <div className="text-xs font-extrabold uppercase tracking-wider text-amber-700 bg-amber-50 px-3 py-1.5 rounded-lg inline-block border border-amber-200">
                  {groupName}
                </div>
                <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-4">
                  {items.map((cat) => {
                    let options: string[] = [];
                    try {
                      options = JSON.parse(cat.optionsJson || "[]");
                    } catch {
                      options = [];
                    }
                    return (
                      <div
                        key={cat.key}
                        className="bg-slate-50/80 p-3.5 rounded-xl border border-slate-200 hover:border-amber-400 transition"
                      >
                        <label className="block text-xs font-extrabold text-slate-800 mb-1">
                          {cat.label}
                        </label>
                        {cat.description && (
                          <div className="text-[11px] text-slate-500 mb-2 line-clamp-1">
                            {cat.description}
                          </div>
                        )}
                        <select
                          value={dropdownValues[cat.key] || ""}
                          onChange={(e) =>
                            setDropdownValues((prev) => ({
                              ...prev,
                              [cat.key]: e.target.value,
                            }))
                          }
                          className="w-full rounded-lg border border-slate-300 bg-white px-3 py-2 text-xs sm:text-sm font-semibold text-slate-900 focus:border-amber-500 focus:outline-none"
                        >
                          {options.map((opt) => (
                            <option key={opt} value={opt}>
                              {opt}
                            </option>
                          ))}
                        </select>
                      </div>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>

          {/* Step 3: Geo-Located Photos & Area / Perimeter Tracing */}
          <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-6">
            <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 border-b border-slate-200 pb-4">
              <div>
                <h2 className="text-lg font-black text-slate-900 flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-honey-500 text-hive-950 text-xs font-black flex items-center justify-center">
                    3
                  </span>
                  Geo-Located Photos & Automatic Area / Perimeter Tracing
                </h2>
                <p className="text-xs text-slate-500 mt-0.5">
                  Upload photos (auto-extracts EXIF GPS) or capture live device GPS waypoints to
                  trace the farm area (Hectares) or bio-fence line (Metres).
                </p>
              </div>

              {/* Polygon vs Polyline Switcher */}
              <div className="inline-flex bg-slate-100 p-1 rounded-xl border border-slate-200 self-start">
                <button
                  type="button"
                  onClick={() => setTraceMode("POLYGON")}
                  className={`px-3.5 py-2 rounded-lg text-xs font-extrabold transition ${
                    traceMode === "POLYGON"
                      ? "bg-hive-900 text-honey-400 shadow-sm"
                      : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  Polygon Area Mode (Hectares)
                </button>
                <button
                  type="button"
                  onClick={() => setTraceMode("POLYLINE")}
                  className={`px-3.5 py-2 rounded-lg text-xs font-extrabold transition ${
                    traceMode === "POLYLINE"
                      ? "bg-hive-900 text-honey-400 shadow-sm"
                      : "text-slate-600 hover:text-slate-900"
                  }`}
                >
                  Bio-Fence Line Mode (Metres)
                </button>
              </div>
            </div>

            {/* Action Buttons for Capturing Photos & GPS */}
            <div className="flex flex-wrap items-center gap-3">
              <label className="cursor-pointer inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-honey-500 hover:bg-honey-400 text-hive-950 font-black text-xs sm:text-sm shadow-sm transition">
                <Camera className="w-4 h-4" />
                <span>Take / Upload Geo-Located Photos</span>
                <input
                  type="file"
                  accept="image/*"
                  multiple
                  onChange={handlePhotoUpload}
                  className="hidden"
                />
              </label>

              <button
                type="button"
                onClick={handleCaptureLiveGpsWaypoint}
                className="inline-flex items-center gap-2 px-4 py-3 rounded-xl bg-hive-900 hover:bg-hive-800 text-white font-bold text-xs sm:text-sm transition"
              >
                <Navigation className="w-4 h-4 text-honey-400" />
                Capture Live GPS Corner Pin
              </button>

              <button
                type="button"
                onClick={handleLoadSampleBoundaryPhotos}
                className="inline-flex items-center gap-2 px-4 py-3 rounded-xl bg-amber-50 hover:bg-amber-100 text-amber-900 border border-amber-300 font-bold text-xs sm:text-sm transition"
              >
                <Sparkles className="w-4 h-4 text-amber-600" />
                Load 4-Point Demo Boundary Photos
              </button>
            </div>

            {gpsStatusMsg && (
              <div className="text-xs font-semibold text-amber-900 bg-amber-50 border border-amber-200 px-4 py-2.5 rounded-xl flex items-center gap-2">
                <CheckCircle2 className="w-4 h-4 text-amber-600 shrink-0" />
                <span>{gpsStatusMsg}</span>
              </div>
            )}

            {/* Live Traced Metrics Banner */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 bg-hive-950 text-white p-4 rounded-xl border border-slate-800">
              <div>
                <div className="text-[10px] font-bold uppercase text-slate-400">
                  GPS Waypoints Active
                </div>
                <div className="text-xl font-black text-honey-400 mt-0.5">
                  {liveTrace.pointCount} Pins
                </div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase text-slate-400">
                  Traced Area (Hectares)
                </div>
                <div className="text-xl font-black text-white mt-0.5">
                  {traceMode === "POLYGON" ? `${liveTrace.areaHectares} Ha` : "Linear Mode"}
                </div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase text-slate-400">
                  Area (Acres / m²)
                </div>
                <div className="text-sm font-bold text-slate-200 mt-1">
                  {traceMode === "POLYGON"
                    ? `${liveTrace.areaAcres} ac (${liveTrace.areaSqm.toLocaleString()} m²)`
                    : "N/A"}
                </div>
              </div>
              <div>
                <div className="text-[10px] font-bold uppercase text-slate-400">
                  {traceMode === "POLYGON" ? "Boundary Perimeter" : "Bio-Fence / Line Length"}
                </div>
                <div className="text-xl font-black text-emerald-400 mt-0.5">
                  {liveTrace.distanceMetres.toLocaleString()} m
                </div>
              </div>
            </div>

            {/* Interactive Leaflet Map with Live Polygon/Polyline Trace */}
            <GeoTraceMap
              waypoints={photos}
              traceMode={traceMode}
              editable={true}
              height="440px"
              defaultCenter={[
                selectedSite?.latitude ?? -1.2844,
                selectedSite?.longitude ?? 37.2411,
              ]}
              onMapClickAddPoint={handleMapClickAddPoint}
              onWaypointDragEnd={handleWaypointDragEnd}
            />

            {/* Geo-Located Photo Cards Grid */}
            {photos.length > 0 && (
              <div className="space-y-3">
                <div className="text-xs font-bold uppercase text-slate-500">
                  Captured Geo-Photo Waypoints ({photos.length}) — Edit Captions, Tags, or
                  Coordinates
                </div>
                <div className="grid md:grid-cols-2 gap-4">
                  {photos.map((pin, idx) => (
                    <div
                      key={pin.tempId}
                      className="flex gap-3.5 p-3.5 rounded-xl border border-slate-200 bg-slate-50/70 items-start"
                    >
                      <div className="relative w-24 h-24 rounded-lg overflow-hidden shrink-0 border border-slate-300 bg-slate-200">
                        <img
                          src={pin.imageUrl}
                          alt={pin.caption}
                          className="w-full h-full object-cover"
                        />
                        <span className="absolute top-1 left-1 w-6 h-6 rounded-full bg-honey-500 text-hive-950 font-black text-xs flex items-center justify-center shadow">
                          #{pin.sequenceOrder}
                        </span>
                      </div>

                      <div className="flex-1 space-y-2 text-xs">
                        <div className="flex items-center justify-between gap-2">
                          <select
                            value={pin.tagCategory}
                            onChange={(e) =>
                              setPhotos((prev) =>
                                prev.map((p, i) =>
                                  i === idx ? { ...p, tagCategory: e.target.value } : p
                                )
                              )
                            }
                            className="rounded-md border border-slate-300 px-2 py-1 font-bold text-amber-900 bg-amber-50 text-[11px]"
                          >
                            {photoTagOptions.map((opt: string) => (
                              <option key={opt} value={opt}>
                                {opt}
                              </option>
                            ))}
                          </select>

                          <button
                            type="button"
                            onClick={() =>
                              setPhotos((prev) =>
                                prev
                                  .filter((_, i) => i !== idx)
                                  .map((p, newIdx) => ({ ...p, sequenceOrder: newIdx + 1 }))
                              )
                            }
                            className="text-rose-600 hover:text-rose-800 p-1"
                            title="Remove waypoint"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>

                        <input
                          type="text"
                          value={pin.caption}
                          onChange={(e) =>
                            setPhotos((prev) =>
                              prev.map((p, i) =>
                                i === idx ? { ...p, caption: e.target.value } : p
                              )
                            )
                          }
                          placeholder="Photo description / hive ID..."
                          className="w-full rounded-md border border-slate-300 px-2.5 py-1 text-xs font-semibold bg-white"
                        />

                        <div className="grid grid-cols-2 gap-2">
                          <div>
                            <span className="text-[10px] text-slate-500 block">Latitude</span>
                            <input
                              type="number"
                              step="any"
                              value={pin.latitude}
                              onChange={(e) =>
                                setPhotos((prev) =>
                                  prev.map((p, i) =>
                                    i === idx ? { ...p, latitude: Number(e.target.value) } : p
                                  )
                                )
                              }
                              className="w-full rounded border border-slate-300 px-2 py-1 font-mono text-[11px] bg-white"
                            />
                          </div>
                          <div>
                            <span className="text-[10px] text-slate-500 block">Longitude</span>
                            <input
                              type="number"
                              step="any"
                              value={pin.longitude}
                              onChange={(e) =>
                                setPhotos((prev) =>
                                  prev.map((p, i) =>
                                    i === idx ? { ...p, longitude: Number(e.target.value) } : p
                                  )
                                )
                              }
                              className="w-full rounded border border-slate-300 px-2 py-1 font-mono text-[11px] bg-white"
                            />
                          </div>
                        </div>

                        <div className="flex items-center justify-between pt-0.5 text-[11px] text-slate-500">
                          <span>Source: {pin.gpsSource}</span>
                          <label className="flex items-center gap-1.5 cursor-pointer font-semibold text-slate-700">
                            <input
                              type="checkbox"
                              checked={pin.includeInTrace}
                              onChange={(e) =>
                                setPhotos((prev) =>
                                  prev.map((p, i) =>
                                    i === idx
                                      ? { ...p, includeInTrace: e.target.checked }
                                      : p
                                  )
                                )
                              }
                              className="accent-amber-600"
                            />
                            Connect in Boundary Trace
                          </label>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Step 4: Summary Notes, Recommendations & Submit */}
          <div className="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm space-y-5">
            <h2 className="text-lg font-black text-slate-900 flex items-center gap-2">
              <span className="w-6 h-6 rounded-full bg-honey-500 text-hive-950 text-xs font-black flex items-center justify-center">
                4
              </span>
              Executive Field Summary & Client Report Dispatch
            </h2>

            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Field Observations Summary (Optional — auto-generated if left blank)
                </label>
                <textarea
                  rows={3}
                  value={summaryNotes}
                  onChange={(e) => setSummaryNotes(e.target.value)}
                  placeholder="Additional notes on colony vigor, queen acceptance, or site forage..."
                  className="w-full rounded-xl border border-slate-300 px-3.5 py-2.5 text-sm focus:border-amber-500 focus:outline-none"
                />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-700 mb-1">
                  Recommendations for Client (Optional — auto-generated if left blank)
                </label>
                <textarea
                  rows={3}
                  value={recommendations}
                  onChange={(e) => setRecommendations(e.target.value)}
                  placeholder="Recommended next steps, honey supering schedule, or bio-fence upkeep..."
                  className="w-full rounded-xl border border-slate-300 px-3.5 py-2.5 text-sm focus:border-amber-500 focus:outline-none"
                />
              </div>
            </div>

            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 pt-3 border-t border-slate-200">
              {currentUser?.role === "ADMIN" ? (
                <label className="flex items-center gap-3 cursor-pointer bg-amber-50 px-4 py-3 rounded-xl border border-amber-200">
                  <input
                    type="checkbox"
                    checked={sendEmailImmediately}
                    onChange={(e) => setSendEmailImmediately(e.target.checked)}
                    className="w-4 h-4 accent-amber-600"
                  />
                  <div>
                    <div className="text-xs font-extrabold text-amber-950">
                      Immediately Email Branded Report & GIS Link to Client ({selectedClient?.email})
                    </div>
                    <div className="text-[11px] text-amber-800">
                      Admin Privilege: Leave unchecked if you want to preview/edit the report on the
                      next screen before sending.
                    </div>
                  </div>
                </label>
              ) : (
                <div className="bg-emerald-50 px-4 py-3 rounded-xl border border-emerald-200 text-xs text-emerald-900">
                  <strong className="font-extrabold">Field Technician Submission:</strong> Logged
                  under <strong>{currentUser?.name || technicianName}</strong>. Your report &amp;
                  traced GPS polygon will be submitted to the Admin Review queue for approval and
                  client email dispatch.
                </div>
              )}

              <button
                type="submit"
                disabled={submitting}
                className="inline-flex items-center justify-center gap-2 px-7 py-3.5 rounded-xl bg-hive-900 hover:bg-hive-800 text-honey-400 font-black text-sm shadow-lg transition shrink-0"
              >
                {currentUser?.role === "ADMIN" && sendEmailImmediately ? (
                  <>
                    <Send className="w-4 h-4" />
                    {submitting
                      ? "Saving & Dispatching Email..."
                      : "Save Field Log & Email Client"}
                  </>
                ) : (
                  <>
                    <FileCheck2 className="w-4 h-4" />
                    {submitting
                      ? "Saving Field Report..."
                      : currentUser?.role === "ADMIN"
                      ? "Save & Open Report Review / Emailer"
                      : "Submit Field Log for Admin Approval"}
                  </>
                )}
              </button>
            </div>
          </div>
        </form>
      </main>
    </div>
  );
}
