import { Button, buttonVariants } from "@/components/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle, DrawerTrigger } from "@/components/ui/drawer";
import { useViewportFlags } from "@/hooks/useMobile";
import { buildDirectionsOptions, type DirectionsProvider } from "@/lib/mapDirections";
import type { VariantProps } from "class-variance-authority";
import { ChevronDown, Compass, ExternalLink, Globe, MapPinned, Navigation, Route, Smartphone } from "lucide-react";

type DirectionsMenuProps = {
  latitude?: number | null;
  longitude?: number | null;
  destinationLabel?: string | null;
  travelMode?: "driving" | "walking" | "bicycling" | "transit";
  label?: string;
  align?: "start" | "center" | "end";
  buttonVariant?: VariantProps<typeof buttonVariants>["variant"];
  buttonSize?: VariantProps<typeof buttonVariants>["size"];
  className?: string;
  providerLabels?: Partial<Record<DirectionsProvider, string>>;
  usageContext?: "generic" | "public" | "admin-logistics" | "directory";
};

function getDirectionsCopy(usageContext: NonNullable<DirectionsMenuProps["usageContext"]>) {
  switch (usageContext) {
    case "public":
      return {
        triggerLabel: "Rejoindre l’association",
        drawerTitle: "Rejoindre l’association",
        drawerDescription: "Choisis l’application la plus pratique selon ton appareil pour rejoindre cette association.",
        desktopLabel: "Choisir l’application",
      };
    case "admin-logistics":
      return {
        triggerLabel: "Aller sur le terrain",
        drawerTitle: "Aller sur le terrain",
        drawerDescription: "Choisis l’application de navigation la plus adaptée pour rejoindre ce point logistique.",
        desktopLabel: "Choisir l’application",
      };
    case "directory":
      return {
        triggerLabel: "Ouvrir le point",
        drawerTitle: "Ouvrir le point",
        drawerDescription: "Choisis une app de navigation pour ouvrir ce point sans quitter le repère métier.",
        desktopLabel: "Choisir l’application",
      };
    default:
      return {
        triggerLabel: "Ouvrir avec",
        drawerTitle: "Ouvrir l’itinéraire",
        drawerDescription: "Choisis l’application la plus pratique selon ton appareil pour rejoindre ce point.",
        desktopLabel: "Choisir l’application",
      };
  }
}

function getPlatformDirectionsOrder(isMobile: boolean) {
  if (typeof window === "undefined") {
    return ["google", "apple", "waze"] as DirectionsProvider[];
  }

  const userAgent = window.navigator.userAgent.toLowerCase();
  const isAppleMobile = /iphone|ipad|ipod/.test(userAgent);
  const isAndroidMobile = /android/.test(userAgent);

  if (isMobile && isAppleMobile) {
    return ["apple", "google", "waze"] as DirectionsProvider[];
  }

  if (isMobile && isAndroidMobile) {
    return ["google", "waze", "apple"] as DirectionsProvider[];
  }

  return ["google", "apple", "waze"] as DirectionsProvider[];
}

function getDirectionsIcon(provider: DirectionsProvider) {
  switch (provider) {
    case "apple":
      return Compass;
    case "waze":
      return Route;
    default:
      return Navigation;
  }
}

function getDirectionsSubtitle(provider: DirectionsProvider, isMobile: boolean) {
  if (provider === "apple") {
    return isMobile ? "Ouvrir dans l’app native Apple Plans" : "Ouvrir dans Apple Plans";
  }
  if (provider === "google") {
    return isMobile ? "Ouvrir dans l’app native Google Maps" : "Ouvrir dans Google Maps";
  }
  return isMobile ? "Ouvrir dans l’app native Waze" : "Ouvrir dans Waze";
}

function getDirectionsPlatformMeta(provider: DirectionsProvider, isMobile: boolean) {
  if (provider === "apple") {
    return {
      label: isMobile ? "iPhone / iPad" : "Apple",
      Icon: Smartphone,
    };
  }

  if (provider === "google") {
    return {
      label: isMobile ? "Android & web" : "Web & mobile",
      Icon: Globe,
    };
  }

  return {
    label: isMobile ? "Trafic en direct" : "Navigation",
    Icon: Route,
  };
}

