import * as am5 from "@amcharts/amcharts5";
import * as am5map from "@amcharts/amcharts5/map";
import Animated from "@amcharts/amcharts5/themes/Animated";
import Responsive from "@amcharts/amcharts5/themes/Responsive";
import worldLow from "@amcharts/amcharts5-geodata/worldLow";

import type { components } from "../types.js";
import { launchWs } from "./mapWebsocket.js";

type Loc = components["schemas"]["Location"];
declare module "@amcharts/amcharts5/map" {
	interface IMapChartEvents {
		ready: {};
	}
}



function makeBullet(root: am5.Root, pointSeries: am5map.MapPointSeries) {
	var circleTemplate = am5.Template.new<am5.Circle>({});
	const container = am5.Container.new(root, {})


	const circle: am5.Circle = container.children.push(am5.Circle.new(
		root,
		{
			interactive: true,
			radius: 6,
			stroke: am5.color("#ffffff"),
			tooltipText: "{name}",
			fill: pointSeries.get("fill"),
			shadowColor: am5.color(0x000000),
			shadowBlur: 5,
			shadowOffsetX: 0,
			shadowOffsetY: 2,
			shadowOpacity: 0.3
		},
		circleTemplate,
	))


	circle.adapters.add("fill", (fill, target) => {
		const data = target.dataItem?.dataContext as Loc;
		return data?.enabled ? am5.color("#5B8B48") : am5.color("#DC602E");
	});

	circle.states.create("hover", {
		fill: am5.color(0x00ff00)
	});

	const bullet = am5.Bullet.new(root, {
		sprite: container,
	});


	return bullet;
}

function buildChart(root: am5.Root) {
	const chart = root.container.children.push(
		am5map.MapChart.new(root, {
			projection: am5map.geoMercator(),
			minZoomLevel: 2,
			maxZoomLevel: 20,
		}),
	);


	chart.chartContainer.set("background", am5.Rectangle.new(root, {
		fill: am5.color("#05A8AA"),
		fillOpacity: 1
	}));


	return chart
}

async function getLocations(): Promise<Loc[]> {
	const res = await fetch("/map/locations");
	return res.json();
}
let root: am5.Root;

document.body.addEventListener("htmx:load", async (evt) => {
	console.log("HEY")
	if (document.getElementById("chartdiv") !== null) {
		if (root) {
			root.dispose()
		}
		root = am5.Root.new("chartdiv");
		const tooltipTheme = am5.Theme.new(root);

		tooltipTheme.rule("Tooltip").setAll({
			getFillFromSprite: false,
			autoTextColor: false,
			paddingTop: 4,
			paddingBottom: 4,
			paddingLeft: 8,
			paddingRight: 8,
			marginBottom: 8,
		});

		tooltipTheme.rule("Label", ["tooltip"]).setAll({
			fill: am5.color("#000000"),
			fontSize: 16,
			fontWeight: "400",
			fontFamily: "Frama"
		});

		tooltipTheme.rule("RoundedRectangle", ["tooltip", "background"]).setAll({
			fill: am5.color("#000000"),
			fillOpacity: 1,
			cornerRadiusTL: 6,
			cornerRadiusTR: 6,
			cornerRadiusBL: 6,
			cornerRadiusBR: 6,
			shadowColor: am5.color(0x000000),
			shadowBlur: 8,
			shadowOffsetX: 0,
			shadowOffsetY: 2,
			shadowOpacity: 0.15,
		});

		root.setThemes([
			Animated.new(root),
			Responsive.new(root),
			tooltipTheme,
		]);


		const chart = buildChart(root)

		const polygonSeries = chart.series.push(
			am5map.MapPolygonSeries.new(root, {
				geoJSON: worldLow,
				fill: am5.color("#F2D0A4"),
				stroke: am5.color("#545E75")
			}),
		);

		var pointSeries = chart.series.push(
			am5map.MapPointSeries.new(root, {
				latitudeField: "lat",
				longitudeField: "long",
			}),
		);

		pointSeries.bullets.push(() => { return makeBullet(root, pointSeries) });

		const locs = await getLocations();

		pointSeries.data.setAll(
			locs.map((loc) => {
				return {
					long: loc.long,
					lat: loc.lat,
					name: loc.name,
					enabled: loc.enabled,
				};
			}),
		);

		chart.zoomToGeoPoint(
			{
				longitude: 10,
				latitude: 52,
			},
			3.5,
		);

		const label = am5.Label.new(root, {
			text: "+1",
			fontWeight: "bold",
			centerX: am5.percent(50),
			centerY: am5.percent(50),
			dy: 0,
			opacity: 1
		});

		launchWs(pointSeries, locs, label);
		await fetch("/cards/test_new")
	}
})
