import { useProfiles } from "@/hooks/useProfiles";
import { usePrefetchProfile } from "@/hooks/useXtreamData";
import { xtreamApi } from "@/lib/xtream";
import { m3uApi } from "@/lib/m3u";
import { stalkerApi, isValidMac } from "@/lib/stalker";
import { toast } from "sonner";
import type { AddServerData } from "@/components/AddServerDialog";
import type { XtreamProfile } from "@/types/xtream";

export const useConnectProfile = () => {
  const { addProfile, setActiveProfileId } = useProfiles();
  const prefetch = usePrefetchProfile();

  return async (data: AddServerData): Promise<XtreamProfile | null> => {
    const loadingId = toast.loading(`Connecting to ${data.name}...`);
    try {
      const profile: Omit<XtreamProfile, "id"> = {
        name: data.name,
        kind: data.kind,
        target: data.target || "all",
        serverUrl: data.serverUrl,
        username: data.username,
        password: data.password,
        m3uUrl: data.m3uUrl,
        m3uContent: data.m3uContent,
        portalUrl: data.portalUrl,
        macAddress: data.macAddress,
      };

      // Validate per-kind
      if (data.kind === "xtream") {
        await xtreamApi.authenticate(profile as XtreamProfile);
      } else if (data.kind === "m3u") {
        const hasContent = !!(data.m3uContent && data.m3uContent.trim().length);
        const entries = hasContent
          ? m3uApi.parsePlaylistText(data.m3uContent!)
          : await m3uApi.fetchPlaylist(data.m3uUrl!);
        if (!entries.length) throw new Error("Empty playlist");
      } else if (data.kind === "stalker") {
        if (!data.portalUrl) throw new Error("Portal URL is required");
        if (!data.macAddress || !isValidMac(data.macAddress)) {
          throw new Error("MAC must be in 00:1A:79:XX:XX:XX format");
        }
        const hs = await stalkerApi.handshake(data.portalUrl, data.macAddress);
        if (hs.profile.blocked)
          throw new Error("This MAC is blocked on the portal");
      }

      const created = addProfile(profile);
      setActiveProfileId(created.id);

      toast.loading("Loading channels, movies & series...", { id: loadingId });
      const all = await prefetch(created);
      toast.success(
        `Connected! ${all.channels.length} channels • ${all.movies.length} movies • ${all.series.length} series`,
        { id: loadingId },
      );
      return created;
    } catch (e: any) {
      toast.error(`Failed: ${e.message || "Connection error"}`, {
        id: loadingId,
      });
      return null;
    }
  };
};
