"use client";
import { MapContainer, TileLayer, Marker, Polyline, Popup, CircleMarker } from "react-leaflet";
import L, { LatLngTuple,  } from "leaflet";
import "leaflet/dist/leaflet.css";
import { FC } from "react";
import { useSettings } from "@/utils/settings";

// Fix default marker icon for users
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
    iconRetinaUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png",
    iconUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png",
    shadowUrl: "https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png",
});

// Create blue marker icon for active clients
const blueIcon = new L.Icon({
    iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-blue.png",
    shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowSize: [41, 41]
});

// Create red marker icon for inactive clients
const redIcon = new L.Icon({
    iconUrl: "https://raw.githubusercontent.com/pointhi/leaflet-color-markers/master/img/marker-icon-red.png",
    shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
    iconSize: [25, 41],
    iconAnchor: [12, 41],
    popupAnchor: [1, -34],
    shadowSize: [41, 41]
});

type Client = {
    id: string;
    location: [number, number];
    info?: {
        name?: string,
        status?: string,
        address?: string,
        phone?: string
    }
};

type OLTDevice = {
    id: string;
    location: [number, number];
    color: string;
    client: Client[];
    info?: {
        name?: string,
        status?: string,
        type?: string,
    }
};

const oltData: OLTDevice[] = [
    {
        id: "olt1",
        info: {
            name: "OLT-1"
        },
        location: [23.8103, 90.4125],
        color: "#e74c3c",
        client: [
            { id: "u1", info: { name: "User A" }, location: [23.8123, 90.4140] },
            { id: "u2", info: { name: "User B" }, location: [23.8085, 90.4100] },
            { id: "u12", info: { name: "User W" }, location: [23.8085, 90.4109] },
            { id: "u12", info: { name: "User W" }, location: [23.8085, 90.4112] },
        ],
    },
    {
        id: "olt2",
        info: { name: "OLT-2" },
        location: [23.8203, 90.4255],
        color: "#3498db",
        client: [
            { id: "u3", info: { name: "User C" }, location: [23.8210, 90.4280] },
            { id: "u4", info: { name: "User D" }, location: [23.8190, 90.4230] },
            { id: "u9", info: { name: "User X" }, location: [23.8150, 90.4270] },
        ],
    },
    {
        id: "olt3",
        info: { name: "OLT-3" },
        location: [23.8155, 90.4175],
        color: "#2ecc71",
        client: [
            { id: "u5", info: { name: "User E" }, location: [23.8140, 90.4099] },
            { id: "u6", info: { name: "User F" }, location: [23.8150, 90.4200] },
            { id: "u7", info: { name: "User G" }, location: [23.8160, 90.4220] },
            { id: "u7", info: { name: "User G" }, location: [23.8160, 90.4100] },
            { id: "u8", info: { name: "User H" }, location: [23.8170, 90.4250] },
        ],
    },
];

type Props = {
    mapData: OLTDevice[]
    center: LatLngTuple
}

const OLTUserMap: FC<Props> = ({ mapData, center = [23.815, 90.418] }) => {
    const company = useSettings("company") ?? "";
    const address = useSettings("address") ?? ""
    return (
        <MapContainer center={center} zoom={15} style={{ height: "calc(100dvh - 200px)", width: "100%" }}>
            <TileLayer
                attribution='&copy; OpenStreetMap contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />

            {mapData && mapData?.map((olt: OLTDevice) => (
                <CircleMarker
                    key={olt.id}
                    center={olt?.location}
                    radius={10}
                    pathOptions={{ color: olt?.color, fillColor: olt?.color, fillOpacity: 1 }}
                >
                    <Popup>
                        {olt?.info?.name && (
                            <div>
                                Device: {olt?.info?.name}
                            </div>
                        )}
                    </Popup>
                </CircleMarker>
            ))}

            {mapData?.length > 1 && (
                <>
                    {mapData?.map((olt) => (
                        <div key={olt.id}>
                            <CircleMarker center={center} pathOptions={{ color: "green" }} radius={20}>
                                <Popup>
                                    <div className="text-lg font-semibold">Company: {company}</div>
                                    <div>Address: {address}</div>
                                </Popup>
                            </CircleMarker>
                            <Polyline
                                positions={[center, olt?.location]}
                                pathOptions={{ color: "#666", dashArray: "5,5", weight: 3 }}
                            />
                        </div>
                    ))}
                </>
            )}

            {mapData?.map((olt) =>
                olt?.client?.map((client) => (
                    <div key={client.id}>
                        <Marker 
                            position={client.location}
                            icon={client?.info?.status === "active" ? blueIcon : redIcon}
                        >
                            <Popup>
                                {client?.info?.name && (
                                    <div className={`font-semibold text-sm ${client?.info?.status === "active" ? "text-green-500" : "text-red-500"}`}>
                                        Client: {client.info.name}
                                    </div>
                                )}
                                {client?.info?.status && (
                                    <div className={`font-semibold text-sm ${client?.info?.status === "active" ? "text-green-500" : "text-red-500"}`}>
                                        Status: {client.info.status}
                                    </div>
                                )}
                                {client?.info?.address && (
                                    <div className={`font-semibold text-sm ${client?.info?.status === "active" ? "text-green-500" : "text-red-500"}`}>
                                        Address: {client.info.address}
                                    </div>
                                )}
                                {client?.info?.phone && (
                                    <div className={`font-semibold text-sm ${client?.info?.status === "active" ? "text-green-500" : "text-red-500"}`}>
                                        Phone: {client.info.phone}
                                    </div>
                                )}
                            </Popup>
                        </Marker>
                        <Polyline
                            positions={[olt.location, client.location]}
                            pathOptions={{ color: olt.color, weight: 3 }}
                        />
                    </div>
                ))
            )}
        </MapContainer>
    );
};

export default OLTUserMap;
