"use client";

import React, { useCallback, useEffect, useRef, useState } from "react";
import type { Hotspot } from "./types";
import './Model3DViewer.model.css'
import type { ModelViewerElement } from "@google/model-viewer";
import { Alert, Box, Button, Chip, Paper, Snackbar, Stack, Switch, TextField, Typography } from "@mui/material";

interface Model3DViewerProps {
  src: string;
  modelId: number;
  alt?: string;
  title?: string;
  speachtext?: string;
  hotspots?: Hotspot[];
  autoRotate?: boolean;
  cameraControls?: boolean;
  style?: React.CSSProperties;
  onClose?: () => void;
  onHotspotsChange?: (hotspots: Hotspot[]) => void;
}

type HitPoint = {
  position: string;
  normal: string;
};


const EditModel3DViewer: React.FC<Model3DViewerProps> = ({
  src,
  alt = "3D model",
  hotspots = [],
  style,
  onClose,
  onHotspotsChange,
}) => {
  const modelRef = useRef<ModelViewerElement | null>(null);

  const [viewerHotspots, setViewerHotspots] = useState<Hotspot[]>(hotspots);
  const [activeHotspot, setActiveHotspot] = useState<string | null>(null);
  const [selectedHotspotId, setSelectedHotspotId] = useState<string | null>(null);
  const [pendingHit, setPendingHit] = useState<HitPoint | null>(null);
  const [hotspotTitle, setHotspotTitle] = useState("");
  const [hotspotDescription, setHotspotDescription] = useState("");
  const [isRendered, setIsRendered] = useState(false);
  const [cameraControls, setCameraControls] = useState(true);

  // Snackbar state
  const [snack, setSnack] = useState<{ open: boolean; message: string; severity: "success" | "error" }>({
    open: false,
    message: "",
    severity: "success",
  });

  const showSnack = (message: string, severity: "success" | "error" = "success") => {
    setSnack({ open: true, message, severity });
  };

  const closeSnack = () => {
    setSnack((prev) => ({ ...prev, open: false }));
  };

  const selectedHotspot = viewerHotspots.find((hotspot) => hotspot.id === selectedHotspotId) || null;

  // Dynamically import @google/model-viewer on client-side only
  useEffect(() => {
    import("@google/model-viewer").catch((err) => console.error("Failed to load model-viewer:", err));
  }, []);

  useEffect(() => {
    setViewerHotspots(hotspots);
  }, [hotspots]);

  useEffect(() => {
    if (!selectedHotspot) {
      return;
    }

    setHotspotTitle(selectedHotspot.title || "");
    setHotspotDescription(selectedHotspot.description || "");
  }, [selectedHotspot]);

  useEffect(() => {
    const model = modelRef.current;
    if (!model) return;

    // Fires when model finishes loading
    const handleLoad = () => {
      // Wait for next frame to ensure render
      requestAnimationFrame(() => {
        setIsRendered(true);
      });
    };

    model.addEventListener("load", handleLoad);

    return () => {
      model.removeEventListener("load", handleLoad);
    };
  }, []);

  const publishHotspots = (nextHotspots: Hotspot[]) => {
    setViewerHotspots(nextHotspots);
    onHotspotsChange?.(nextHotspots);
  };

  const handleModelClick = useCallback((event: Event) => {
    if (cameraControls) {
      return;
    }

    const model = modelRef.current;
    if (!model) return;

    const mouseEvent = event as MouseEvent;
    const rect = model.getBoundingClientRect();
    const x = mouseEvent.clientX - rect.left;
    const y = mouseEvent.clientY - rect.top;

    const hit = model.positionAndNormalFromPoint(x, y);
    if (!hit) {
      return;
    }
    
    setPendingHit({
      position: hit.position.toString(),
      normal: hit.normal.toString(),
    });
    setSelectedHotspotId(null);
    setActiveHotspot(null);
    setHotspotTitle("");
    setCameraControls(true);
  }, [cameraControls]);

  useEffect(() => {
    const model = modelRef.current;
    if (!model) return;

    model.addEventListener("click", handleModelClick);

    return () => {
      model.removeEventListener("click", handleModelClick);
    };
  }, [handleModelClick]);

  const startEditHotspot = (hotspot: Hotspot) => {
    setSelectedHotspotId(hotspot.id);
    setPendingHit(null);
    setActiveHotspot(hotspot.id);
  };

  const handleSaveHotspot = () => {
    const normalizedTitle = hotspotTitle.trim();
    if (!normalizedTitle) {
      showSnack("Please enter a hotspot title.", "error");
      return;
    }

    if (selectedHotspotId) {
      const updated = viewerHotspots.map((hotspot) => {
        if (hotspot.id !== selectedHotspotId) {
          return hotspot;
        }

        return {
          ...hotspot,
          title: normalizedTitle,
          description: hotspotDescription.trim() || null,
        };
      });

      publishHotspots(updated);
      setActiveHotspot(selectedHotspotId);
      showSnack(`Hotspot "${normalizedTitle}" updated successfully.`);
      return;
    }

    if (!pendingHit) {
      return;
    }

    const newHotspot: Hotspot = {
      id: `new-${Date.now()}`,
      title: normalizedTitle,
      description: hotspotDescription.trim() || null,
      position: pendingHit.position,
      normal: pendingHit.normal,
    };

    const updated = [newHotspot, ...viewerHotspots];
    publishHotspots(updated);
    showSnack(`Hotspot "${normalizedTitle}" added successfully.`);

    // Clear form after successful add and reset to "add new" mode
    setPendingHit(null);
    setSelectedHotspotId(null);
    setActiveHotspot(null);
    setHotspotTitle("");
    setHotspotDescription("");
  };

  const handleDeleteHotspot = () => {
    if (!selectedHotspotId) {
      return;
    }

    const deletedTitle = viewerHotspots.find((h) => h.id === selectedHotspotId)?.title || "Hotspot";
    const updated = viewerHotspots.filter((hotspot) => hotspot.id !== selectedHotspotId);
    publishHotspots(updated);
    setSelectedHotspotId(null);
    setActiveHotspot(null);
    setHotspotTitle("");
    showSnack(`Hotspot "${deletedTitle}" deleted successfully.`, "success");
  };

  const handleClearPending = () => {
    setPendingHit(null);
    setHotspotTitle("");
  };

  const isEditing = Boolean(selectedHotspotId);
  const canSave = hotspotTitle.trim().length > 0 && (isEditing || Boolean(pendingHit));

  return (
    <>
      <Box
        sx={{
          display: "flex",
          flexDirection: { xs: "column", md: "row" },
          gap: 2,
          width: "100%",
          height: "100%",
        }}
      >
        <Box
          style={{ position: "relative", width: "100%", height: "100%", background:"#0a0e1a", ...style }}
          sx={{
            flex: { xs: "0 0 auto", md: "1 1 0" },
            minHeight: { xs: 420, md: 560 },
          }}
        >
          {!isRendered && (
            <div className="loader-overlay">
              <div className="loader">
                <div className="spinner" />
                <p>Loading Preview...</p>
              </div>
            </div>
          )}
          {/* @ts-expect-error custom web component */}
          <model-viewer
            ref={modelRef}
            src={src}
            alt={alt}
            debug-hotspots="true"
            camera-controls={cameraControls}
            interaction-prompt-threshold="0"
            shadow-intensity="0.5"
            shadow-softness="0.5"
            exposure="1"
            environment-image="neutral"
            loading="eager"
            reveal="auto"
            touch-action="pan-y"
            crossorigin="anonymous"
            max-camera-orbit="auto 90deg auto"
            style={{ width: "100%", height: "100%", cursor: cameraControls ? "default" : "crosshair" }}
          >
            <div className="preview-mode">{cameraControls ? "Preview Mode" : "Edit Mode: click on model to add hotspot"}</div>
            <div className="actions">
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, pl: 1, color: "#000", background: '#fff' }}>
                Edit Mode: <Switch
                  checked={!cameraControls}
                  onChange={() => setCameraControls(!cameraControls)}
                  slotProps={{ input: { 'aria-label': 'controlled' } }}
                />
              </Box>
              {!!onClose && (
                <Button variant="contained" color="error" size="small" onClick={onClose} sx={{ ml: 1 }}>
                  Close
                </Button>
              )}
            </div>

            {isRendered && pendingHit && !isEditing && (
              <div
                slot="hotspot-temp"
                data-position={pendingHit.position}
                data-normal={pendingHit.normal}
                className="hotspot-wrapper"
              >
                <div className="hotspot-container">
                  <Chip label="New hotspot" variant="outlined" sx={{ background: "#fff" }} />
                  <div className="hotspot-line" />
                </div>
                <button
                  className="hotspot-dot"
                  style={{ background: "#f59e0b" }}
                  onClick={(event) => event.stopPropagation()}
                />
              </div>
            )}

            {isRendered && viewerHotspots.map((hotspot, index) => {
              const isActive = activeHotspot === hotspot.id;

              return (
                <div
                  key={hotspot.id || index}
                  slot={`hotspot-${hotspot.id || index}`}
                  data-position={hotspot.position}
                  data-normal={hotspot.normal}
                  className="hotspot-wrapper"
                >
                  {isActive && (
                    <div className="hotspot-container">
                      <Chip label={hotspot.title} variant="outlined"
                        onDelete={() => setActiveHotspot(null)}
                        sx={{ background: '#fff' }}
                      />
                      <div className="hotspot-line" />
                    </div>
                  )}

                  <button
                    className="hotspot-dot"
                    onClick={(event) => {
                      event.stopPropagation();
                      setActiveHotspot(isActive ? null : hotspot.id);
                      startEditHotspot(hotspot);
                    }}
                  />
                </div>
              );
            })}
          {/* @ts-expect-error custom web component */}
          </model-viewer>
        </Box>

        <Paper
          elevation={2}
          sx={{
            width: { xs: "100%", md: 360 },
            minWidth: { md: 320 },
            p: 2,
            display: "flex",
            flexDirection: "column",
            gap: 2,
            alignSelf: { xs: "stretch", md: "flex-start" },
          }}
        >
          <Typography variant="h6" sx={{ color: "#171717", fontWeight: 700 }}>
            {isEditing ? "Edit Hotspot" : "Add Hotspot"}
          </Typography>

          {!cameraControls && !isEditing && !pendingHit && (
            <Typography variant="body2" color="text.secondary">
              Click a point on the model to create a hotspot.
            </Typography>
          )}

          {pendingHit && (
            <Typography variant="caption" color="text.secondary">
              New point selected. Fill details and save.
            </Typography>
          )}

          {isEditing && selectedHotspot && (
            <Typography variant="caption" color="text.secondary">
              Editing hotspot: {selectedHotspot.id}
            </Typography>
          )}

          <TextField
            label="Hotspot title"
            value={hotspotTitle}
            onChange={(event) => setHotspotTitle(event.target.value)}
            fullWidth
            size="small"
          />
          <TextField
            label="Position"
            value={
              isEditing && selectedHotspot
                ? selectedHotspot.position
                : pendingHit?.position || ""
            }
            fullWidth
            size="small"
            disabled
            InputProps={{ readOnly: true }}
            variant="outlined"
          />

          <TextField
            label="Normal"
            value={
              isEditing && selectedHotspot
                ? selectedHotspot.normal
                : pendingHit?.normal || ""
            }
            fullWidth
            size="small"
            disabled
            InputProps={{ readOnly: true }}
            variant="outlined"
          />

          <Stack direction={{ xs: "column", sm: "row", md: "column" }} spacing={1}>
            <Button variant="contained" onClick={handleSaveHotspot} disabled={!canSave}>
              {isEditing ? "Update Hotspot" : "Add Hotspot"}
            </Button>

            {isEditing && (
              <Button variant="outlined" color="error" onClick={handleDeleteHotspot}>
                Delete Hotspot
              </Button>
            )}

            {pendingHit && !isEditing && (
              <Button variant="outlined" onClick={handleClearPending}>
                Clear Selection
              </Button>
            )}
          </Stack>
        </Paper>
      </Box>

      {/* Snackbar Notifications */}
      <Snackbar
        open={snack.open}
        autoHideDuration={3000}
        onClose={closeSnack}
        anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      >
        <Alert onClose={closeSnack} severity={snack.severity} variant="filled" sx={{ width: "100%" }}>
          {snack.message}
        </Alert>
      </Snackbar>
    </>
  );
};

export default EditModel3DViewer;
