import React, { useEffect, useState } from "react";
import { Navigate } from "react-router-dom";
import { ThemeProvider } from "@/components/dashboard/theme/ThemeProvider";
import LockButton from "@/components/dashboard/LockButton";
import PinProtection from "@/components/dashboard/PinProtection";
import DateTimeWeatherDisplay from "@/components/dashboard/DateTime";
import MiniStatCards from "@/components/dashboard/MiniStatCards";
import MiniSalesChart from "@/components/dashboard/MiniSalesChart";
import MiniEventFeed from "@/components/dashboard/MiniEventFeed";
// @ts-expect-error - JSX component without type declarations
import MiniBusinessMetrics from "@/components/dashboard/MiniBusinessMetrics";
// @ts-expect-error - JSX component without type declarations
import MiniInventorySnapshot from "@/components/dashboard/MiniInventorySnapshot";
import PageLoading from "@/components/ui/page-loading";
import { apiFetch } from "@/utils/api";

// Pin Protected Layout
const PinProtectedLayout = ({ children }: { children: React.ReactNode }) => {
  const [isPinVerified, setIsPinVerified] = useState(() => {
    return sessionStorage.getItem("pinVerified") === "true";
  });

  const handlePinSuccess = () => {
    setIsPinVerified(true);
    sessionStorage.setItem("pinVerified", "true");
  };

  if (!isPinVerified) {
    return <PinProtection onSuccess={handlePinSuccess} />;
  }

  return <>{children}</>;
};

// Three-way gate: office IP gets PIN, authenticated users skip PIN,
// everyone else is bounced to login. Identity comes from /api/dashboard/whoami,
// which sits behind Caddy's office-IP allowlist for the kiosk case.
type Identity = "probing" | "kiosk" | "authenticated" | "anonymous";

const AccessGate = ({ children }: { children: React.ReactNode }) => {
  const [identity, setIdentity] = useState<Identity>("probing");

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await apiFetch("/api/dashboard/whoami");
        if (cancelled) return;
        if (res.status === 401) {
          setIdentity("anonymous");
          return;
        }
        const body = await res.json();
        setIdentity(body.is_kiosk ? "kiosk" : "authenticated");
      } catch {
        if (!cancelled) setIdentity("anonymous");
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  if (identity === "probing") return <PageLoading />;
  if (identity === "anonymous") return <Navigate to="/login?redirect=/small" replace />;
  if (identity === "kiosk") return <PinProtectedLayout>{children}</PinProtectedLayout>;
  return <>{children}</>;
};

// Small Layout
const SmallLayout = () => {
  const DATETIME_SCALE = 2;
  const STATS_SCALE = 1.65;
  const PANELS_SCALE = 1.65;
  const SALES_SCALE = 1.65;
  const FEED_SCALE = 1.65;

  return (
    <div className="min-h-screen w-screen relative bg-gradient-to-br from-slate-950 via-slate-900 to-indigo-950 overflow-hidden">
      {/* Subtle ambient glow spots */}
      <div className="absolute top-0 left-1/4 w-[600px] h-[600px] bg-indigo-500/[0.07] rounded-full blur-[120px] pointer-events-none" />
      <div className="absolute bottom-1/4 right-0 w-[500px] h-[500px] bg-sky-500/[0.05] rounded-full blur-[100px] pointer-events-none" />

      <span className="absolute top-4 left-4 z-50">
        <LockButton />
      </span>

      <div className="p-4 grid grid-cols-12 gap-4 relative z-10">
        {/* DateTime */}
        <div className="col-span-3">
          <div style={{ 
            transform: `scale(${DATETIME_SCALE})`,
            transformOrigin: 'top left',
            width: `${100/DATETIME_SCALE}%`
          }}>
            <DateTimeWeatherDisplay scaleFactor={DATETIME_SCALE} />
          </div>
        </div>

        {/* Stats and Analytics */}
        <div className="col-span-9">
          <div className="">
            {/* Mini Stat Cards */}
            <div>
              <div style={{ 
                transform: `scale(${STATS_SCALE})`,
                transformOrigin: 'top left',
                width: `${100/STATS_SCALE}%`
              }}>
                <MiniStatCards 
                  title="Live Stats"
                  timeRange="today"
                />
              </div>
            </div>

            {/* Mini Charts Grid */}
            <div className="grid grid-cols-2 gap-4 mt-28">
              {/* Mini Sales Chart */}
              <div>
                <div style={{ 
                  transform: `scale(${SALES_SCALE})`,
                  transformOrigin: 'top left',
                  width: `${100/SALES_SCALE}%`
                }}>
                  <MiniSalesChart />
                </div>
              </div>

              {/* Operations + Inventory Panels */}
              <div className="h-full">
                <div className="h-full" style={{
                  transform: `scale(${PANELS_SCALE})`,
                  transformOrigin: 'top left',
                  width: `${100/PANELS_SCALE}%`,
                  height: '100%',
                }}>
                  <div className="flex gap-2 h-full">
                    <div className="flex-1 min-w-0 h-full">
                      <MiniBusinessMetrics />
                    </div>
                    <div className="flex-1 min-w-0 h-full">
                      <MiniInventorySnapshot />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Event Feed at bottom */}
      <div className="absolute bottom-0 left-0 right-0 z-10">
        <div style={{
          transform: `scale(${FEED_SCALE})`,
          transformOrigin: 'bottom center',
          width: `${100/FEED_SCALE}%`,
          margin: '0 auto'
        }}>
          <MiniEventFeed />
        </div>
      </div>
    </div>
  );
};

export function SmallDashboard() {
  return (
    <ThemeProvider>
      <AccessGate>
        <SmallLayout />
      </AccessGate>
    </ThemeProvider>
  );
}

export default SmallDashboard; 