"use client";

import React, { useEffect, useState, useMemo, useCallback } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import dynamic from "next/dynamic";
import ErpNavbar from "@/components/ErpNavbar";
import { computeGeoTrace } from "@/lib/geo";
import {
  Mail,
  Printer,
  Share2,
  CheckCircle2,
  MapPin,
  Save,
  ExternalLink,
  ArrowLeft,
  Send,
  Copy,
  Sparkles,
} from "lucide-react";

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

interface PhotoWayPoint {
  id: string;
  imageUrl: string;
  caption: string;
  tagCategory: string;
  latitude: number;
  longitude: number;
  altitude?: number | null;
  accuracy?: number | null;
  gpsSource: string;
  capturedAt: string;
  sequenceOrder: number;
  includeInTrace: boolean;
}

interface ReportDetail {
  id: string;
  reportCode: string;
  shareToken: string;
  technicianName: string;
  visitDate: string;
  activityType: string;
  traceMode: "POLYGON" | "POLYLINE";
  calculatedAreaHa: number;
  calculatedAreaSqm: number;
  calculatedDistanceM: number;
  dropdownData: string;
  hivesInspected: number;
  colonisedCount: number;
  summaryNotes: string;
  recommendations: string;
  status: string;
  emailedAt?: string | null;
  emailedTo?: string | null;
  client: {
    id: string;
    name: string;
    contactPerson: string;
    email: string;
    phone: string;
    subLocation: string;
    county: string;
  };
  site: {
    id: string;
    name: string;
    subLocation: string;
    county: string;
    latitude: number;
    longitude: number;
  };
  photos: PhotoWayPoint[];
}

