"use client";

import React, { useEffect, useState, useMemo } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import dynamic from "next/dynamic";
import {
  Printer,
  ShieldCheck,
  MapPin,
  Phone,
  Mail,
  CheckCircle2,
  ArrowLeft,
} 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 Client GIS Map...
    </div>
  ),
});

interface SharedReportDetail {
  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;
  client: {
    name: string;
    contactPerson: string;
    email: string;
    phone: string;
  };
  site: {
    name: string;
    subLocation: string;
    county: string;
  };
  photos: Array<{
    id: string;
    imageUrl: string;
    caption: string;
    tagCategory: string;
    latitude: number;
    longitude: number;
    altitude?: number | null;
    gpsSource: string;
    capturedAt: string;
    sequenceOrder: number;
    includeInTrace: boolean;
  }>;
}

export default function ClientShareReportPage() {
  const params = useParams<{ token: string }>();
  const token = params?.token;

  const [report, setReport] = useState<SharedReportDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!token) return;
    async function load() {
      setLoading(true);
      try {
        const res = await fetch(`/api/activities/${token}`);
        const data = await res.json();
        if (data.activity) {
          setReport(data.activity);
        }
      } catch (err) {
        console.error("Failed to load shared report:", err);
      } finally {
        setLoading(false);
      }
    }
    load();
  }, [token]);

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

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50 text-sm font-semibold text-slate-600">
        Loading Verified Davally Apiculture Client Report...
      </div>
    );
  }

  if (!report) {
    return (
      <div className="min-h-screen flex flex-col items-center justify-center bg-slate-50 p-6 text-center space-y-4">
        <div className="text-xl font-black text-slate-900">
          Client Field Report Not Found
        </div>
        <Link
          href="/"
          className="px-4 py-2 rounded-xl bg-hive-900 text-honey-400 text-xs font-bold"
        >
          Return to Davally Apiculture Website
        </Link>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-100 py-8 px-4 sm:px-6">
      <div className="max-w-5xl mx-auto space-y-6">
        {/* Top Action Bar (Hidden in Print) */}
        <div className="no-print flex flex-wrap items-center justify-between gap-4 bg-white px-5 py-3.5 rounded-2xl border border-slate-200 shadow-sm">
          <div className="flex items-center gap-3">
            <Link
              href="/"
              className="inline-flex items-center gap-1.5 text-xs font-bold text-slate-600 hover:text-slate-900"
            >
              <ArrowLeft className="w-3.5 h-3.5" />
              Davally Website
            </Link>
            <span className="text-slate-300">|</span>
            <span className="inline-flex items-center gap-1.5 text-xs font-bold text-emerald-700">
              <ShieldCheck className="w-4 h-4" />
              GPS & GIS Verified Client Report
            </span>
          </div>

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

        {/* Main Branded Report Sheet */}
        <div className="bg-white rounded-2xl border border-slate-200 shadow-md overflow-hidden">
          <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-16 h-16 rounded-xl bg-white p-1 object-contain"
              />
              <div>
                <div className="text-xs font-extrabold uppercase tracking-widest text-honey-400">
                  Davally Apiculture Limited • Client Field & GIS Report
                </div>
                <h1 className="text-2xl sm:text-3xl font-black mt-0.5">
                  {report.activityType}
                </h1>
                <div className="text-xs sm:text-sm text-slate-300 mt-1">
                  Prepared for: <strong>{report.client?.name}</strong> (
                  {report.client?.contactPerson})
                </div>
              </div>
            </div>

            <div className="text-left sm:text-right text-xs space-y-1 shrink-0 bg-white/5 p-3.5 rounded-xl border border-white/10">
              <div className="font-mono font-black text-honey-400 text-sm">
                Ref: {report.reportCode}
              </div>
              <div className="text-slate-200">
                Visit Date:{" "}
                {new Date(report.visitDate).toLocaleDateString("en-KE", {
                  dateStyle: "medium",
                })}
              </div>
              <div className="text-slate-300">Lead Apiarist: {report.technicianName}</div>
              <div className="text-emerald-400 font-bold flex items-center sm:justify-end gap-1">
                <CheckCircle2 className="w-3.5 h-3.5" /> GIS Coordinates Verified
              </div>
            </div>
          </div>

          <div className="p-6 sm:p-8 space-y-8">
            {/* Key Site & Traced Metrics Summary */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 bg-amber-50/60 p-4 rounded-xl border border-amber-200">
              <div>
                <div className="text-[10px] font-bold uppercase text-amber-900">
                  Apiary / Project Site
                </div>
                <div className="text-sm font-black text-slate-900 mt-0.5">
                  {report.site?.name}
                </div>
                <div className="text-xs text-slate-600">
                  {report.site?.subLocation}, {report.site?.county}
                </div>
              </div>

              <div>
                <div className="text-[10px] font-bold uppercase text-amber-900">
                  Colonised Hives Active
                </div>
                <div className="text-xl font-black text-emerald-700 mt-0.5">
                  {report.colonisedCount} / {report.hivesInspected}
                </div>
                <div className="text-xs text-slate-600">Inspected On-Site</div>
              </div>

              <div>
                <div className="text-[10px] font-bold uppercase text-amber-900">
                  Traced Coverage Area
                </div>
                <div className="text-xl font-black text-slate-900 mt-0.5">
                  {report.traceMode === "POLYGON" && report.calculatedAreaHa > 0
                    ? `${report.calculatedAreaHa} Ha`
                    : "Linear Corridor"}
                </div>
                <div className="text-xs text-slate-600">
                  {report.calculatedAreaSqm > 0
                    ? `${report.calculatedAreaSqm.toLocaleString()} m²`
                    : `${report.photos?.length || 0} GPS Waypoints`}
                </div>
              </div>

              <div>
                <div className="text-[10px] font-bold uppercase text-amber-900">
                  {report.traceMode === "POLYGON"
                    ? "Traced Perimeter"
                    : "Bio-Fence Length"}
                </div>
                <div className="text-xl font-black text-amber-800 mt-0.5">
                  {report.calculatedDistanceM.toLocaleString()} m
                </div>
                <div className="text-xs text-slate-600">GPS Boundary Trace</div>
              </div>
            </div>

            {/* Interactive Satellite Map */}
            <div className="space-y-2.5">
              <h2 className="text-base font-black text-slate-900 flex items-center gap-2">
                <MapPin className="w-4 h-4 text-amber-500" />
                1. Interactive Satellite Map & Traced GPS Boundary
              </h2>
              <p className="text-xs text-slate-500">
                Click any numbered pin on the map below to view the photo and exact GPS coordinates
                captured at that position.
              </p>
              <GeoTraceMap
                waypoints={report.photos || []}
                traceMode={report.traceMode}
                editable={false}
                height="440px"
              />
            </div>

            {/* Dropdown Inspection Table */}
            <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 Apiculture & Biosecurity Inspection Metrics
              </h2>
              <div className="grid sm:grid-cols-2 gap-3">
                {Object.entries(parsedDropdowns).map(([key, val]) => (
                  <div
                    key={key}
                    className="p-3.5 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-sm font-extrabold text-slate-900 mt-1">{val}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Summary & Recommendations */}
            <div className="grid sm:grid-cols-2 gap-4">
              <div className="p-4 rounded-xl bg-slate-50 border border-slate-200 space-y-1.5">
                <div className="text-xs font-extrabold uppercase text-slate-700">
                  3. Executive Field Summary
                </div>
                <p className="text-xs sm:text-sm text-slate-700 leading-relaxed whitespace-pre-line">
                  {report.summaryNotes}
                </p>
              </div>
              <div className="p-4 rounded-xl bg-emerald-50/70 border border-emerald-200 space-y-1.5">
                <div className="text-xs font-extrabold uppercase text-emerald-900">
                  4. Recommended Next Steps
                </div>
                <p className="text-xs sm:text-sm text-emerald-950 leading-relaxed whitespace-pre-line">
                  {report.recommendations}
                </p>
              </div>
            </div>

            {/* 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">
                5. Geo-Located Photographic Evidence ({report.photos?.length || 0} Waypoints)
              </h2>
              <div className="grid sm:grid-cols-2 gap-4">
                {report.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"
                  >
                    <div className="relative h-52 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]">
                        GPS: {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} • Verified via {photo.gpsSource}
                      </div>
                      <div className="text-xs font-bold text-slate-900">{photo.caption}</div>
                      <div className="text-[11px] text-slate-500">
                        Timestamp:{" "}
                        {new Date(photo.capturedAt).toLocaleString("en-KE", {
                          dateStyle: "medium",
                          timeStyle: "short",
                        })}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>

            {/* Corporate Footer */}
            <div className="bg-hive-950 text-slate-300 rounded-xl p-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4 text-xs">
              <div>
                <div className="font-black text-honey-400 text-sm">
                  DAVALLY APICULTURE LIMITED
                </div>
                <div>
                  Tala Town, Machakos County, Kenya • Business Reg No: BN-79S6OBMR
                </div>
                <div>
                  M-Pesa Buy Goods Till No: <strong className="text-white">1801420</strong>
                </div>
              </div>
              <div className="space-y-1">
                <div className="flex items-center gap-2">
                  <Phone className="w-3.5 h-3.5 text-honey-400" />
                  <span>Mr. David: 0708 701 569 | Mr. Maveke: 0722 260 670</span>
                </div>
                <div className="flex items-center gap-2">
                  <Mail className="w-3.5 h-3.5 text-honey-400" />
                  <span>david.kyalo@muajiri.com</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
