"use client";

import { useEffect, useRef, useState } from "react";

type Props = {
  employeeName: string;
  employeeCode: string;
  policy: { name: string; description: string } | null;
  policyAcknowledged: boolean;
  activeWorkSession: { state: string } | null;
  activeEmergency: boolean;
};

function getDeviceUid(): string {
  try {
    const existing = localStorage.getItem("kj_device_uid");
    if (existing) return existing;
    const uid = crypto.randomUUID();
    localStorage.setItem("kj_device_uid", uid);
    return uid;
  } catch {
    return crypto.randomUUID();
  }
}

export default function EmployeePortal(props: Props) {
  const [acknowledged, setAcknowledged] = useState(props.policyAcknowledged);
  const [workState, setWorkState] = useState(props.activeWorkSession?.state ?? null);
  const [tracking, setTracking] = useState(false);
  const [lastSync, setLastSync] = useState<Date | null>(null);
  const [battery, setBattery] = useState<number | null>(null);
  const [online, setOnline] = useState(true);
  const [sosSent, setSosSent] = useState(props.activeEmergency);
  const [busy, setBusy] = useState(false);

  const deviceUidRef = useRef<string>("");
  const watchIdRef = useRef<number | null>(null);
  const trackingSessionIdRef = useRef<string>("");

  useEffect(() => {
    deviceUidRef.current = getDeviceUid();
    fetch("/api/devices/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        deviceUid: deviceUidRef.current,
        model: navigator.platform,
        osVersion: navigator.userAgent.slice(0, 80),
        appVersion: "web-1.0",
      }),
    }).catch(() => {});

    setOnline(navigator.onLine);
    const onOnline = () => setOnline(true);
    const onOffline = () => setOnline(false);
    window.addEventListener("online", onOnline);
    window.addEventListener("offline", onOffline);

    const nav = navigator as Navigator & { getBattery?: () => Promise<{ level: number; addEventListener: (e: string, cb: () => void) => void }> };
    if (nav.getBattery) {
      nav.getBattery().then((b) => {
        setBattery(Math.round(b.level * 100));
        b.addEventListener("levelchange", () => setBattery(Math.round(b.level * 100)));
      });
    }

    return () => {
      window.removeEventListener("online", onOnline);
      window.removeEventListener("offline", onOffline);
    };
  }, []);

  async function acknowledgePolicy() {
    setBusy(true);
    try {
      await fetch("/api/employees/policy-ack", { method: "POST" });
      setAcknowledged(true);
    } finally {
      setBusy(false);
    }
  }

  function startTracking() {
    if (!("geolocation" in navigator)) return;
    trackingSessionIdRef.current = crypto.randomUUID();
    const id = navigator.geolocation.watchPosition(
      (pos) => {
        setLastSync(new Date());
        fetch("/api/location", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            deviceUid: deviceUidRef.current,
            latitude: pos.coords.latitude,
            longitude: pos.coords.longitude,
            accuracy: pos.coords.accuracy,
            speed: pos.coords.speed,
            heading: pos.coords.heading,
            trackingSessionId: trackingSessionIdRef.current,
            clientRecordId: crypto.randomUUID(),
            batteryLevel: battery,
            networkState: navigator.onLine ? "online" : "offline",
          }),
        }).catch(() => {});
      },
      () => {},
      { enableHighAccuracy: true, maximumAge: 5000, timeout: 20000 }
    );
    watchIdRef.current = id;
    setTracking(true);
  }

  function stopTracking() {
    if (watchIdRef.current != null) navigator.geolocation.clearWatch(watchIdRef.current);
    watchIdRef.current = null;
    setTracking(false);
  }

  async function attendanceAction(eventType: "START_WORK" | "BREAK_START" | "BREAK_END" | "END_WORK") {
    setBusy(true);
    try {
      const pos = await new Promise<GeolocationPosition | null>((resolve) =>
        navigator.geolocation
          ? navigator.geolocation.getCurrentPosition((p) => resolve(p), () => resolve(null), { timeout: 8000 })
          : resolve(null)
      );
      const res = await fetch("/api/attendance", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          eventType,
          latitude: pos?.coords.latitude,
          longitude: pos?.coords.longitude,
        }),
      });
      if (res.ok) {
        if (eventType === "START_WORK") {
          setWorkState("WORKING");
          startTracking();
        } else if (eventType === "BREAK_START") {
          setWorkState("ON_BREAK");
        } else if (eventType === "BREAK_END") {
          setWorkState("WORKING");
        } else {
          setWorkState(null);
          stopTracking();
        }
      }
    } finally {
      setBusy(false);
    }
  }

  async function triggerSos() {
    if (!confirm("Send an emergency SOS alert to security/HR now?")) return;
    setBusy(true);
    try {
      const pos = await new Promise<GeolocationPosition | null>((resolve) =>
        navigator.geolocation
          ? navigator.geolocation.getCurrentPosition((p) => resolve(p), () => resolve(null), { timeout: 8000 })
          : resolve(null)
      );
      const res = await fetch("/api/emergency", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ latitude: pos?.coords.latitude, longitude: pos?.coords.longitude }),
      });
      if (res.ok) setSosSent(true);
    } finally {
      setBusy(false);
    }
  }

  if (props.policy && !acknowledged) {
    return (
      <div className="rounded-xl border border-slate-800 bg-slate-900 p-6">
        <h1 className="text-lg font-semibold mb-2">Corporate Monitoring Policy</h1>
        <p className="text-sm text-slate-300 mb-3">{props.policy.description}</p>
        <ul className="text-xs text-slate-400 list-disc pl-4 mb-4 space-y-1">
          <li>Location is only tracked while you are in an active work session.</li>
          <li>Device battery and network status are shared to confirm device health.</li>
          <li>You can see your monitoring status at all times on this screen.</li>
        </ul>
        <button
          onClick={acknowledgePolicy}
          disabled={busy}
          className="w-full rounded-md bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white text-sm font-medium py-2"
        >
          I understand and acknowledge
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="rounded-xl border border-slate-800 bg-slate-900 p-5">
        <div className="text-sm text-slate-400">{props.employeeCode}</div>
        <div className="text-xl font-semibold">{props.employeeName}</div>
        <div className="mt-3 text-sm">
          {workState === "WORKING" && <span className="text-emerald-400">WORKING</span>}
          {workState === "ON_BREAK" && <span className="text-amber-400">ON BREAK</span>}
          {!workState && <span className="text-slate-500">NOT IN SESSION</span>}
        </div>
        <div className="mt-1 text-sm">
          {tracking ? (
            <span className="text-emerald-400">🟢 Location Tracking Active</span>
          ) : (
            <span className="text-slate-500">⚪ Location Tracking Inactive</span>
          )}
        </div>
      </div>

      <div className="rounded-xl border border-slate-800 bg-slate-900 p-5 grid grid-cols-2 gap-3 text-sm">
        <div>
          <div className="text-xs text-slate-500">Device</div>
          <div className={online ? "text-emerald-400" : "text-red-400"}>{online ? "Online" : "Offline"}</div>
        </div>
        <div>
          <div className="text-xs text-slate-500">Battery</div>
          <div>{battery != null ? `${battery}%` : "—"}</div>
        </div>
        <div className="col-span-2">
          <div className="text-xs text-slate-500">Last synchronization</div>
          <div>{lastSync ? lastSync.toLocaleTimeString() : "Not yet synced"}</div>
        </div>
      </div>

      <div className="rounded-xl border border-slate-800 bg-slate-900 p-5 space-y-2">
        {!workState && (
          <button
            disabled={busy}
            onClick={() => attendanceAction("START_WORK")}
            className="w-full rounded-md bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-sm font-medium py-2"
          >
            Start Work
          </button>
        )}
        {workState === "WORKING" && (
          <>
            <button
              disabled={busy}
              onClick={() => attendanceAction("BREAK_START")}
              className="w-full rounded-md bg-amber-600 hover:bg-amber-500 disabled:opacity-50 text-white text-sm font-medium py-2"
            >
              Start Break
            </button>
            <button
              disabled={busy}
              onClick={() => attendanceAction("END_WORK")}
              className="w-full rounded-md bg-slate-700 hover:bg-slate-600 disabled:opacity-50 text-white text-sm font-medium py-2"
            >
              End Work
            </button>
          </>
        )}
        {workState === "ON_BREAK" && (
          <button
            disabled={busy}
            onClick={() => attendanceAction("BREAK_END")}
            className="w-full rounded-md bg-emerald-600 hover:bg-emerald-500 disabled:opacity-50 text-white text-sm font-medium py-2"
          >
            Resume Work
          </button>
        )}
      </div>

      <button
        onClick={triggerSos}
        disabled={busy || sosSent}
        className="w-full rounded-md bg-red-600 hover:bg-red-500 disabled:opacity-60 text-white font-semibold py-3 text-sm"
      >
        {sosSent ? "🚨 SOS SENT — security notified" : "🚨 SOS — Emergency"}
      </button>
    </div>
  );
}
