"use client";

import { useEffect, useRef, useState } from "react";
import ModelCard from "./ModelCard";
import Box from "@mui/material/Box";
import styles from "./ModelCard.module.css";
import { CircularProgress, Grid, Dialog, Typography } from "@mui/material";
import Model3DViewer from "./GoogleViewer/Model3DViewer";
import CategoryFilter from "./CategoryFilter";

type Hotspots = {
  id: string;
  color?: string;
  title: string;
  normal: string;
  position: string;
  description?: string | null;
};

export type Models = {
  id: number;
  title: string;
  description: string;
  speachtext?: string;
  image: string;
  modelSrc: string;
  category: string;
  program?: string;
  size?: string;
  date?: string;
  stackCount?: number;
  tag?: string | null;
  createdAt?: string;
  updatedAt?: string;
  hotspots: Hotspots[];
};

// type PendingHit = { position: string; normal: string } | null;

const ModelGrid: React.FC = () => {
  // const [adminMode, setAdminMode] = useState<boolean>(false);
  // const [pendingHit, setPendingHit] = useState<PendingHit>(null);
  // const [activeLabelId, setActiveLabelId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [models, setModels] = useState<Models[]>([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [selectedModel, setSelectedModel] = useState<Models | null>(null);
  const [openModel, setOpenModel] = useState(false);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);

  // Sentinel ref for Intersection Observer
  const loaderRef = useRef<HTMLDivElement | null>(null);

  const categories = Array.from(new Set(models.map((m) => m.category))).sort();

  const fetchModels = async (pageNum: number) => {
    setLoading(true);
    try {
      const res = await fetch(`/api/models?page=${pageNum}&limit=50`);
      const data = await res.json();
      setModels((prev) => [...prev, ...data.data]);
      setHasMore(data.hasMore);
    } catch (error) {
      console.error("Failed to fetch models:", error);
    } finally {
      setLoading(false);
    }
  };

  // Initial fetch
  useEffect(() => {
    fetchModels(1);
  }, []);

  // Fetch when page changes (but skip page 1 since initial fetch handles it)
  useEffect(() => {
    if (page === 1) return;
    fetchModels(page);
  }, [page]);

  // Intersection Observer — triggers load more when sentinel is visible
  useEffect(() => {
    const observer = new IntersectionObserver(
      (entries) => {
        if (entries[0].isIntersecting && hasMore && !loading) {
          setPage((prev) => prev + 1);
        }
      },
      { threshold: 0.1 } // lowered from 1.0 to 0.1 — triggers earlier
    );

    const currentLoader = loaderRef.current;
    if (currentLoader) observer.observe(currentLoader);

    return () => {
      if (currentLoader) observer.unobserve(currentLoader);
    };
  }, [hasMore, loading]);

  if (loading && models.length === 0) {
    return (
      <Box sx={{ display: "flex", justifyContent: "center", alignItems: "center", height: "400px" }}>
        <CircularProgress />
      </Box>
    );
  }

  return (
    <section className={styles.container}>
      {openModel && (
        <Dialog fullScreen open={openModel} onClose={() => setOpenModel(false)} maxWidth="lg" fullWidth>
          <Model3DViewer
            src={selectedModel?.modelSrc ? `/assets/${selectedModel.modelSrc}` : ""}
            hotspots={selectedModel?.hotspots || []}
            speachtext={selectedModel?.speachtext}
            title={selectedModel?.title}
            onClose={() => {
              setOpenModel(false);
            }}
          />
        </Dialog>
      )}

      {!openModel && (
        <div className="models-list">
          <Box
            sx={{
              display: "flex",
              flexDirection: { xs: "column", sm: "row" },
              alignItems: { xs: "stretch", sm: "center" },
              justifyContent: "space-between",
              gap: 2,
              mb: 2,
            }}
          >
            <Typography variant="h4" component="h2" sx={{ fontWeight: 700, color:"#171717" }}>
              Available Models
            </Typography>
            <CategoryFilter
              categories={categories}
              selected={selectedCategories}
              onChange={setSelectedCategories}
            />
          </Box>

          <Grid container spacing={{ xs: 2, sm: 2, md: 3 }} sx={{ mt: 2, mb: 4 }}>
            {models
              .filter((m) => selectedCategories.length === 0 || selectedCategories.includes(m.category))
              .map((model) => (
                <Grid key={model.id} size={{ xs: 12, sm: 6, md: 4, lg: 3 }}>
                  <ModelCard
                    model={model}
                    onSelect={() => {
                      setSelectedModel(model);
                      setOpenModel(true);
                    }}
                  />
                </Grid>
              ))}
          </Grid>

          {/* Sentinel element — triggers load more when scrolled into view */}
          <div ref={loaderRef} style={{ height: 1, marginTop: 100 }} />

          {/* Loading spinner for subsequent pages */}
          {loading && models.length > 0 && (
            <Box sx={{ display: "flex", justifyContent: "center", py: 2 }}>
              <CircularProgress size={28} />
            </Box>
          )}

          {/* End of list message */}
          {/* {!hasMore && models.length > 0 && (
            <Box sx={{ textAlign: "center", py: 2 }}>
              <Typography variant="body2" color="text.secondary">
                All models loaded
              </Typography>
            </Box>
          )} */}
        </div>
      )}
    </section>
  );
};

export default ModelGrid;