export default function AdminReportReviewPage() {
  const params = useParams<{ id: string }>();
  const reportId = params?.id;

  const [currentUser, setCurrentUser] = useState<{
    id: string;
    name: string;
    email: string;
    role: "ADMIN" | "TECHNICIAN";
  } | null>(null);
  const [report, setReport] = useState<ReportDetail | null>(null);
  const [loading, setLoading] = useState(true);

  // Editable state for Admin Review
  const [traceMode, setTraceMode] = useState<"POLYGON" | "POLYLINE">("POLYGON");
  const [photos, setPhotos] = useState<PhotoWayPoint[]>([]);
  const [summaryNotes, setSummaryNotes] = useState("");
  const [recommendations, setRecommendations] = useState("");
  const [savingEdits, setSavingEdits] = useState(false);
  const [saveSuccess, setSaveSuccess] = useState(false);

  // Email dispatch state
  const [toEmail, setToEmail] = useState("");
  const [ccEmail, setCcEmail] = useState("");
  const [customMessage, setCustomMessage] = useState("");
  const [sendingEmail, setSendingEmail] = useState(false);
  const [emailDispatchResult, setEmailDispatchResult] = useState<{
    mode: string;
    sentTo: string;
    previewUrl?: string | null;
    shareUrl?: string;
  } | null>(null);
  const [copiedLink, setCopiedLink] = useState(false);

  useEffect(() => {
    fetch("/api/auth/me")
      .then((r) => r.json())
      .then((d) => {
        if (d.user) setCurrentUser(d.user);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    if (!reportId) return;
    async function fetchReport() {
      setLoading(true);
      try {
        const res = await fetch(`/api/activities/${reportId}`);
        const data = await res.json();
        if (data.activity) {
          const act: ReportDetail = data.activity;
          setReport(act);
          setTraceMode(act.traceMode === "POLYLINE" ? "POLYLINE" : "POLYGON");
          setPhotos(act.photos || []);
          setSummaryNotes(act.summaryNotes || "");
          setRecommendations(act.recommendations || "");
          setToEmail(act.client?.email || "");
        }
      } catch (err) {
        console.error("Failed to fetch report:", err);
      } finally {
        setLoading(false);
      }
    }
    fetchReport();
  }, [reportId]);

  const parsedDropdowns = useMemo(() => {
    if (!report?.dropdownData) return {};
    try {
      return JSON.parse(report.dropdownData) as Record<string, string>;
    } catch {
      return {};
    }
  }, [report]);

  const liveTrace = useMemo(() => {
    return computeGeoTrace(
      photos.map((p) => ({
        latitude: p.latitude,
        longitude: p.longitude,
        sequenceOrder: p.sequenceOrder,
        includeInTrace: p.includeInTrace,
      })),
      traceMode
    );
  }, [photos, traceMode]);

  const handleWaypointDragEnd = useCallback(
    (index: number, lat: number, lng: number) => {
      setPhotos((prev) =>
        prev.map((p, idx) =>
          idx === index ? { ...p, latitude: lat, longitude: lng } : p
        )
      );
      setSaveSuccess(false);
    },
    []
  );

  const handleSaveChanges = async () => {
    if (!report) return;
    setSavingEdits(true);
    setSaveSuccess(false);
    try {
      const res = await fetch(`/api/activities/${report.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          traceMode,
          photos,
          summaryNotes,
          recommendations,
          status: report.status === "PENDING_REVIEW" ? "APPROVED" : report.status,
        }),
      });
      const data = await res.json();
      if (data.activity) {
        setReport(data.activity);
        setPhotos(data.activity.photos || []);
        setSaveSuccess(true);
      }
    } finally {
      setSavingEdits(false);
    }
  };

  const handleSendEmailToClient = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!report || !toEmail) return;
    setSendingEmail(true);
    try {
      // Save any pending edits first
      await fetch(`/api/activities/${report.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          traceMode,
          photos,
          summaryNotes,
          recommendations,
        }),
      });

      const res = await fetch(`/api/activities/${report.id}/send-email`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          toEmail,
          ccEmail,
          customMessage,
        }),
      });
      const data = await res.json();
      if (data.activity) {
        setReport(data.activity);
        setEmailDispatchResult({
          ...data.emailResult,
          shareUrl: data.shareUrl,
        });
      }
    } finally {
      setSendingEmail(false);
    }
  };

  const shareUrl =
    typeof window !== "undefined" && report
      ? `${window.location.origin}/reports/share/${report.shareToken}`
      : report
      ? `/reports/share/${report.shareToken}`
      : "";

  const handleCopyShareLink = () => {
    if (!shareUrl) return;
    navigator.clipboard.writeText(shareUrl);
    setCopiedLink(true);
    setTimeout(() => setCopiedLink(false), 2500);
  };

  if (loading) {
    return (
      <div className="min-h-screen flex flex-col bg-slate-50">
        <ErpNavbar />
        <div className="p-12 text-center text-sm text-slate-500">
          Loading Field & GIS Report...
        </div>
      </div>
    );
  }

  if (!report) {
    return (
      <div className="min-h-screen flex flex-col bg-slate-50">
        <ErpNavbar />
        <div className="p-12 text-center space-y-4">
          <div className="text-lg font-bold text-slate-800">Report Not Found</div>
          <Link
            href="/erp"
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-hive-900 text-honey-400 text-xs font-bold"
          >
            &larr; Back to ERP Dashboard
          </Link>
        </div>
      </div>
    );
  }

  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-6">
        {/* Top Admin Control Bar (Hidden when printing PDF) */}
        <div className="no-print flex flex-wrap items-center justify-between gap-4 bg-white p-4 rounded-2xl border border-slate-200 shadow-sm">
          <div className="flex items-center gap-3">
            <Link
              href="/erp"
              className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-slate-100 hover:bg-slate-200 text-xs font-bold text-slate-700"
            >
              <ArrowLeft className="w-3.5 h-3.5" />
              ERP Reports
            </Link>
            <span className="font-mono text-xs font-black px-2.5 py-1 rounded bg-hive-900 text-honey-400">
              {report.reportCode}
            </span>
            <span
              className={`text-xs font-bold px-3 py-1 rounded-full ${
                report.status === "SENT_TO_CLIENT"
                  ? "bg-emerald-100 text-emerald-800"
                  : "bg-amber-100 text-amber-800"
              }`}
            >
              {report.status === "SENT_TO_CLIENT"
                ? `Emailed to ${report.emailedTo}`
                : report.status.replace("_", " ")}
            </span>
          </div>

          <div className="flex flex-wrap items-center gap-2.5">
            <button
              type="button"
              onClick={handleCopyShareLink}
              className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 text-xs font-bold transition"
            >
              <Copy className="w-3.5 h-3.5" />
              {copiedLink ? "Client Share Link Copied!" : "Copy Client Share Link"}
            </button>

            <Link
              href={`/reports/share/${report.shareToken}`}
              target="_blank"
              className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-amber-50 hover:bg-amber-100 text-amber-900 border border-amber-300 text-xs font-bold transition"
            >
              <Share2 className="w-3.5 h-3.5" />
              Open Client Web View
            </Link>

            <button
              type="button"
              onClick={() => window.print()}
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-hive-900 hover:bg-hive-800 text-honey-400 text-xs font-extrabold transition shadow-sm"
            >
              <Printer className="w-3.5 h-3.5" />
              Print / Save Official PDF
            </button>
          </div>
        </div>

        <div className="grid lg:grid-cols-12 gap-6 items-start">
          {/* Left 8 Columns: Official Branded Report Document + Interactive GIS Trace */}
          <div className="lg:col-span-8 bg-white rounded-2xl border border-slate-200 shadow-sm overflow-hidden">
            {/* Branded Report Header */}
            <div className="bg-hive-950 text-white p-6 sm:p-8 border-b-4 border-honey-500 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
              <div className="flex items-center gap-4">
                <img
                  src="/images/logo-icon.png"
                  alt="Davally Logo"
                  className="w-14 h-14 rounded-xl bg-white p-1 object-contain"
                />
                <div>
                  <div className="text-[11px] font-extrabold uppercase tracking-widest text-honey-400">
                    Davally Apiculture Limited • Official Field & GIS Report
                  </div>
                  <h1 className="text-xl sm:text-2xl font-black mt-0.5">
                    {report.activityType}
                  </h1>
                  <div className="text-xs text-slate-300 mt-1">
                    Site: <strong>{report.site?.name}</strong> ({report.site?.subLocation},{" "}
                    {report.site?.county})
                  </div>
                </div>
              </div>

              <div className="text-left sm:text-right text-xs space-y-0.5 shrink-0">
                <div className="font-mono font-bold text-honey-400 text-sm">
                  {report.reportCode}
                </div>
                <div className="text-slate-300">
                  Date:{" "}
                  {new Date(report.visitDate).toLocaleDateString("en-KE", {
                    dateStyle: "medium",
                  })}
                </div>
                <div className="text-slate-400">Apiarist: {report.technicianName}</div>
              </div>
            </div>

            <div className="p-6 sm:p-8 space-y-8">
              {/* Client & Traced GIS KPI Strip */}
              <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 bg-slate-50 p-4 rounded-xl border border-slate-200">
                <div>
                  <div className="text-[10px] font-bold uppercase text-slate-500">
                    Client Organization
                  </div>
                  <div className="text-sm font-extrabold text-slate-900 mt-0.5">
                    {report.client?.name}
                  </div>
                  <div className="text-[11px] text-slate-500">
                    {report.client?.contactPerson}
                  </div>
                </div>

                <div>
                  <div className="text-[10px] font-bold uppercase text-slate-500">
                    Colony Occupancy
                  </div>
                  <div className="text-lg font-black text-emerald-700 mt-0.5">
                    {report.colonisedCount} / {report.hivesInspected} Hives
                  </div>
                  <div className="text-[11px] text-slate-500">
                    {report.hivesInspected > 0
                      ? `${Math.round(
                          (report.colonisedCount / report.hivesInspected) * 100
                        )}% Active`
                      : "Site Survey"}
                  </div>
                </div>

                <div>
                  <div className="text-[10px] font-bold uppercase text-slate-500">
                    Traced Area (GIS)
                  </div>
                  <div className="text-lg font-black text-amber-700 mt-0.5">
                    {traceMode === "POLYGON" && liveTrace.areaHectares > 0
                      ? `${liveTrace.areaHectares} Ha`
                      : "Linear Trace"}
                  </div>
                  <div className="text-[11px] text-slate-500">
                    {traceMode === "POLYGON" && liveTrace.areaSqm > 0
                      ? `${liveTrace.areaSqm.toLocaleString()} m² (${liveTrace.areaAcres} ac)`
                      : `${liveTrace.pointCount} GPS Waypoints`}
                  </div>
                </div>

                <div>
                  <div className="text-[10px] font-bold uppercase text-slate-500">
                    {traceMode === "POLYGON" ? "Boundary Perimeter" : "Bio-Fence Length"}
                  </div>
                  <div className="text-lg font-black text-slate-900 mt-0.5">
                    {liveTrace.distanceMetres.toLocaleString()} m
                  </div>
                  <div className="text-[11px] text-slate-500">
                    Turf.js Geodesic Verified
                  </div>
                </div>
              </div>

              {/* Section 1: Interactive Satellite Area/Perimeter Trace Map */}
              <div className="space-y-3">
                <div className="flex flex-wrap items-center justify-between gap-2">
                  <div>
                    <h2 className="text-base font-black text-slate-900 flex items-center gap-2">
                      <MapPin className="w-4 h-4 text-amber-500" />
                      1. Geo-Located Waypoints & Traced Site Geometry
                    </h2>
                    <p className="text-xs text-slate-500">
                      Drag numbered pins to fine-tune the traced area or switch between Polygon
                      (Hectares) and Bio-Fence Line (Metres).
                    </p>
                  </div>

                  <div className="no-print inline-flex bg-slate-100 p-1 rounded-lg border border-slate-200">
                    <button
                      type="button"
                      onClick={() => setTraceMode("POLYGON")}
                      className={`px-2.5 py-1 rounded text-xs font-bold ${
                        traceMode === "POLYGON"
                          ? "bg-hive-900 text-honey-400"
                          : "text-slate-600"
                      }`}
                    >
                      Polygon (Ha)
                    </button>
                    <button
                      type="button"
                      onClick={() => setTraceMode("POLYLINE")}
                      className={`px-2.5 py-1 rounded text-xs font-bold ${
                        traceMode === "POLYLINE"
                          ? "bg-hive-900 text-honey-400"
                          : "text-slate-600"
                      }`}
                    >
                      Polyline (m)
                    </button>
                  </div>
                </div>

                <GeoTraceMap
                  waypoints={photos}
                  traceMode={traceMode}
                  editable={true}
                  height="400px"
                  onWaypointDragEnd={handleWaypointDragEnd}
                />
              </div>

              {/* Section 2: Standardized Dropdown Findings */}
              <div className="space-y-3">
                <h2 className="text-base font-black text-slate-900 border-b-2 border-honey-500 pb-1.5">
                  2. Standardized Field Assessment Metrics (Dropdown Data)
                </h2>
                <div className="grid sm:grid-cols-2 gap-3">
                  {Object.entries(parsedDropdowns).map(([key, val]) => (
                    <div
                      key={key}
                      className="p-3 rounded-xl bg-slate-50 border border-slate-200 flex flex-col justify-between"
                    >
                      <div className="text-[11px] font-bold uppercase text-slate-500">
                        {key.replace(/_/g, " ")}
                      </div>
                      <div className="text-xs sm:text-sm font-extrabold text-slate-900 mt-1">
                        {val}
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Section 3: Editable Executive Summary & Recommendations */}
              <div className="space-y-4">
                <h2 className="text-base font-black text-slate-900 border-b-2 border-honey-500 pb-1.5">
                  3. Apiarist Field Summary & Recommendations
                </h2>
                <div className="grid sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-xs font-bold text-slate-700 mb-1">
                      Executive Field Observations
                    </label>
                    <textarea
                      rows={4}
                      value={summaryNotes}
                      onChange={(e) => {
                        setSummaryNotes(e.target.value);
                        setSaveSuccess(false);
                      }}
                      className="w-full rounded-xl border border-slate-300 p-3 text-xs sm:text-sm text-slate-800 leading-relaxed bg-slate-50 focus:bg-white"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-bold text-emerald-800 mb-1">
                      Recommended Next Steps for Client
                    </label>
                    <textarea
                      rows={4}
                      value={recommendations}
                      onChange={(e) => {
                        setRecommendations(e.target.value);
                        setSaveSuccess(false);
                      }}
                      className="w-full rounded-xl border border-emerald-300 p-3 text-xs sm:text-sm text-emerald-950 leading-relaxed bg-emerald-50/40 focus:bg-white"
                    />
                  </div>
                </div>

                <div className="no-print flex items-center justify-end gap-3">
                  {saveSuccess && (
                    <span className="text-xs font-bold text-emerald-700 flex items-center gap-1">
                      <CheckCircle2 className="w-4 h-4" /> Changes & GIS Trace Saved!
                    </span>
                  )}
                  <button
                    type="button"
                    onClick={handleSaveChanges}
                    disabled={savingEdits}
                    className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-slate-900 hover:bg-slate-800 text-white text-xs font-bold transition"
                  >
                    <Save className="w-3.5 h-3.5 text-honey-400" />
                    {savingEdits ? "Saving..." : "Save Report & Trace Adjustments"}
                  </button>
                </div>
              </div>

              {/* Section 4: Geo-Located Photo Evidence Grid */}
              <div className="space-y-3">
                <h2 className="text-base font-black text-slate-900 border-b-2 border-honey-500 pb-1.5">
                  4. Geo-Located Photographic Evidence ({photos.length} GPS Pins)
                </h2>
                <div className="grid sm:grid-cols-2 gap-4">
                  {photos.map((photo, idx) => (
                    <div
                      key={photo.id || idx}
                      className="print-break-inside-avoid rounded-xl border border-slate-200 overflow-hidden bg-slate-50 shadow-sm"
                    >
                      <div className="relative h-48 bg-slate-900">
                        <img
                          src={photo.imageUrl}
                          alt={photo.caption}
                          className="w-full h-full object-cover"
                        />
                        <div className="absolute top-2.5 left-2.5 px-2.5 py-1 rounded-md bg-honey-500 text-hive-950 font-black text-xs shadow">
                          Waypoint #{photo.sequenceOrder || idx + 1}
                        </div>
                        <div className="absolute bottom-2 right-2 px-2.5 py-1 rounded bg-black/80 text-white font-mono text-[11px]">
                          {photo.latitude.toFixed(5)}, {photo.longitude.toFixed(5)}
                        </div>
                      </div>
                      <div className="p-3.5 space-y-1">
                        <div className="text-[10px] font-extrabold uppercase text-amber-700">
                          {photo.tagCategory} • {photo.gpsSource}
                        </div>
                        <div className="text-xs font-bold text-slate-900">{photo.caption}</div>
                        <div className="text-[11px] text-slate-500 flex items-center justify-between pt-1">
                          <span>
                            Captured:{" "}
                            {new Date(photo.capturedAt).toLocaleString("en-KE", {
                              dateStyle: "medium",
                              timeStyle: "short",
                            })}
                          </span>
                          {photo.altitude && <span>Alt: {photo.altitude}m</span>}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* Official Report Footer */}
              <div className="border-t border-slate-200 pt-4 text-xs text-slate-500 flex flex-wrap items-center justify-between gap-2">
                <div>
                  <strong>Davally Apiculture Limited</strong> • Tala Town, Machakos County • Reg No:
                  BN-79S6OBMR
                </div>
                <div>
                  M-Pesa Till: <strong>1801420</strong> • Contacts: 0708 701 569 / 0722 260 670
                </div>
              </div>
            </div>
          </div>

          {/* Right 4 Columns: Client Email Dispatch Panel (Hidden when printing PDF) */}
          <div className="no-print lg:col-span-4 space-y-5 sticky top-20">
            <div className="bg-hive-950 text-white rounded-2xl p-6 border-2 border-honey-500 shadow-xl space-y-4">
              <div className="flex items-center gap-2.5">
                <div className="w-10 h-10 rounded-xl bg-honey-500 text-hive-950 flex items-center justify-center shrink-0">
                  <Mail className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="font-black text-base text-white">
                    Email Report to Client
                  </h3>
                  <p className="text-xs text-slate-400">
                    Sends HTML report, GPS table & interactive map link
                  </p>
                </div>
              </div>

              {currentUser?.role === "ADMIN" ? (
                <form onSubmit={handleSendEmailToClient} className="space-y-3.5 text-xs">
                  <div>
                    <label className="block font-bold text-slate-300 mb-1">
                      Client Recipient Email *
                    </label>
                    <input
                      type="email"
                      required
                      value={toEmail}
                      onChange={(e) => setToEmail(e.target.value)}
                      placeholder="client@organization.co.ke"
                      className="w-full rounded-xl bg-hive-900 border border-slate-700 px-3.5 py-2.5 text-white font-semibold focus:border-honey-500 focus:outline-none"
                    />
                  </div>

                  <div>
                    <label className="block font-bold text-slate-300 mb-1">
                      CC Email (Optional — e.g. david.kyalo@muajiri.com)
                    </label>
                    <input
                      type="email"
                      value={ccEmail}
                      onChange={(e) => setCcEmail(e.target.value)}
                      placeholder="david.kyalo@muajiri.com"
                      className="w-full rounded-xl bg-hive-900 border border-slate-700 px-3.5 py-2 text-white focus:border-honey-500 focus:outline-none"
                    />
                  </div>

                  <div>
                    <label className="block font-bold text-slate-300 mb-1">
                      Cover Note to {report.client?.contactPerson || "Client"} (Optional)
                    </label>
                    <textarea
                      rows={3}
                      value={customMessage}
                      onChange={(e) => setCustomMessage(e.target.value)}
                      placeholder="Dear client, attached is the geo-verified inspection & boundary trace from our visit today..."
                      className="w-full rounded-xl bg-hive-900 border border-slate-700 px-3.5 py-2 text-white focus:border-honey-500 focus:outline-none"
                    />
                  </div>

                  <button
                    type="submit"
                    disabled={sendingEmail}
                    className="w-full py-3.5 rounded-xl bg-honey-500 hover:bg-honey-400 text-hive-950 font-black text-sm flex items-center justify-center gap-2 shadow-lg shadow-honey-500/20 transition"
                  >
                    <Send className="w-4 h-4" />
                    {sendingEmail
                      ? "Dispatching Branded Email..."
                      : "Approve & Send Report to Client Email"}
                  </button>
                </form>
              ) : (
                <div className="bg-white/5 border border-white/10 rounded-xl p-4 text-xs text-slate-300 space-y-2">
                  <div className="font-extrabold text-honey-400 uppercase">
                    Admin Approval Required
                  </div>
                  <p className="leading-relaxed">
                    You are signed in with the <strong>TECHNICIAN</strong> role (
                    {currentUser?.name}). You can adjust the GIS trace and field notes on this
                    report, and an <strong>ADMIN</strong> (Mr. David or Mr. Maveke) will review and
                    dispatch the official email to <strong>{report.client?.email}</strong>.
                  </p>
                </div>
              )}

              {emailDispatchResult && (
                <div className="bg-emerald-950/90 border border-emerald-500/40 rounded-xl p-4 space-y-2.5 text-xs">
                  <div className="flex items-center gap-2 text-emerald-300 font-extrabold">
                    <CheckCircle2 className="w-4 h-4 shrink-0" />
                    <span>Report Dispatched to {emailDispatchResult.sentTo}!</span>
                  </div>
                  <p className="text-slate-300 text-[11px] leading-relaxed">
                    Delivery Mode: <strong className="text-white">{emailDispatchResult.mode}</strong>
                    {emailDispatchResult.mode === "ETHEREAL_SANDBOX"
                      ? " (Local SMTP Sandbox preview generated below — add SMTP_PASS in .env for live inbox delivery)."
                      : ""}
                  </p>
                  <div className="flex flex-col gap-2 pt-1">
                    {emailDispatchResult.previewUrl && (
                      <a
                        href={emailDispatchResult.previewUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-emerald-500 text-hive-950 font-black text-xs hover:bg-emerald-400"
                      >
                        <Sparkles className="w-3.5 h-3.5" />
                        Open Sent Email Preview
                        <ExternalLink className="w-3.5 h-3.5" />
                      </a>
                    )}
                    <Link
                      href={`/reports/share/${report.shareToken}`}
                      target="_blank"
                      className="inline-flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg bg-white/10 text-white font-bold text-xs hover:bg-white/20"
                    >
                      View Client Interactive Map Link
                      <ExternalLink className="w-3.5 h-3.5" />
                    </Link>
                  </div>
                </div>
              )}
            </div>

            {/* Quick Share Card */}
            <div className="bg-white rounded-2xl p-5 border border-slate-200 shadow-sm space-y-3">
              <div className="text-xs font-extrabold uppercase text-slate-500">
                Passwordless Client Share Link
              </div>
              <p className="text-xs text-slate-600 leading-relaxed">
                This link is embedded inside the client&apos;s email so they can explore the traced
                satellite map and print their PDF report anytime without needing an ERP login:
              </p>
              <div className="p-2.5 rounded-lg bg-slate-100 font-mono text-[11px] text-slate-800 break-all border border-slate-200">
                {shareUrl}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
