import React, { useEffect, useRef, useState } from "react";
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Grid from '@mui/material/Grid';
import Paper from '@mui/material/Paper';
import CircularProgress from '@mui/material/CircularProgress';
import Chip from '@mui/material/Chip';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import TextField from '@mui/material/TextField';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import MapIcon from "@mui/icons-material/Map";
import CloseIcon from "@mui/icons-material/Close";
import { Trans } from "@lingui/macro";
import {
  loadLeaflet,
  gatewayIcon,
  getColoredMarkerIcon,
} from "./mapsLoader";
import axios from "axios";

const STATUS_OPTIONS = ["ONLINE", "OFFLINE", "NEVER_SEEN", "UNKNOWN"];
const CARD_HEIGHT = 220;

const LorawanGatewayTable = ({ refreshCounter = 0, searchTerm = "" }) => {
  const [gateways, setGateways] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selected, setSelected] = useState(null);
  const [saving, setSaving] = useState(false);
  const [mapOpen, setMapOpen] = useState(false);
  const [mapGateway, setMapGateway] = useState(null);
  const [devices, setDevices] = useState([]);
  const [deviceLoading, setDeviceLoading] = useState(false);
  const [mapLoading, setMapLoading] = useState(true);
  const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
  const [confirmDeviceName, setConfirmDeviceName] = useState("");
  const [isDeleting, setIsDeleting] = useState(false); 

  const mapRef = useRef(null);
  const mapInstanceRef = useRef(null);
  const deviceMarkersRef = useRef([]);

  /* Gateways laden */
  useEffect(() => {
    const fetchGateways = async () => {
      setLoading(true);
      try {
        const { data } = await axios.get("/getLorawanGateways");
        setGateways(data);
      } catch (err) {
        console.error("Fehler beim Laden der Gateways:", err);
      }
      setLoading(false);
    };
    fetchGateways();
  }, [refreshCounter]);

  /* Devices für Map laden */
  useEffect(() => {
    if (!mapOpen || !mapGateway) return;
    const fetchDevices = async () => {
      setDeviceLoading(true);
      try {
        const { data } = await axios.get(`/gateways/${mapGateway.gateway_euid}/devices`);
        setDevices(data);
      } catch (err) {
        console.error("Fehler beim Laden der Geräte:", err);
        setDevices([]);
      }
      setDeviceLoading(false);
    };
    fetchDevices();
  }, [mapGateway, mapOpen]);

  useEffect(() => {
    const initMap = async () => {
      if (!mapRef.current || !mapGateway || deviceLoading) return;
      setMapLoading(true);
      const L = await loadLeaflet();
      
      // Vorherige Map und Marker entfernen
      mapInstanceRef.current?.remove();
      deviceMarkersRef.current.forEach((m) => m.remove());
      deviceMarkersRef.current = [];
      
      const lat = parseFloat(mapGateway.latitude) || 52.52;
      const lng = parseFloat(mapGateway.longitude) || 13.405;
      
      const map = L.map(mapRef.current).setView([lat, lng], 10);
  
      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution: "&copy; OpenStreetMap contributors",
      }).addTo(map);
  
      // Markercluster-Gruppe erstellen
      const clusterGroup = L.markerClusterGroup({
        showCoverageOnHover: false,
        maxClusterRadius: 10,
      });
      
      // Gerätemarkierungen hinzufügen
      devices.forEach((dev) => {
        const dx = parseFloat(dev.xcoord);
        const dy = parseFloat(dev.ycoord);
        if (!isNaN(dx) && !isNaN(dy)) {
          const status = getStatusColor(dev.last_seen);
          const marker = L.marker([dy, dx], {
            icon: getColoredMarkerIcon(status),
          }).bindTooltip(
            `<strong>${dev.device_name}</strong><br/>Letzter Datensatz: ${dev.last_seen || '—'}`
          );
          clusterGroup.addLayer(marker);
          deviceMarkersRef.current.push(marker);
        }
      });
  
      map.addLayer(clusterGroup);
  
      // Gateway-Marker mit hoher Z-Ordnung hinzufügen
      const gwMarker = L.marker([lat, lng], {
        icon: gatewayIcon,
        zIndexOffset: 1000,
      }).addTo(map);
      gwMarker.bindTooltip(`<strong>${mapGateway.name}</strong>`);
  
      // View anpassen
      if (deviceMarkersRef.current.length > 0) {
        const group = L.featureGroup([gwMarker, ...deviceMarkersRef.current]);
        map.fitBounds(group.getBounds().pad(0.2));
      }
  
      setTimeout(() => {
        map.invalidateSize();
        setMapLoading(false);
      }, 200);
  
      mapInstanceRef.current = map;
    };
  
    if (mapOpen && mapGateway && !deviceLoading) {
      initMap();
    }
  
    return () => {
      mapInstanceRef.current?.remove();
      mapInstanceRef.current = null;
    };
  }, [mapOpen, mapGateway, deviceLoading]);
  
  const getStatusColor = (ls: string): 'green' | 'orange' | 'red' | 'grey' => {
    if (!ls || ls === "Unknown" || ls === "Unbekannt") return 'grey';
    const diff = (Date.now() - new Date(ls).getTime()) / 36e5;
    if (diff < 24) return 'green';
    if (diff < 168) return 'orange';
    return 'red';
  };
  const handleSave = async () => {
    if (!selected) return;
    setSaving(true);
    try {
      await axios.post("/updateLorawanGateways", selected);
      setGateways((prev) =>
        prev.map((g) => (g.id === selected.id ? { ...selected } : g))
      );
      setSelected(null);
    } catch (err) {
      console.error("Save-Error:", err);
    }
    setSaving(false);
  };

  const filtered = gateways.filter((g) =>
    g.name.toLowerCase().includes(searchTerm.toLowerCase())
  );
  const handleDelete = async () => {
    if (!selected) return;
    setIsDeleting(true);
    try {
      await axios.delete("/deleteLorawanGateway", {
        data: { gateway_euid: selected.gateway_euid },
        headers: {
          "X-CSRF-TOKEN": document.querySelector('meta[name="csrf-token"]').content,
        },
      });
      setGateways((prev) =>
        prev.filter((g) => g.gateway_euid !== selected.gateway_euid)
      );
      setSelected(null);
      setDeleteConfirmOpen(false);
      setConfirmDeviceName("");
    } catch (err) {
      console.error("Fehler beim Löschen:", err);
    }
    setIsDeleting(false);
  };

  return (
    <Box mt={3}>
      <Typography variant="h5" gutterBottom>
        <Trans>Gateways</Trans>
      </Typography>

      {loading ? (
        <Box display="flex" justifyContent="center" my={5}>
          <CircularProgress />
        </Box>
      ) : (
        <Box sx={{ maxHeight: "60vh", overflowY: "auto", pr: 1 }}>
          <Grid container spacing={2}>
            {filtered.map((gw) => (
              <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={gw.id}>
                <Paper
                  elevation={1}
                  sx={{
                    height: CARD_HEIGHT,
                    display: "flex",
                    flexDirection: "column",
                    justifyContent: "space-between",
                    p: 2,
                    borderRadius: 2,
                    transition: "transform .15s, box-shadow .15s",
                    "&:hover": {
                      transform: "translateY(-3px)",
                      boxShadow: 4,
                      cursor: "pointer",
                    },
                  }}
                  onClick={() => setSelected({ ...gw })}
                >
                  <Box>
                    <Typography variant="subtitle1" fontWeight="bold" gutterBottom noWrap>
                      {gw.name}
                    </Typography>
                    <Box display="flex" justifyContent="space-between" alignItems="center" mb={1}>
                      <Chip
                        label={gw.status}
                        color={
                          gw.status === "ONLINE"
                            ? "success"
                            : gw.status === "OFFLINE"
                            ? "error"
                            : "default"
                        }
                        size="small"
                      />
                      <Typography variant="caption" color="text.secondary">
                        {gw.connectedDevices ?? 0} <Trans> verbunden</Trans>
                      </Typography>
                    </Box>
                    <Typography
                      variant="body2"
                      sx={{
                        display: "-webkit-box",
                        WebkitLineClamp: 3,
                        WebkitBoxOrient: "vertical",
                        overflow: "hidden",
                      }}
                    >
                      {gw.description || "—"}
                    </Typography>
                  </Box>
                  <Box display="flex" justifyContent="flex-end" mt={1}>
                    <IconButton
                      size="small"
                      onClick={(e) => {
                        e.stopPropagation();
                        setMapLoading(true);
                        setMapGateway(gw);
                        setMapOpen(true);
                      }}
                    >
                      <MapIcon fontSize="small" />
                    </IconButton>
                  </Box>
                </Paper>
              </Grid>
            ))}
          </Grid>
        </Box>
      )}

      {!loading && filtered.length === 0 && (
        <Typography variant="body2" color="textSecondary" mt={2}>
          <Trans>Keine Gateways gefunden.</Trans>
        </Typography>
      )}

      {/* Dialog für Details */}
{selected && (
  <Dialog
    open
    onClose={() => setSelected(null)}
    PaperProps={{ sx: { width: "50vw", mx: "auto" } }}
  >
    <DialogTitle>
      <Trans>Gateway bearbeiten</Trans>
    </DialogTitle>
    <DialogContent dividers>
      <TextField
        fullWidth
        margin="normal"
        label={<Trans>Name</Trans>}
        value={selected.name}
        onChange={(e) => setSelected((s) => ({ ...s, name: e.target.value }))}
      />
      <TextField
        fullWidth
        multiline
        minRows={3}
        margin="normal"
        label={<Trans>Beschreibung</Trans>}
        value={selected.description || ""}
        onChange={(e) =>
          setSelected((s) => ({ ...s, description: e.target.value }))
        }
      />
      <TextField
        fullWidth
        margin="normal"
        label={<Trans>Longitude</Trans>}
        type="number"
        value={selected.longitude || ""}
        onChange={(e) =>
          setSelected((s) => ({ ...s, longitude: e.target.value }))
        }
      />
      <TextField
        fullWidth
        margin="normal"
        label={<Trans>Latitude</Trans>}
        type="number"
        value={selected.latitude || ""}
        onChange={(e) =>
          setSelected((s) => ({ ...s, longitude: e.target.value }))
        }
      />
        <TextField
          fullWidth
          margin="normal"
          label={<Trans>Altitude/Höhe</Trans>}
          type="number"
          value={selected.altitude || ""}
          onChange={(e) =>
            setSelected((s) => ({ ...s, altitude: e.target.value }))
          }
        />
      <TextField
        fullWidth
        margin="normal"
        label={<Trans>EUID</Trans>}
        value={selected.gateway_euid || ""}
        InputProps={{ readOnly: true }}
      />
    </DialogContent>
    <DialogActions sx={{ justifyContent: "space-between" }}>
      <Button
        color="error"
        onClick={() => setDeleteConfirmOpen(true)}
      >
        <Trans>Löschen</Trans>
      </Button>
      <Box>
        <Button onClick={() => setSelected(null)}>
          <Trans>Abbrechen</Trans>
        </Button>
        <Button variant="contained" disabled={saving} onClick={handleSave}>
          <Trans>Speichern</Trans>
        </Button>
      </Box>
    </DialogActions>

  </Dialog>
  
)}

{/* Dialog für Map */}
{mapOpen && (
  <Dialog
    open
    onClose={() => {
      setMapOpen(false);
      setMapGateway(null);
      setDevices([]);
    }}
    maxWidth="lg"
    fullWidth
    keepMounted
  >
    <DialogContent sx={{ p: 0 }}>
      <Box
        sx={{
          position: 'relative',
          border: '10px solid #e0e0e0',
          borderRadius: 1,
          overflow: 'hidden',
          height: '80vh',
          width: '100%',
        }}
      >
        {/* Close-Button oben rechts */}
        <IconButton
          aria-label="Close map"
          onClick={() => {
            setMapOpen(false);
            setMapGateway(null);
            setDevices([]);
          }}
          size="small"
          sx={{
            position: 'absolute',
            top: 8,
            right: 8,
            zIndex: 1000,
            backgroundColor: 'rgba(255,255,255,0.8)',
            '&:hover': { backgroundColor: 'rgba(255,255,255,1)' },
          }}
        >
          <CloseIcon fontSize="small" />
        </IconButton>

        {/* Leaflet-Map */}
        <Box ref={mapRef} sx={{ height: '100%', width: '100%' }} />

        {/* Loading Overlay */}
        {mapLoading && (
          <Box
            sx={{
              position: 'absolute',
              inset: 0,
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              bgcolor: 'background.paper',
              zIndex: 500,
            }}
          >
            <CircularProgress />
          </Box>
        )}
      </Box>
    </DialogContent>

  </Dialog>
)}
<Dialog open={deleteConfirmOpen} onClose={() => setDeleteConfirmOpen(false)}>
  <DialogTitle><Trans>Gateway entfernen</Trans></DialogTitle>

  <DialogContent>
    <Typography sx={{ mb: 2 }}>
      <Trans>
        Zur Bestätigung der Löschung gib bitte den Gatewaynamen "{selected?.name}"
        unten ein.
      </Trans>
    </Typography>

    <TextField
      fullWidth
      variant="outlined"
      value={confirmDeviceName}
      onChange={(e) => setConfirmDeviceName(e.target.value)}
      placeholder={selected?.name}
      autoFocus
    />
  </DialogContent>

  <DialogActions sx={{ pr: 3, pb: 2 }}>
    <Button onClick={() => setDeleteConfirmOpen(false)}>
      <Trans>Abbrechen</Trans>
    </Button>
    <Button
      onClick={handleDelete}
      disabled={confirmDeviceName !== selected?.name || isDeleting}
      sx={{
        color: "#FFFFFF",
        background: "#FF4C4C",
        "&:hover": { background: "#E84343" },
      }}
    >
      <Trans>Löschen</Trans>
    </Button>
  </DialogActions>
</Dialog>


    </Box>
  );
};

export default LorawanGatewayTable;