export function DirectionsMenu({
  latitude,
  longitude,
  destinationLabel,
  travelMode = "driving",
  label = "Ouvrir avec",
  align = "start",
  buttonVariant = "outline",
  buttonSize = "sm",
  className,
  providerLabels,
  usageContext = "generic",
}: DirectionsMenuProps) {
  const { isMobile } = useViewportFlags();
  const copy = getDirectionsCopy(usageContext);
  const options = buildDirectionsOptions({
    latitude,
    longitude,
    destinationLabel,
    travelMode,
  }).map((option) => ({
    ...option,
    label: providerLabels?.[option.provider] || option.label,
  }));
  const orderedProviders = getPlatformDirectionsOrder(isMobile);
  const orderedOptions = [...options].sort(
    (left, right) => orderedProviders.indexOf(left.provider) - orderedProviders.indexOf(right.provider)
  );

  if (orderedOptions.length === 0) {
    return null;
  }

  const trigger = (
    <Button type="button" variant={buttonVariant} size={buttonSize} className={className}>
      <MapPinned className="mr-2 h-4 w-4" />
      {label || copy.triggerLabel}
      <ChevronDown className="ml-2 h-4 w-4" />
    </Button>
  );

  if (isMobile) {
    return (
      <Drawer>
        <DrawerTrigger asChild>{trigger}</DrawerTrigger>
        <DrawerContent className="max-h-[82vh] rounded-t-3xl border-slate-200">
          <DrawerHeader className="border-b border-slate-100 px-4 pb-4 text-left">
            <DrawerTitle className="text-base">{copy.drawerTitle}</DrawerTitle>
            <DrawerDescription>
              {copy.drawerDescription}
            </DrawerDescription>
          </DrawerHeader>
          <div className="space-y-2 px-4 py-4">
            {orderedOptions.map((option, index) => {
              const OptionIcon = getDirectionsIcon(option.provider);
              const PlatformIcon = getDirectionsPlatformMeta(option.provider, true).Icon;
              const platformLabel = getDirectionsPlatformMeta(option.provider, true).label;

              return (
              <a
                key={option.provider}
                href={option.href}
                target="_blank"
                rel="noopener noreferrer"
                className="flex min-h-16 items-center justify-between rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm font-medium text-slate-900 shadow-sm transition-colors hover:border-primary/30 hover:bg-slate-50"
              >
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-primary/10 text-primary">
                    <OptionIcon className="h-4 w-4" />
                  </div>
                  <div className="space-y-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p>{option.label}</p>
                      {index === 0 && (
                        <span className="rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-semibold text-primary">
                          Recommandé
                        </span>
                      )}
                    </div>
                    <p className="text-xs font-normal text-slate-500">
                      {getDirectionsSubtitle(option.provider, true)}
                    </p>
                    <div className="flex flex-wrap items-center gap-2 pt-0.5">
                      <span className="inline-flex items-center gap-1 rounded-full border border-slate-200 bg-slate-50 px-2 py-0.5 text-[11px] font-medium text-slate-600">
                        <PlatformIcon className="h-3 w-3" />
                        {platformLabel}
                      </span>
                    </div>
                  </div>
                </div>
                <ExternalLink className="h-4 w-4 text-slate-400" />
              </a>
              );
            })}
          </div>
        </DrawerContent>
      </Drawer>
    );
  }

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        {trigger}
      </DropdownMenuTrigger>
      <DropdownMenuContent align={align} className="min-w-[220px]">
        <DropdownMenuLabel>{copy.desktopLabel}</DropdownMenuLabel>
        <DropdownMenuSeparator />
        {orderedOptions.map((option) => {
          const OptionIcon = getDirectionsIcon(option.provider);
          const platformMeta = getDirectionsPlatformMeta(option.provider, false);
          const PlatformIcon = platformMeta.Icon;

          return (
          <DropdownMenuItem asChild key={option.provider}>
            <a href={option.href} target="_blank" rel="noopener noreferrer" className="flex items-center justify-between gap-3">
              <span className="flex items-center gap-2">
                <OptionIcon className="h-4 w-4 text-slate-500" />
                <span>{option.label}</span>
              </span>
              <span className="inline-flex items-center gap-1 rounded-full bg-slate-100 px-2 py-0.5 text-[11px] font-medium text-slate-500">
                <PlatformIcon className="h-3 w-3" />
                {platformMeta.label}
              </span>
            </a>
          </DropdownMenuItem>
          );
        })}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
